Django編寫第一個(gè)應(yīng)用視圖
前面我們創(chuàng)建了django項(xiàng)目,并啟動了服務(wù)web服務(wù),下面在項(xiàng)目中創(chuàng)建應(yīng)用,開啟我們的編寫之旅。
項(xiàng)目中創(chuàng)建應(yīng)用
- 首先切換到項(xiàng)目目錄中
- 其次輸入命令:python manage.py startapp 項(xiàng)目名稱(自定義名稱)
- 最后按下 enter 鍵,創(chuàng)建成功
- (venv) apple:hello_django lifeng$ python manage.py startapp hello_apps
編寫第一個(gè)視圖
在創(chuàng)建的應(yīng)用中創(chuàng)建視圖:
- from django.contrib import admin
- from django.urls import path
- from hello_apps import views
- urlpatterns = [
- # admin這個(gè)是系統(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中有五個(gè)參數(shù),兩個(gè)必傳參數(shù)route、view;兩個(gè)可傳參數(shù)kwargs、name;Pattern默認(rèn)值是None
- route:路線,也就是配置url路徑,
- view:視圖函數(shù),用于執(zhí)行與正則匹配的url請求
- kwargs:任意個(gè)關(guān)鍵字參數(shù)可以作為一個(gè)字典傳遞給目標(biāo)視圖函數(shù)
- name:別名,為url路徑取別名使用
Pattern默認(rèn)值是None,體現(xiàn)在下面這段代碼上:
- path = partial(_path, Pattern=RoutePattern)
在這里就引入了一個(gè)高階函數(shù)的概念,偏函數(shù),舉例子如下:
- print(int('11111', base=8))
把字符串轉(zhuǎn)成8進(jìn)制的整數(shù)類型,如遇到一次還可以這樣操作,如遇到多個(gè)變量進(jìn)行八進(jìn)制的轉(zhuǎn)換就每次都要寫base=8,那如果是下面這樣寫會不會就舒服些呢?
設(shè)置固定默認(rèn)值:
- def new_int(value, base=8):
- return int(value, base)
使用partial創(chuàng)建偏函數(shù),簡單理解就是固定住默認(rèn)值,返回一個(gè)新的函數(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)建一個(gè)偏函數(shù),并返回一個(gè)新函數(shù),新函數(shù)是保留原函數(shù)參數(shù)的,只是做了一個(gè)默認(rèn)值綁定:
- path = partial(_path, Pattern=RoutePattern)
有些時(shí)候可能你會有疑問,為什么有的會加include
- urlpatterns = [
- path('hello/', include(hello.urls))
- ]
官方描述:函數(shù) include() 允許引用其它 URLconfs。每當(dāng) Django 遇到 :func:~django.urls.include 時(shí),它會截?cái)嗯c此項(xiàng)匹配的 URL 的部分,并將剩余的字符串發(fā)送到 URLconf 以供進(jìn)一步處理。
實(shí)際就是根據(jù)你傳的值再一次確認(rèn),是不是符合django要求的url配置
使用前要注意引包操作,不然會報(bào):NameError: name 'include' is not defined
- from django.conf.urls import include
創(chuàng)建好應(yīng)用后,啟動項(xià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/
成功進(jìn)入第一個(gè)頁面。
以上總結(jié)或許能幫助到你,或許幫助不到你,但還是希望能幫助到你,如有疑問、歧義,評論區(qū)留言會及時(shí)修正發(fā)布,謝謝!