主頁 > 後端開發 > 3. 投票 案例專案(合集)

3. 投票 案例專案(合集)

2023-02-19 07:02:26 後端開發

3.投票-1創建專案和子應用

創建專案

  • 命令
    $ python django-admin startproject mysite
    
  • 目錄結構
    
    
    mysite/               # 專案容器、可任意命名
        manage.py         # 命令列工具
        mysite/           # 純 Python 包 # 你參考任何東西都要用到它
            __init__.py   # 空檔案 告訴Python這個目錄是Python包
            settings.py   # Django 專案組態檔
            urls.py       # URL 宣告  # 就像網站目錄
            asgi.py       # 部署時用的配置 # 運行在ASGI兼容的Web服務器上的 入口
            wsgi.py       # 部署時用的配置 # 運行在WSGI兼容的Web服務器上的 
    
    
  • 初始化資料庫 遷移
    $ python mangae.py makemigrations
    
    $ python manage.py migrate
    

Django 簡易服務器

  • 用于開發使用,Django 在網路框架方面很NB, 但在網路服務器方面不行~

    專業的事讓專業的程式做嘛,最后部署到 Nginx Apache 等專業網路服務器上就行啦,

  • 自動重啟服務器

    對每次訪問請求、重新載入一遍 Python 代碼

    新添加檔案等一些操作 不會觸發重啟

  • 命令

    $ python manage.py runserver
    
    E:\PYTHON\0CODE\mysite>
    E:\PYTHON\0CODE\mysite>python manage.py runserver
    Watching for file changes with StatReloader
    Performing system checks...
    
    System check identified no issues (0 silenced).
    June 29, 2022 - 22:35:10
    Django version 4.0.5, using settings 'mysite.settings'
    Starting development server at http://127.0.0.1:8000/
    Quit the server with CTRL-BREAK.
    
  • 指定埠

    $ python manage.py runserver 8080
    

創建應用


  • 命令
    $ python manage.py startapp polls
    
  • 目錄結構
    polls/
        __init__.py
        admin.py
        apps.py
        migrations/
            __init__.py
        models.py
        tests.py
        views.py
    

撰寫應用視圖

  • 視圖函式
    # polls/views.py
    
    from django.shortcuts import render
    
    # Create your views here.
    
    from django.http import HttpRespose
    
    
    def index(rquest):
    
        return HttpResponse("投票應用 -首頁")
    

配置路由

  • 配置路由

    # polls/urls.py  子應用路由
    
    from django.urls import path
    
    from . import views
    
    urlpatterns = [
        path('', views.index, name='index'),
    ]
    
    # mysite/urls.py  全域路由 include()即插即用
    
    from django.contrib import admin
    from django.urls import include, path
    
    urlpatterns = [
        path('polls/', include('polls.urls')),
        path('admin/', admin.site.urls),
    ]
    
  • 效果

    截圖



path() 引數含義


path('', views.index, name='index'),
path('polls/', include('polls.urls'))
  • route 路徑

    一個匹配URL的規則,類似正則運算式,不匹配GET、POST傳參 、域名

  • view 視圖函式

     Django 呼叫這個函式,默認傳給函式一個 HttpRequest 引數
    
  • kwargs 視圖函式引數

    字典格式

  • name 給這條URL取一個溫暖的名子~

    可以在 Django 的任意地方唯一的參考,允許你只改一個檔案就能全域地修改某個 URL 模式,

3.投票-2本地化和資料庫API

本地化配置

  • 時區和語言

    # mysite/mysite/settings.py
    
    # Internationalization
    # https://docs.djangoproject.com/en/4.0/topics/i18n/
    
    LANGUAGE_CODE = 'zh-hans'   # 'en-us'
    
    TIME_ZONE = 'UTC'
    
    USE_I18N = True
    
    USE_TZ = True
    
    
  • 為啥要在資料庫之前?

    配置時區,資料庫可以以此做相應配置,比如時間的存放是以UTC還是本地時間...


資料庫配置

  • django 支持 sqlite mysql postgresql oracle
  • 默認是sqlite 它是本地的一個檔案name 哪里直接寫了檔案的絕對路徑
    # mysite/mysite/settings.py
    
    # Database
    # https://docs.djangoproject.com/en/4.0/ref/settings/#databases
    
    DATABASES = {
        'default': {
            'ENGINE': 'django.db.backends.sqlite3',
            'NAME': BASE_DIR / 'db.sqlite3',
        }
    }
    
    
  • 遷移 主要為Django默認的模型建表
    python manage.py migrate
    

創建模型


  • 撰寫

    # mysite/polls/models.py
    
    from django.db import models
    
    
    class Question(models.Model):
        question_text = models.CharField(max_length=200)
        pub_date = models.DateTimeField('date published')
    
    
    class Choice(models.Model):
        question = models.ForeignKey(Question, on_delete=models.CASCADE)
        choice_text = models.CharField(max_length=200)
        votes = models.IntegerField(default=0)
    
  • 很多資料庫的知識 都可以用到里面

    Question Choice 類都是基于models.Model, 是它的子類,

    類的屬性--------表的欄位

    類名-----------表名

    還有pub_date on_delete=models.CASCAD 級聯洗掉, pub_date 的欄位描述, vo tes的默認值, 都和資料庫很像,

    而且max_length這個個欄位,讓Django可以在前端自動校驗我們的資料

激活模型


  • 把配置注冊到專案

    # mysite/mysite/settings.py
    
    # Application definition
    
    INSTALLED_APPS = [
        'polls.apps.PollsConfig',
    
        'django.contrib.admin',
        'django.contrib.auth',
        'django.contrib.contenttypes',
        'django.contrib.sessions',
        'django.contrib.messages',
        'django.contrib.staticfiles',
    ]
    
  • 做遷移-

    僅僅把模型的配置資訊轉化成 Sql 語言

    (venv) E:\PYTHON\0CODE\mysite>python manage.py makemigrations polls
    Migrations for 'polls':
      polls\migrations\0001_initial.py
        - Create model Question
        - Create model Choice
    

    查看 Sql 語言 (對應我們配的 Sqlite 資料庫的語法)

(venv) E:\PYTHON\0CODE\mysite>python manage.py sqlmigrate polls 0001
BEGIN;
--
  -- Create model Question
  --
  
  CREATE TABLE "polls_question" ("id" integer NOT NULL PRIMARY KEY AUTOINCREMENT, "question_text" varchar(200) NOT NULL, "pub_data" datetime NOT NULL
);
--
  -- Create model Choice
  --
  
  CREATE TABLE "polls_choice" ("id" integer NOT NULL PRIMARY KEY AUTOINCREMENT, "choice_text" varchar(200) NOT NULL, "votes" integer NOT NULL, "quest
ion_id" bigint NOT NULL REFERENCES "polls_question" ("id") DEFERRABLE INITIALLY DEFERRED);
CREATE INDEX "polls_choice_question_id_c5b4b260" ON "polls_choice" ("question_id");
COMMIT;
  

  • 執行遷移
    (venv) E:\PYTHON\0CODE\mysite>python manage.py migrate
    Operations to perform:
      Apply all migrations: admin, auth, contenttypes, polls, sessions
    Running migrations:
      Applying polls.0001_initial... OK
    
    (venv) E:\PYTHON\0CODE\mysite>
    
    

API 的初體驗


  • 進入shell
    python manage.py shell
    

  • - (venv) E:\PYTHON\0CODE\mysite>python manage.py shell
    Python 3.9.1 (tags/v3.9.1:1e5d33e, Dec  7 2020, 17:08:21) [MSC v.1927 64 bit (AMD64)] on win32
    Type "help", "copyright", "credits" or "license" for more information.
    (InteractiveConsole)
    >>>
    >>> from polls.models import Question, Choice
    >>> from django.utils import timezone
    >>>
    >>> q = Question( question_text = "what's up ?", pub_date=timezone.now() )
    >>>
    >>> q.save()
    >>>
    
    
  • 查看欄位
    >>> q.id
    1
    >>> q.question_text
    "what's up ?"
    >>>
    >>> q.pub_date
    datetime.datetime(2022, 7, 6, 5, 46, 10, 997140, tzinfo=datetime.timezone.utc)
    >>>
    
  • >>> q.question_text = 'are you kidding me ?'
    >>> q.save()
    >>>
    >>> q.question_text
    'are you kidding me ?'
    >>>
    
    >>>
    >>>
    >>> Question.objects.all()
    <QuerySet [<Question: Question object (1)>]>
    >>>
    >>>
    

下面寫點更人性化的方法


  • __str__方法

    默認列印自己的text欄位,便于查看

    后臺展示物件資料也會用這個欄位

    class Question(models.Model):
        ...
        
        def __str__(self):
            return self.question_text
    
    
    class Choice(models.Model):
        ...
        
        def __str__(self):
            return self.choice_text
    

  • 自定義方法
    class Question(models.Model):
        ...
    
        def was_published_recently(self):
            return self.pub_date >= timezone.now()-datetime.timedelta(days=1)
    

  • __str__方法效果

    (venv) E:\PYTHON\0CODE\mysite>python manage.py shell
    Python 3.9.1 (tags/v3.9.1:1e5d33e, Dec  7 2020, 17:08:21) [MSC v.1927 64 bit (AMD64)] on win32
    Type "help", "copyright", "credits" or "license" for more information.
    (InteractiveConsole)
    >>>
    >>> from polls.models import Question, Choice
    >>>
    >>> Question.objects.all()
    <QuerySet [<Question: are you kidding me ?>]>
    >>>
    >>> Question.objects.filter(id=1)
    <QuerySet [<Question: are you kidding me ?>]>
    >>>
    
    
  • 按屬性查

    
    >>>
    >>> Question.objects.filter(question_text__startswith='are')
    <QuerySet [<Question: are you kidding me ?>]>
    >>>
    
    
    >>> from django.utils import timezone
    >>>
    >>> current_year = timezone.now().year
    >>> Question.objects.get(pub_date__year=current_year)
    <Question: are you kidding me ?>
    >>>
    
    
    >>> Question.objects.get(id=2)
    Traceback (most recent call last):
      File "<console>", line 1, in <module>
      File "E:\PYTHON\0CODE\StudyBuddy\venv\lib\site-packages\django\db\models\manager.py", line 85, in manager_method
        return getattr(self.get_queryset(), name)(*args, **kwargs)
      File "E:\PYTHON\0CODE\StudyBuddy\venv\lib\site-packages\django\db\models\query.py", line 496, in get
        raise self.model.DoesNotExist(
    polls.models.Question.DoesNotExist: Question matching query does not exist.
    >>>
    >>>
    
  • 更多操作

    用pk找更保險一些,有的model 不以id 為主鍵

    >>> Question.objects.get(pk=1)  
    <Question: are you kidding me ?>
    >>>
    # 自定義查找條件
    >>> q = Question.objects.get(pk=1)
    >>> q.was_published_recently()
    True
    >>>
    
    # 安主鍵獲取物件
    >>> q = Question.objects.get(pk=1)
    >>> q.choice_set.all()
    <QuerySet []>
    >>>
    
    # 增  問題物件關系到選項物件
    >>> q.choice_set.create(choice_text='Not much', votes=0)
    <Choice: Not much>
    >>>
    >>> q.choice_set.create(choice_text='The sky', votes=0)
    <Choice: The sky>
    >>>
    >>> q.choice_st.create(choice_text='Just hacking agin', votes=0)
    Traceback (most recent call last):
      File "<console>", line 1, in <module>
    AttributeError: 'Question' object has no attribute 'choice_st'
    >>>
    >>> q.choice_set.create(choice_text='Just hacking agin', votes=0)
    <Choice: Just hacking agin>
    >>>
    >>>
    >>> c = q.choice_set.create(choic_text='Oh my god.', votes=0)
    Traceback (most recent call last):
      File "<console>", line 1, in <module>
      File "E:\PYTHON\0CODE\StudyBuddy\venv\lib\site-packages\django\db\models\fields\related_descriptors.py", line 747, in create
        return super(RelatedManager, self.db_manager(db)).create(**kwargs)
      File "E:\PYTHON\0CODE\StudyBuddy\venv\lib\site-packages\django\db\models\manager.py", line 85, in manager_method
        return getattr(self.get_queryset(), name)(*args, **kwargs)
      File "E:\PYTHON\0CODE\StudyBuddy\venv\lib\site-packages\django\db\models\query.py", line 512, in create
        obj = self.model(**kwargs)
      File "E:\PYTHON\0CODE\StudyBuddy\venv\lib\site-packages\django\db\models\base.py", line 559, in __init__
        raise TypeError(
    TypeError: Choice() got an unexpected keyword argument 'choic_text'
    >>>
    
    
    # 選項 關系 到問題
    >>> c = q.choice_set.create(choice_text='Oh my god.', votes=0)
    >>>
    >>> c.question
    <Question: are you kidding me ?>
    >>>
    >>> q.choice_set.all()
    <QuerySet [<Choice: Not much>, <Choice: The sky>, <Choice: Just hacking agin>, <Choice: Oh my god.>]>
    >>>
    >>>
    >>> q.choice_set.count()
    4
    >>>
    >>> Choice.objects.filter(question__pub_date__year=current_year)
    <QuerySet [<Choice: Not much>, <Choice: The sky>, <Choice: Just hacking agin>, <Choice: Oh my god.>]>
    >>>
    >>>
    
    
    
  • >>> c = q.choice_set.filter(choice_text__startswith='Just hacking')
    >>> c.delete()
    (1, {'polls.Choice': 1})
    >>>
    >>> q.choice_set.all()
    <QuerySet [<Choice: Not much>, <Choice: The sky>, <Choice: Oh my god.>]>
    >>>
    >>>
    

管理頁面


  • 創建用戶
    (venv) E:\PYTHON\0CODE\mysite>python manage.py createsuperuser
    
    
    用戶名: admin
    電子郵件地址: [email protected]
    Password:
    Password (again):
    密碼長度太短,密碼必須包含至少 8 個字符,
    這個密碼太常見了,
    Bypass password validation and create user anyway? [y/N]: y
    Superuser created successfully.
    
    
  • 啟動 開發服務器
    python manage.py runserver
    
  • login
    http://localhost:8000/admin/
    
  • 讓我們的polls 投票應用也展示在后臺
    # mysite/polls/admin.py
    
    
    from .models import Question, Choice
    
    admin.site.register(Question)
    admin.site.register(Choice)
    

3.投票-3模板和路由

撰寫更多視圖


# polls/views.py

...

def detail(request, question_id):
    
    return HttpResponse(f"當前問題id:{question_id}")


def results(request, question_id):
    
    return HttpResponse(f"問題id:{question_id}的投票結果")


def vote(request, question_id):
    
    return HttpResponse(f"給問題id:{question_id}投票")


添加url

  • 全域我們已經加過
    
    urlpatterns = [
        path('admin/', admin.site.urls),
        path('polls/', include('polls.urls')),
        
    ]
    

  • 應用程式添加如下
    # polls/urls.py
    
    from django.urls import path
    
    from . import views
    
    urlpatterns = [
        path('', views.index, name='index'),
    
        path('<int:question_id>/', views.detail, name='detail'),
    
        path('<int:question_id>/results/', views.results, name='results'),
    
        path('<int:question_id>/vote/', views.vote, name='vote'),
    ]
    

看看效果

  • path 里的引數很敏感 結尾含/ 的訪問時也必須含 / 否則404


image

image

image

image

  • 以 /polls/1/ 為例分析匹配程序

    • 從mysite/settings.py 載入 ROOT_URLCONF = 'mysite.urls'
    • 從urls.py 的“polls/”匹配到 polls/ 載入 polls.urls
    • 從polls/urls.py 的“int:question_id/”匹配到 1/ ,獲取int型的 1 轉發給視圖函式 views.details


升級index 視圖 展示近期5個投票問題

  • 撰寫視圖

    def index(request):
        latest_question_list = Question.objects.order_by('-pub_date')[:5]
        output = ','.join([q.question_text for q  in latest_question_list])
    
        return HttpResponse(output)
    
  • 好吧,總共就一個
    image

  • 加點

image


這里直接把頁面內容,寫到了視圖函式里,寫死的,很不方便,下面用模板檔案來處理這個問題


模板檔案

  • 創建polls存放 模板檔案的 檔案夾 為什么里面多套了一層polls?沒看出他有區分的作用,第一個polls不已經區分過了?
    polls/templates/polls/
    
  • 主要內容
    # polls/templates/polls/index.html
    
    {% if latest_question_list %}
      <ul>
        {% for question in latest_question_list %}
            <li>
              <a href="https://www.cnblogs.com/polls/{{ question.id }}/">{{question.question_text}}</a>
            </li>
        {% endfor %}
      </ul>
    {% else %}
        <p>暫時沒有開放的投票,</p>
    {% endif %}
    

  • 修改視圖函式

    這里函式載入index.html模本,還傳給他一個背景關系字典context,字典把模板里的變數映射成了Python 物件

    # polls/views.py
    
    ...
    from django.template import loader
    
    
    def index(request):
        latest_question_list = Question.objects.order_by('-pub_date')[:5]
    
        template = loader.get_template('polls/index.html')
        context = {
            'latest_question_list': latest_question_list,
        }
    
        return HttpResponse(template.render(context, request))
        
    ...
    
  • 效果

image


  • 快捷函式 render()

    上面的視圖函式用法很普遍,有種更簡便的函式替代這一程序

    # polls/views.py
    ...
    from django.template import loader
    
    import django.shortcuts import render
    
    def index(request):
        latest_question_list = Question.objects.order_by('-pub_date')[:5]
    
        #template = loader.get_template('polls/index.html')
        context = {
            'latest_question_list': latest_question_list,
        }
    
        #return HttpResponse(template.render(context, request))
        return render(request, 'polls/index.html', context)
        
    ...
    

優雅的拋出 404

  • 修改 detail 視圖函式

    # polls/views.py
    
    ...
    
    def detail(request, question_id):
        try:
            question = Question.objects.get(pk=question_id)
    
        except:
            raise Http404("問題不存在 !")
    
        # return HttpResponse(f"當前問題id:{question_id}")
        return render(request, 'polls/detail.html', {'question': question})
    
    
  • 撰寫模板

    # polls/templates/polls/detail.html
    
    
    {{ question }}
    
    
  • 效果
    image

  • 快捷函式 get_object_or_404()

    # polls/views.py
    from django.shortcuts import render, get_object_or_404
    
    ...
    
    def detail(request, question_id):
        
        question = get_object_or_404(Question, pk=question_id)
        return render(request, 'polls/detail.html', {'question': question})
    

  • 效果
    image

使用模板系統

  • 對detail.html獲取的question變數進行分解 展示
    • 模板系統用.來訪問變數屬性

    • question.question_text先對question用字典查找nobj.get(str)------>屬性查找obj.str---------->串列查找obj[int]當然在第二步就成功的獲取了question_text屬性,不在繼續進行,

    • 其中 question.choice_set.all解釋為Python代碼question.choice_set.all()


    # polls/templates/polls/detail.html
    
    <h1>{{ question.question_text }}</h1>
    <ul>
        {% for choice in question.choice_set.all %}
            <li>{{ choice.choice_text }}</li>
        {% endfor %}
    </ul>
    
  • 效果
    image


去除 index.html里的硬編碼


  • 其中的'detail' 使我們在urls.py 定義的名稱
    # polls/urls.py
    
    path('<int:question_id>/', views.detail, name='detail'),
    
    # polls/templates/polls/index.html
    
    <!--<li>-->
    <!--       <a href="https://www.cnblogs.com/polls/{{ question.id }}/">{{question.question_text}}</a>-->
    <!--</li>-->
    
    <li>
           <a href="https://www.cnblogs.com/hugboy/p/{% url'detail' question.id %}">{{question.question_text}}</a>
    </li>
    
  • 有啥用?
    • 簡單明了 書寫方便

    • 我們修改.html 的真實位置后, 只需在urls.py 同步修改一條記錄, 就會在所有模板檔案的無數個連接中生效

      大大的節省時間


為URL添加命名空間


  • 為什么?

    上面去除硬鏈接方便了我們,我們只有1個應用polls有自己的detail.html模板,但有多個應用同時有名字為detail.html的模板時呢?

    Django看到{% url %} 咋知道是哪個應用呢?

  • 怎么加 ?

    # polls/urls.py
    
    app_name = 'polls'
    
    ...
    
  • 修改.html模板檔案

    # polls/templates/polls/index.html
    
    <!--<li>-->
    <!--       <a href="https://www.cnblogs.com/polls/{{ question.id }}/">{{question.question_text}}</a>-->
    <!--</li>-->
    
    <!--<li>-->
    <!--       <a href="https://www.cnblogs.com/hugboy/p/{% url'detail' question.id %}">{{question.question_text}}</a>-->
    <!--</li>-->
    
    <li>
           <a href="https://www.cnblogs.com/hugboy/p/{% url'polls:detail' question.id %}">{{question.question_text}}</a>
    </li>
    

3.投票-4投票結果保存 和 Django通用模板

投票結果保存


前端


# polls/templates/polls/detail.html

{#<h1>{{ question.question_text }}</h1>#}
{#<ul>#}
{#    {% for choice in question.choice_set.all %}#}
{#        <li>{{ choice.choice_text }}</li>#}
{#    {% endfor %}#}
{#</ul>#}


<form action="{% url 'polls:vote' question.id %}" method="post">
    {% csrf_token %}
    <fieldset>
    
        ...
        
    </fieldset>
    <input type="submit" value="https://www.cnblogs.com/hugboy/p/投票">
</form>
# polls/templates/polls/detail.html


<form action="{% url 'polls:vote' question.id %}" method="post">
    {% csrf_token %}
    <fieldset>

        <legend><h1>{{ question.question_text }}</h1></legend>

        {% if error_message  %}
            <strong><p>{{ error_message }}</p></strong>
        {% endif %}

        {% for choice in question.choice_set.all %}
            <input type="radio" name="choice" id="choice{{ forloop.counter }}" value="https://www.cnblogs.com/hugboy/p/{{ choice.id }}">
            <label for="choice{{ forloop.counter }}">{{ choice.choice_text }}</label>
        {% endfor %}

    </fieldset>
    <input type="submit" value="https://www.cnblogs.com/hugboy/p/投票">
</form>

路由


# polls/urls.py

path('<int:question_id>/vote/', views.vote, name='vote'),



視圖

vote


# polls/views.py?

# ...

from django.http import HttpResponseRedirect
from django.urls import reverse

# ...


# def vote(request, question_id):
#     return HttpResponse(f"給問題id:{question_id}投票")

def vote(request, question_id):
    question = get_object_or_404(Question, pk=question_id)
    try:
        selected_choice = question.choice_set.get(pk=request.POST['choice'])
    except (KeyError, Choice.DoesNotExist):
        return render(request, 'polls/detail.html', {
            'question': question,
            'error_message': "選擇為空, 無法提交 !"
        })
    else:
        selected_choice.votes += 1
        selected_choice.save()
        # 重定向到其他頁面 防止誤觸重復投票
        return HttpResponse(reverse('polls:results', args=(question.id, )))


result


# polls/views.py?

from django.shortcuts import get_object_or_404, render


def results(request, question_id):
    question = get_object_or_404(Question, pk=question_id)
    return render(request, 'polls/results.html', {'question': question})


前端

新建檔案


# polls/templates/polls/results.html?

<h1>{{ question.question_text }}</h1>

<ul>
    {% for choice in question.choice_set.all %}
        <li>{{ choice.choice_text }} -- {{ choice.votes }} vote {{ choice.votes|pluralize }}</li>
    {% endfor %}
</ul>

<a href="https://www.cnblogs.com/hugboy/p/{% url'polls:detail' question.id %}">繼續投票</a>




降低冗余 URLConf

修改url

# mysite/polls/urls.py

from django.urls import path

from . import views

app_name = 'polls'

# urlpatterns = [
#
#     path('', views.index, name='index'),
#
#     path('<int:question_id>/', views.detail, name='detail'),
#
#     path('<int:question_id>/results/', views.results, name='results'),
#
#     path('<int:question_id>/vote/', views.vote, name='vote'),
#
#
# ]

urlpatterns = [
    path('', views.IndexView.as_view(), name='index'),
    path('<int:pk>/', views.DeatilView.as_view(), name='detail'),
    path('<int:pl>/results/', views.ResultsViews.as_view(), name='results'),
    path('<int:question_id>/vote/', views.vote, name='vote')
]

修改視圖

ListView 和 DetailView ,這兩個視圖分別抽象“顯示一個物件串列”和“顯示一個特定型別物件的詳細資訊頁面”這兩種概念,

每個通用視圖需要知道它將作用于哪個模型, 這由 model 屬性提供,

template_name 屬性是用來告訴 Django 使用一個指定的模板名字,而不是自動生成的默認名字,

自動生成的 context 變數是 question_list,為了覆寫這個行為,我們提供 context_object_name 屬性,表示我們想使用 latest_question_list,作為一種替換方案,

# polls/views.py

from django.urls import reverse
# ...

# def index(request):
#     latest_question_list = Question.objects.order_by('-pub_date')[:5]
#
#     template = loader.get_template('polls/index.html')
#     context = {
#         'latest_question_list': latest_question_list,
#     }
#
#     return HttpResponse(template.render(context, request))

# 用Django 通用視圖 重寫index, detail, results視圖


class IndexView(generic.ListView):
    template_name = 'polls/index.html'
    context_object_name = 'latest_question_list'
    
    def get_queryset(self):
        """回傳最近的 5 個投票問題"""
        return Question.objects.order_by('-pub_date')[:5]

    
class DetailView(generic.DetailView):
    model = Question
    template_name = 'polls/detail.html'


class ResultsView(generic.DetailView):
    model = Question
    template_name = 'polls/detail.html'
    
    

# def detail(request, question_id):
#     # try:
#     #     question = Question.objects.get(pk=question_id)
#     #
#     # except:
#     #     raise Http404("問題不存在 !")
# 
#     # return HttpResponse(f"當前問題id:{question_id}")
# 
#     question = get_object_or_404(Question, pk=question_id)
#     return render(request, 'polls/detail.html', {'question': question})
# 
# 
# # def results(request, question_id):
# #     return HttpResponse(f"問題id:{question_id}的投票結果")
# 
# def results(request, question_id):
#     question = get_object_or_404(Question, pk=question_id)
#     return render(request, 'polls/results.html', {'question': question})


# def vote(request, question_id):
#     return HttpResponse(f"給問題id:{question_id}投票")

3.投票-5自動化測驗 模型


自動化測驗


一個bug

當設定發布時間為很遠的未來的時間時,函式.was_published_recently()竟然回傳True


$ python manage.py shell

>>> import datetime
>>> from django.utils import timezone
>>> from polls.models import Question
>>> # create a Question instance with pub_date 30 days in the future
>>> future_question = Question(pub_date=timezone.now() + datetime.timedelta(days=30))
>>> # was it published recently?
>>> future_question.was_published_recently()
True



撰寫測驗用例

針對上面的bug寫個腳本,用來測驗這個bug


# polls/tests.py

import datetime

from django.test import TestCase
from django.utils import timezone

from .models import Question


class QuestionModelTests(TestCase):

    def test_was_published_recently_with_future_question(self):
        """
        was_published_recently() returns False for questions whose pub_date
        is in the future.
        """
        time = timezone.now() + datetime.timedelta(days=30)
        future_question = Question(pub_date=time)
        self.assertIs(future_question.was_published_recently(), False)


我們創建了一個 django.test.TestCase 的子類,并添加了一個方法,此方法創建一個 pub_date 時未來某天的 Question 實體,然后檢查它的 was_published_recently() 方法的回傳值——它 應該 是 False,


運行


# python manage.py test polls

(venv) E:\PYTHON\0CODE\mysite>
(venv) E:\PYTHON\0CODE\mysite>python manage.py test polls
Found 1 test(s).
Creating test database for alias 'default'...
System check identified no issues (0 silenced).
E
======================================================================
ERROR: test_was_published_recently_with_future_questsion (polls.tests.QuestionModelTests)
當日期為 未來 時間時 was_published_recently() 應該回傳 False
----------------------------------------------------------------------
Traceback (most recent call last):
  File "E:\PYTHON\0CODE\mysite\polls\tests.py", line 16, in test_was_published_recently_with_future_questsion
    time = timezone.now() + datetime.timedelta(day=30)
TypeError: 'day' is an invalid keyword argument for __new__()

----------------------------------------------------------------------
Ran 1 test in 0.001s

FAILED (errors=1)
Destroying test database for alias 'default'...

(venv) E:\PYTHON\0CODE\mysite>


image




修復Bug

限制下界為當前

# mysite/polls/models.py

#...

class Question(models.Model):
    question_text = models.CharField(max_length=200)
    pub_date = models.DateTimeField('date published')

    def __str__(self):
        return self.question_text

    # def was_published_recently(self):
    #
    #     return self.pub_date >= timezone.now()-datetime.timedelta(days=1)
    def was_published_recently(self):
        now = timezone.now()
        # 發布時間比現在小 比一天之前大 (即最近一天發布)
        return now - datetime.timedelta(days=1) <= self.pub_date <= now
        
#...


測驗其他時間段情況

class QuestionModelTests(TestCase):

    def test_was_published_recently_with_future_question(self):
        """
        當日期為 未來 時間時 was_published_recently() 應該回傳 False
        """
        time = timezone.now() + datetime.timedelta(days=30)
        future_question = Question(pub_date=time)
        self.assertIs(future_question.was_published_recently(), False)

    def test_was_published_recently_with_recent_question(self):
        """
        當日期為 最近 時間時 was_published_recently() 應該回傳 False
        """
        time = timezone.now() - datetime.timedelta(hours=23, minutes=59, seconds=59)
        future_question = Question(pub_date=time)
        self.assertIs(future_question.was_published_recently(), True)

    def test_was_published_recently_with_old_question(self):
        """
        當日期為 過去(至少一天前) 時間時 was_published_recently() 應該回傳 False
        """
        time = timezone.now() + datetime.timedelta(days=1, seconds=1)
        future_question = Question(pub_date=time)
        self.assertIs(future_question.was_published_recently(), False)

運行

Microsoft Windows [版本 10.0.22000.978]
(c) Microsoft Corporation,保留所有權利,
(venv) E:\PYTHON\0CODE\mysite>python manage.py polls test
Unknown command: 'polls'
Type 'manage.py help' for usage.

(venv) E:\PYTHON\0CODE\mysite>python manage.py test polls
Found 3 test(s).
Creating test database for alias 'default'...
System check identified no issues (0 silenced).
...
----------------------------------------------------------------------
Ran 3 tests in 0.002s

OK
Destroying test database for alias 'default'...

(venv) E:\PYTHON\0CODE\mysite>

3.投票-6自動化測驗 視圖

Client 一個工具

這個很像我之前學過的,requests

但他更細節更貼合Django的視圖,它可以直接捕獲視圖函式傳過來的引數

Microsoft Windows [版本 10.0.22000.978]
(c) Microsoft Corporation,保留所有權利,

(venv) E:\PYTHON\0CODE\mysite>python manage.py shell
Python 3.9.1 (tags/v3.9.1:1e5d33e, Dec  7 2020, 17:08:21) [MSC v.1927 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)
>>>
>>>
>>> from django.test.utils import setup_test_environment
>>>
>>> setup_test_environment()
>>>
>>>
>>> from django.test import Client
>>>
>>> client = Client()
>>>
>>> r = client.get('/')
Not Found: /
>>>
>>> r.status_code
404
>>>
>>> from django.urls import reverse
>>>
>>> r = client.get(reverse("polls:index"))
>>>
>>> r .status_code
200
>>>
>>>
>>>
>>>
>>>
>>> r.content
b'\n  <ul>\n    \n        <li>\n          <a href="https://www.cnblogs.com/polls/5/">Django is nice?</a>\n        </li>\n    \n        <li>\n          <a href="https://www.cnblogs.com/polls/4/">I love Lisa.</a>\n        </li>\n    \
n        <li>\n          <a href="https://www.cnblogs.com/polls/3/">do you lik ch best?</a>\n        </li>\n    \n        <li>\n          <a href="https://www.cnblogs.com/polls/2/">are you okay?</a>\n        </li>\n    \n        <li
>\n          <a href="https://www.cnblogs.com/polls/1/">are you kidding me ?</a>\n        </li>\n    \n  </ul>\n\n'
>>>
>>>
>>>
>>>
>>>
>>> r.context['latest_question_list']
<QuerySet [<Question: Django is nice?>, <Question: I love Lisa.>, <Question: do you lik ch best?>, <Question: are you okay?>, <Question: are you kidding me ?>]>
>>>
>>>



一個 Bug

按照邏輯,當投票發布時間是未來時,視圖應當忽略這些投票


修復 Bug


# polls/views.py

class IndexView(generic.ListView):
    template_name = 'polls/index.html'
    context_object_name = 'latest_question_list'

    def get_queryset(self):
        """回傳最近的 5 個投票問題"""
        #return Question.objects.order_by('-pub_date')[:5]
        return Question.objects.filter(pub_date__lte=timezone.now()).order_by('-pub_date')[:5]

測驗用例



寫個投票腳本,用于產生資料

# polls/test.py

def create_question(question_text, days):
    """
    一個公用的快捷函式用于創建投票問題
    """
    time = timezone.now() + datetime.timedelta(days=days)
    return Question.objects.create(question_text=question_text, pub_date=time)



測驗類


class QuestionIndexViewTests(TestCase):
    def test_no_questions(self):
        """
        不存在 questions 時候 顯示
        """
        res = self.client.get(reverse('polls:index'))
        self.assertEqual(res.status_code, 200)
        #self.assertContains(res, "沒有【正在進行】的投票,")  # 是否顯示“沒有【正在進行】的投票,”字樣
        self.assertQuerysetEqual(res.context['latest_question_list'], [])

    def test_past_question(self):
        """
        發布時間是 past 的 question 顯示到首頁
        """
        question = create_question(question_text="Past question.", days=-30)
        res = self.client.get(reverse("polls:index"))
        self.assertQuerysetEqual(
            res.context['latest_question_list'],
            [question],
        )

    def test_future_question(self):
        """
        發布時間是 future 不顯示
        """
        create_question(question_text="未來問題!", days=30)
        res = self.client.get(reverse('polls:index'))
        #self.assertContains(res, "沒有【可用】的投票")
        self.assertQuerysetEqual(res.context['latest_question_list'], [])

    def test_future_question_and_past_question(self):
        """
        存在 past 和 future 的 questions 僅僅顯示 past
        """
        question = create_question(question_text="【過去】問題!", days=-30)
        create_question(question_text="【未來】問題!", days=30)
        response = self.client.get(reverse('polls:index'))
        self.assertQuerysetEqual(
            response.context['latest_question_list'],
            [question],
        )

    def test_two_past_question(self):
        """
        首頁可能展示 多個 questions
        """
        q1 = create_question(question_text="過去 問題 1", days=-30)
        q2 = create_question(question_text="過去 問題 2", days=-5)
        res = self.client.get(reverse('polls:index'))
        self.assertQuerysetEqual(
            res.context['latest_question_list'],
            [q2, q1],
        )


運行


(venv) E:\PYTHON\0CODE\mysite>
(venv) E:\PYTHON\0CODE\mysite>python manage.py test polls
Found 8 test(s).
Creating test database for alias 'default'...
System check identified no issues (0 silenced).
........
----------------------------------------------------------------------
Ran 8 tests in 0.030s

OK
Destroying test database for alias 'default'...

(venv) E:\PYTHON\0CODE\mysite>

3.投票-7自動化測驗 業務邏輯

一個bug

發布日期時未來的那些投票不會在目錄頁 index 里出現,但是如果用戶知道或者猜到正確的 URL ,還是可以訪問到它們,所以我們得在 DetailView 里增加一些約束:


修復

加強限制,搜尋結果只回傳時間小于當前的投票

# polls/views.py

class DetailView(generic.DetailView): 
    ...
    def get_queryset(self):
        """
        Excludes any questions that aren't published yet.
        """
        return Question.objects.filter(pub_date__lte=timezone.now())

測驗用例

檢驗

# polls/tests.py

class QuestionDetailViewTests(TestCase):
    def test_future_question(self):
        """
        The detail view of a question with a pub_date in the future
        returns a 404 not found.
        """
        future_question = create_question(question_text='Future question.', days=5)
        url = reverse('polls:detail', args=(future_question.id,))
        response = self.client.get(url)
        self.assertEqual(response.status_code, 404)

    def test_past_question(self):
        """
        The detail view of a question with a pub_date in the past
        displays the question's text.
        """
        past_question = create_question(question_text='Past Question.', days=-5)
        url = reverse('polls:detail', args=(past_question.id,))
        response = self.client.get(url)
        self.assertContains(response, past_question.question_text)

3.投票-8應用的界面和風格

a 標簽

新建 mysite/polls/static 目錄 ,寫入下面的檔案


static/        #框架會從此處收集所有子應用靜態檔案 所以需要建一個新的polls目錄區分不同應用
  polls/       #所以寫一個重復的polls很必要 否則Django直接使用找到的第一個style.css
    style.css   
   

定義 a 標簽

# /style.css

li a{
    color: green;
}



背景圖

新建 images 目錄


static/        #框架會從此處收集所有子應用靜態檔案 所以需要建一個新的polls目錄區分不同應用
  polls/
    style.css   
    images/
      bg.jpg

定義 背景

# /style.css

li a{
    color: green;
}

body {
    background: white url("images/bg.jpg") no-repeat;
}


效果

image

3.投票-9自定義后臺表單

欄位順序

替換注釋部分

# /mysite/polls/templates/admin.py


# admin.site.register(Question)


class QuestionAdmin(admin.ModelAdmin):
    fields = ['question_text', 'pub_date']  # 串列里的順序 表示后臺的展示順序

admin.site.register(Question,QuestionAdmin)

效果

image


欄位集


當欄位比較多時,可以把多個欄位分為幾個欄位集

注意變數 fields 變為 fieldsets


class QuestionAdmin(admin.ModelAdmin):
    #fields = ['question_text', 'pub_date']  # 串列里的順序 表示后臺的展示順序
    fieldsets = [
        (None, {'fields': ['question_text']}),
        ('日期資訊', {'fields': ['pub_date']}),

    ]


效果

image


關聯選項

這樣可以在創建 question 時 同時創建 choice

# /mysite/polls/templates/admin.py

image


效果

image



讓卡槽更緊湊

替換 StackedInline 為 TabularInline


#class ChoiceInline(admin.StackedInline):
class ChoiceInline(admin.TabularInline):
    model = Choice
    extra = 3  # 默認有三個卡槽 后面還可以點擊增加

效果

image


展示question的更多欄位


Django默認回傳模型的 str 方法里寫的內容

image



添加欄位 list_display 讓其同時展示更多

方法was_published_recently 和他的回傳內容 也可以當做欄位展示

# mysite/polls/templates/admin.py

# class QuestionAdmin(admin.ModelAdmin):
#     # fields = ['question_text', 'pub_date']  # 串列里的順序 表示后臺的展示順序
#     fieldsets = [
#         (None, {'fields': ['question_text']}),
#         ('日期資訊', {'fields': ['pub_date']}),

#     ]
    
#     inlines = [ChoiceInline]  # 參考模型

    list_display = ('question_text', 'pub_date', 'was_published_recently')


效果 點擊還可以按照該欄位名排序

image

3.投票-9自定義后臺表單-2

用裝飾器優化 方法 的顯示

方法 was_published_recently 默認用空格替換下劃線展示欄位

image


用裝飾器優化一下

# /mysite/polls/templates/models.py

from django.contrib import admin  # 裝飾器

class Question(models.Model):
    #....

    @admin.display(
            boolean=True,
            ordering='pub_date',
            description='最近發布的嗎 ?',
        )
    def was_published_recently(self):
        now = timezone.now()
        # 發布時間距離現在不超過24小時 比現在小 比一天之前大 (即最近一天發布)

        return (now - datetime.timedelta(days=1)) <= self.pub_date <= now

效果

image


添加過濾器

添加一個 list_filter 欄位即可

# mysite/polls/templates/admin.py

# class QuestionAdmin(admin.ModelAdmin):
#     # fields = ['question_text', 'pub_date']  # 串列里的順序 表示后臺的展示順序
#     fieldsets = [
#         (None, {'fields': ['question_text']}),
#         ('日期資訊', {'fields': ['pub_date']}),

#     ]

#     inlines = [ChoiceInline]  # 參考模型

#     list_display = ('question_text', 'pub_date', 'was_published_recently')

    list_filter = ['pub_date']  # 過濾器
    
    

效果

image



檢索框


同上

#...
search_fields = ['question_text', 'pub_date']  # 檢索框 可添加多個欄位

效果

image

3.投票-10自定義后臺風格界面

改掉 'Django 管理'


自定義工程模板(就是在manage.py的同級目錄哪里) 再建一個templates

/mysite
  /templates  # 新建

修改 mysite/settings.py DIR是一個待檢索路徑 在django啟動時加載

把所有模板檔案存放在同一個templates中也可以 但分開會方便以后擴展復用代碼

 #...

# TEMPLATES = [
#     {
#         'BACKEND': 'django.template.backends.django.DjangoTemplates',
        #'DIRS': [],
        'DIRS': [BASE_DIR / 'templates'],
#         'APP_DIRS': True,
#         'OPTIONS': {
#             'context_processors': [
#                 'django.template.context_processors.debug',
#                 'django.template.context_processors.request',
#                 'django.contrib.auth.context_processors.auth',
#                 'django.contrib.messages.context_processors.messages',
#             ],
#         },
#     },
# ]

新建一個admin檔案夾 復制 base_site.html 復制到里面

base_site.html 是django默認的模板 它存放在 django/contrib/admin/templatesadmin/base_site.html 里面

可以用 ...\> py -c "import django; print(django.__path__)"命令查找源檔案django位置

/mysite
  /templates  # 新建
    /admin   # 新建
      base_site.html  # 本地是到E:\PYTHON\0CODE\StudyBuddy\venv\Lib\site-packages\
                      #     django\contrib\admin\templates\admin            復制
  

修改 base_site.html 內容

<!--{% extends "admin/base.html" %}-->

<!--{% block title %}{% if subtitle %}{{ subtitle }} | {% endif %}{{ title }} | {{ site_title|default:_('Django site admin') }}{% endblock %}-->

<!--{% block branding %}-->
<!--<h1 id="site-name"><a href="https://www.cnblogs.com/hugboy/p/{% url'admin:index' %}">{{ site_header|default:_('Django administration') }}</a></h1>-->
<h1 id="site-name"><a href="https://www.cnblogs.com/hugboy/p/{% url'admin:index' %}">投票 管理</a></h1>
<!--{% endblock %}-->

<!--{% block nav-global %}{% endblock %}-->

效果

image

注意,所有的 Django 默認后臺模板均可被復寫,若要復寫模板,像你修改 base_site.html 一樣修改其它檔案——先將其從默認目錄中拷貝到你的自定義目錄,再做修改


當然 也可以用 django.contrib.admin.AdminSite.site_header 來進行簡單的定制,



自定義 子應用 的模板

機智的同學可能會問: DIRS 默認是空的,Django 是怎么找到默認的后臺模板的?因為 APP_DIRS 被置為 True,Django 會自動在每個應用包內遞回查找 templates/ 子目錄(不要忘了 django.contrib.admin 也是一個應用),

我們的投票應用不是非常復雜,所以無需自定義后臺模板,不過,如果它變的更加復雜,需要修改 Django 的標準后臺模板功能時,修改 應用 的模板會比 工程 的更加明智,這樣,在其它工程包含這個投票應用時,可以確保它總是能找到需要的自定義模板檔案,

更多關于 Django 如何查找模板的檔案,參見 加載模板檔案,


自定義 后臺 首頁的模板

同之前base_site.html

復制 E:\PYTHON\0CODE\StudyBuddy\venv\Lib\site-packages\django\contrib\admin\templates\admin\index.html

mysite/templates/admin/index.html 直接修改


結束 撒花! :)

image


image


________________________________________________________

Every good deed you do will someday come back to you.

Love you,love word !

轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/544253.html

標籤:Python

上一篇:Spring IOC官方檔案學習筆記(十一)之使用JSR 330標準注解

下一篇:python定時器

標籤雲
其他(157675) Python(38076) JavaScript(25376) Java(17977) C(15215) 區塊鏈(8255) C#(7972) AI(7469) 爪哇(7425) MySQL(7132) html(6777) 基礎類(6313) sql(6102) 熊猫(6058) PHP(5869) 数组(5741) R(5409) Linux(5327) 反应(5209) 腳本語言(PerlPython)(5129) 非技術區(4971) Android(4554) 数据框(4311) css(4259) 节点.js(4032) C語言(3288) json(3245) 列表(3129) 扑(3119) C++語言(3117) 安卓(2998) 打字稿(2995) VBA(2789) Java相關(2746) 疑難問題(2699) 细绳(2522) 單片機工控(2479) iOS(2429) ASP.NET(2402) MongoDB(2323) 麻木的(2285) 正则表达式(2254) 字典(2211) 循环(2198) 迅速(2185) 擅长(2169) 镖(2155) 功能(1967) .NET技术(1958) Web開發(1951) python-3.x(1918) HtmlCss(1915) 弹簧靴(1913) C++(1909) xml(1889) PostgreSQL(1872) .NETCore(1853) 谷歌表格(1846) Unity3D(1843) for循环(1842)

熱門瀏覽
  • 【C++】Microsoft C++、C 和匯編程式檔案

    ......

    uj5u.com 2020-09-10 00:57:23 more
  • 例外宣告

    相比于斷言適用于排除邏輯上不可能存在的狀態,例外通常是用于邏輯上可能發生的錯誤。 例外宣告 Item 1:當函式不可能拋出例外或不能接受拋出例外時,使用noexcept 理由 如果不打算拋出例外的話,程式就會認為無法處理這種錯誤,并且應當盡早終止,如此可以有效地阻止例外的傳播與擴散。 示例 //不可 ......

    uj5u.com 2020-09-10 00:57:27 more
  • Codeforces 1400E Clear the Multiset(貪心 + 分治)

    鏈接:https://codeforces.com/problemset/problem/1400/E 來源:Codeforces 思路:給你一個陣列,現在你可以進行兩種操作,操作1:將一段沒有 0 的區間進行減一的操作,操作2:將 i 位置上的元素歸零。最終問:將這個陣列的全部元素歸零后操作的最少 ......

    uj5u.com 2020-09-10 00:57:30 more
  • UVA11610 【Reverse Prime】

    本人看到此題沒有翻譯,就附帶了一個自己的翻譯版本 思考 這一題,它的第一個要求是找出所有 $7$ 位反向質數及其質因數的個數。 我們應該需要質數篩篩選1~$10^{7}$的所有數,這里就不慢慢介紹了。但是,重讀題,我們突然發現反向質數都是 $7$ 位,而將它反過來后的數字卻是 $6$ 位數,這就說明 ......

    uj5u.com 2020-09-10 00:57:36 more
  • 統計區間素數數量

    1 #pragma GCC optimize(2) 2 #include <bits/stdc++.h> 3 using namespace std; 4 bool isprime[1000000010]; 5 vector<int> prime; 6 inline int getlist(int ......

    uj5u.com 2020-09-10 00:57:47 more
  • C/C++編程筆記:C++中的 const 變數詳解,教你正確認識const用法

    1、C中的const 1、區域const變數存放在堆疊區中,會分配記憶體(也就是說可以通過地址間接修改變數的值)。測驗代碼如下: 運行結果: 2、全域const變數存放在只讀資料段(不能通過地址修改,會發生寫入錯誤), 默認為外部聯編,可以給其他源檔案使用(需要用extern關鍵字修飾) 運行結果: ......

    uj5u.com 2020-09-10 00:58:04 more
  • 【C++犯錯記錄】VS2019 MFC添加資源不懂如何修改資源宏ID

    1. 首先在資源視圖中,添加資源 2. 點擊新添加的資源,復制自動生成的ID 3. 在解決方案資源管理器中找到Resource.h檔案,編輯,使用整個專案搜索和替換的方式快速替換 宏宣告 4. Ctrl+Shift+F 全域搜索,點擊查找全部,然后逐個替換 5. 為什么使用搜索替換而不使用屬性視窗直 ......

    uj5u.com 2020-09-10 00:59:11 more
  • 【C++犯錯記錄】VS2019 MFC不懂的批量添加資源

    1. 打開資源頭檔案Resource.h,在其中預先定義好宏 ID(不清楚其實ID值應該設定多少,可以先新建一個相同的資源項,再在這個資源的ID值的基礎上遞增即可) 2. 在資源視圖中選中專案資源,按F7編輯資源檔案,按 ID 型別 相對路徑的形式添加 資源。(別忘了先把檔案拷貝到專案中的res檔案 ......

    uj5u.com 2020-09-10 01:00:19 more
  • C/C++編程筆記:關于C++的參考型別,專供新手入門使用

    今天要講的是C++中我最喜歡的一個用法——參考,也叫別名。 參考就是給一個變數名取一個變數名,方便我們間接地使用這個變數。我們可以給一個變數創建N個參考,這N + 1個變數共享了同一塊記憶體區域。(參考型別的變數會占用記憶體空間,占用的記憶體空間的大小和指標型別的大小是相同的。雖然參考是一個物件的別名,但 ......

    uj5u.com 2020-09-10 01:00:22 more
  • 【C/C++編程筆記】從頭開始學習C ++:初學者完整指南

    眾所周知,C ++的學習曲線陡峭,但是花時間學習這種語言將為您的職業帶來奇跡,并使您與其他開發人員區分開。您會更輕松地學習新語言,形成真正的解決問題的技能,并在編程的基礎上打下堅實的基礎。 C ++將幫助您養成良好的編程習慣(即清晰一致的編碼風格,在撰寫代碼時注釋代碼,并限制類內部的可見性),并且由 ......

    uj5u.com 2020-09-10 01:00:41 more
最新发布
  • Rust中的智能指標:Box<T> Rc<T> Arc<T> Cell<T> RefCell<T> Weak

    Rust中的智能指標是什么 智能指標(smart pointers)是一類資料結構,是擁有資料所有權和額外功能的指標。是指標的進一步發展 指標(pointer)是一個包含記憶體地址的變數的通用概念。這個地址參考,或 ” 指向”(points at)一些其 他資料 。參考以 & 符號為標志并借用了他們所 ......

    uj5u.com 2023-04-20 07:24:10 more
  • Java的值傳遞和參考傳遞

    值傳遞不會改變本身,參考傳遞(如果傳遞的值需要實體化到堆里)如果發生修改了會改變本身。 1.基本資料型別都是值傳遞 package com.example.basic; public class Test { public static void main(String[] args) { int ......

    uj5u.com 2023-04-20 07:24:04 more
  • [2]SpinalHDL教程——Scala簡單入門

    第一個 Scala 程式 shell里面輸入 $ scala scala> 1 + 1 res0: Int = 2 scala> println("Hello World!") Hello World! 檔案形式 object HelloWorld { /* 這是我的第一個 Scala 程式 * 以 ......

    uj5u.com 2023-04-20 07:23:58 more
  • 理解函式指標和回呼函式

    理解 函式指標 指向函式的指標。比如: 理解函式指標的偽代碼 void (*p)(int type, char *data); // 定義一個函式指標p void func(int type, char *data); // 宣告一個函式func p = func; // 將指標p指向函式func ......

    uj5u.com 2023-04-20 07:23:52 more
  • Django筆記二十五之資料庫函式之日期函式

    本文首發于公眾號:Hunter后端 原文鏈接:Django筆記二十五之資料庫函式之日期函式 日期函式主要介紹兩個大類,Extract() 和 Trunc() Extract() 函式作用是提取日期,比如我們可以提取一個日期欄位的年份,月份,日等資料 Trunc() 的作用則是截取,比如 2022-0 ......

    uj5u.com 2023-04-20 07:23:45 more
  • 一天吃透JVM面試八股文

    什么是JVM? JVM,全稱Java Virtual Machine(Java虛擬機),是通過在實際的計算機上仿真模擬各種計算機功能來實作的。由一套位元組碼指令集、一組暫存器、一個堆疊、一個垃圾回收堆和一個存盤方法域等組成。JVM屏蔽了與作業系統平臺相關的資訊,使得Java程式只需要生成在Java虛擬機 ......

    uj5u.com 2023-04-20 07:23:31 more
  • 使用Java接入小程式訂閱訊息!

    更新完微信服務號的模板訊息之后,我又趕緊把微信小程式的訂閱訊息給實作了!之前我一直以為微信小程式也是要企業才能申請,沒想到小程式個人就能申請。 訊息推送平臺🔥推送下發【郵件】【短信】【微信服務號】【微信小程式】【企業微信】【釘釘】等訊息型別。 https://gitee.com/zhongfuch ......

    uj5u.com 2023-04-20 07:22:59 more
  • java -- 緩沖流、轉換流、序列化流

    緩沖流 緩沖流, 也叫高效流, 按照資料型別分類: 位元組緩沖流:BufferedInputStream,BufferedOutputStream 字符緩沖流:BufferedReader,BufferedWriter 緩沖流的基本原理,是在創建流物件時,會創建一個內置的默認大小的緩沖區陣列,通過緩沖 ......

    uj5u.com 2023-04-20 07:22:49 more
  • Java-SpringBoot-Range請求頭設定實作視頻分段傳輸

    老實說,人太懶了,現在基本都不喜歡寫筆記了,但是網上有關Range請求頭的文章都太水了 下面是抄的一段StackOverflow的代碼...自己大修改過的,寫的注釋挺全的,應該直接看得懂,就不解釋了 寫的不好...只是希望能給視頻網站開發的新手一點點幫助吧. 業務場景:視頻分段傳輸、視頻多段傳輸(理 ......

    uj5u.com 2023-04-20 07:22:42 more
  • Windows 10開發教程_編程入門自學教程_菜鳥教程-免費教程分享

    教程簡介 Windows 10開發入門教程 - 從簡單的步驟了解Windows 10開發,從基本到高級概念,包括簡介,UWP,第一個應用程式,商店,XAML控制元件,資料系結,XAML性能,自適應設計,自適應UI,自適應代碼,檔案管理,SQLite資料庫,應用程式到應用程式通信,應用程式本地化,應用程式 ......

    uj5u.com 2023-04-20 07:22:35 more