视图层

一、基础

1.URL配置

​ Django将URLconf中配置的url映射到一个Python函数中(views)。

​ Django 还提供根据当前语言翻译URL 的一种方法。更多信息参见 国际化文档

2.设置url

①django.url.path()函数

path(route, view, kwargs=None, name=None)

②re_path()

re_path(route, view, kwargs=None, name=None)

  • route:字符串或则一个gettext_lazy(),字符串兼容Python的re模块,允许包含正则表达式。

④include()

include(module, namespace=None)

include(pattern_list)

include((pattern_list, app_namespace), namespace=None)

​ include()模块用于将url匹配指向另外一个urls.py文件,并且将会截取带已经匹配的部分,将剩余部分传入下一个文件。

3.URL如何解析Http请求:

  1. Django首先使用ROOT_URLCONF中配置的根URLconf,如果传入的HttpRequest含有urlconf属性,ROOT_URLCONF设置将会被替换。

  2. Django使用urlpatterns匹配请求的url,urlpattern中的选项可以是django.urls.path()django.urls.re_path()

  3. Django将会在匹配到第一个符合条件的URL中停止

  4. 一旦URL被匹配到,Django将会调用视图函数,并创建一个HttpRequest实例传入view函数的第一个参数中。

例:

from django.urls import path

from . import views

urlpatterns = [
    path('articles/2003/', views.special_case_2003),
    path('articles/<int:year>/', views.year_archive),
    path('articles/<int:year>/<int:month>/', views.month_archive),
    path('articles/<int:year>/<int:month>/<slug:slug>/', views.article_detail),
]

4.namespace

例:

#pools/urls.py
from django.urls import path

from . import views

app_name = 'polls'
urlpatterns = [
    path('', views.IndexView.as_view(), name='index'),
    path('<int:pk>/', views.DetailView.as_view(), name='detail'),
    ...
]
# urls.py
from django.urls import include, path

urlpatterns = [
    path('author-polls/', include('polls.urls', namespace='author-polls')),
    path('publisher-polls/', include('polls.urls', namespace='publisher-polls')),
]

二、视图

1.render()

render(request, template_name, context=None, content_type=None, status=None, using=None)

  • request是必选参数

  • template_name是一个字符串,用于指定模板路径

  • context:字典对象,将函数变量传入模板

2.装饰器

​ 装饰器用于限定视图函数接收的http请求方式。

from django.views.decorators.http import require_http_methods

@require_http_methods(["GET", "POST"])
def my_view(request):
    pass

3.HttpRequest对象

​ HttpRequest由Django创建并传入view函数的第一个参数中中。

| 属性 | 作用 | | ———— | ——————————————————— | | scheme | 表示请求方式的字符串(http或https) | | body | HTTP请求头的原始字符串 | | path | HTTP路径,不包含域名和端口 | | method | HTTP请求的方式 | | encoding | 表单提交数据的解码方式 | | content_type | 表示请求的MIME类型的字符串 | | GET | 类似字典的对象,包含了GET请求的参数,同名参数只获取第一个 | | POST | 类似字典的对象,包含了POST请求的参数 | | COOKIES | 字典对象,包含了所有cookies | | FILES | 类字典对象,包含了所有上传的文件 | | session | 类似字典的对象,表示当前会话 |

4.HttpResponse对象

​ HttpResponse对象是由程序员创建并实例化的。

①.属性

| 属性 | 作用 | | :———-: | :——————————–: | | content | 表示返回的内容 | | charset | 返回给浏览器的网页的编码格式 | | status_code | 响应状态码(200、304、404) | | content-type | 指定输出的MIME类型(比如text/html) |

②.方法

| 方法 | 作用 | | :————————————————: | :———————————————: | | init | 使页面内容实例化HttpResponse对象 | | write(content) | 以文件的方式写入 | | flush() | 以文件的形式输出缓冲区 | | set_cookie(key,value=’’,max_age=None,exprise=None) | 设置cookie | | delete_cookie(key) | 删除cookie的一个key,若不存在,则不执行任何操作 |

5.HttpResponseRedirect

​ 继承于HttpResponse,用于重定向

6.JSonResponse