Django編寫第一個應用視圖
前面我們創(chuàng)建了django項目,并啟動了服務web服務,下面在項目中創(chuàng)建應用,開啟我們的編寫之旅。
項目中創(chuàng)建應用
- 首先切換到項目目錄中
- 其次輸入命令:python manage.py startapp 項目名稱(自定義名稱)
- 最后按下 enter 鍵,創(chuàng)建成功
- (venv) apple:hello_django lifeng$ python manage.py startapp hello_apps
編寫第一個視圖
在創(chuàng)建的應用中創(chuàng)建視圖:
- from django.contrib import admin
- from django.urls import path
- from hello_apps import views
- urlpatterns = [
- # admin這個是系統(tǒng)自帶的
- path('admin/', admin.site.urls),
- path('hello/', views.hello),
- ]
在urls中配置路徑:
- def _path(route, view, kwargs=None, name=None, Pattern=None):
- if isinstance(view, (list, tuple)):
- # For include(...) processing.
- pattern = Pattern(route, is_endpoint=False)
- urlconf_module, app_name, namespace = view
- return URLResolver(
- pattern,
- urlconf_module,
- kwargs,
- app_name=app_name,
- namespace=namespace,
- )
- elif callable(view):
- pattern = Pattern(route, name=name, is_endpoint=True)
- return URLPattern(pattern, view, kwargs, name)
- else:
- raise TypeError('view must be a callable or a list/tuple in the case of include().')
- path = partial(_path, Pattern=RoutePattern)
- re_path = partial(_path, Pattern=RegexPattern)
path中有五個參數(shù),兩個必傳參數(shù)route、view;兩個可傳參數(shù)kwargs、name;Pattern默認值是None
- route:路線,也就是配置url路徑,
- view:視圖函數(shù),用于執(zhí)行與正則匹配的url請求
- kwargs:任意個關(guān)鍵字參數(shù)可以作為一個字典傳遞給目標視圖函數(shù)
- name:別名,為url路徑取別名使用
Pattern默認值是None,體現(xiàn)在下面這段代碼上:
- path = partial(_path, Pattern=RoutePattern)
在這里就引入了一個高階函數(shù)的概念,偏函數(shù),舉例子如下:
- print(int('11111', base=8))
把字符串轉(zhuǎn)成8進制的整數(shù)類型,如遇到一次還可以這樣操作,如遇到多個變量進行八進制的轉(zhuǎn)換就每次都要寫base=8,那如果是下面這樣寫會不會就舒服些呢?
設置固定默認值:
- def new_int(value, base=8):
- return int(value, base)
使用partial創(chuàng)建偏函數(shù),簡單理解就是固定住默認值,返回一個新的函數(shù),從而能更簡單地調(diào)用:
- from functools import partial
- new_type = partial(int, base=8)
- print(new_type('55555'))
以上創(chuàng)建偏函數(shù)說的均是關(guān)鍵字傳參,還有*args傳參,您可自行百度搜索或可查看python官網(wǎng)文檔。
官方文檔地址:https://docs.python.org/zh-cn/3/library/functools.html
再返回觀看Pattern所傳的關(guān)鍵字是RoutePattern,而RoutePattern利用正則來專門查找url路徑的等一系列方法。
path = partial() 就是創(chuàng)建一個偏函數(shù),并返回一個新函數(shù),新函數(shù)是保留原函數(shù)參數(shù)的,只是做了一個默認值綁定:
- path = partial(_path, Pattern=RoutePattern)
有些時候可能你會有疑問,為什么有的會加include
- urlpatterns = [
- path('hello/', include(hello.urls))
- ]
官方描述:函數(shù) include() 允許引用其它 URLconfs。每當 Django 遇到 :func:~django.urls.include 時,它會截斷與此項匹配的 URL 的部分,并將剩余的字符串發(fā)送到 URLconf 以供進一步處理。
實際就是根據(jù)你傳的值再一次確認,是不是符合django要求的url配置
使用前要注意引包操作,不然會報:NameError: name 'include' is not defined
- from django.conf.urls import include
創(chuàng)建好應用后,啟動項目:python manage.py runserver
- (venv) apple:hello_django lifeng$ python manage.py runserver
- Watching for file changes with StatReloader
- Performing system checks...
- System check identified no issues (0 silenced).
- You have 18 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): admin, auth, contenttypes, sessions.
- Run 'python manage.py migrate' to apply them.
- April 04, 2021 - 13:58:13
- Django version 3.1.7, using settings 'hello_django.settings'
- Starting development server at http://127.0.0.1:8000/
- Quit the server with CONTROL-C.
訪問
http://127.0.0.1:8000/hello/
成功進入第一個頁面。
以上總結(jié)或許能幫助到你,或許幫助不到你,但還是希望能幫助到你,如有疑問、歧義,評論區(qū)留言會及時修正發(fā)布,謝謝!