笔记-django-视图
笔记-django-视图
1. dispatch
1.1. overview
To design URLs for an app, you create a Python module informally called a URLconf (URL configuration). This module is pure Python code and is a mapping between URL path expressions to Python functions (your views).
This mapping can be as short or as long as needed. It can reference other mappings. And, because it’s pure Python code, it can be constructed dynamically.
1.2. django处理请求过程
When a user requests a page from your Django-powered site, this is the algorithm the system follows to determine which Python code to execute:
- Django determines the root URLconf module to use. Ordinarily, this is the value of the ROOT_URLCONF setting, but if the incoming HttpRequest object has a urlconf attribute (set by middleware), its value will be used in place of theROOT_URLCONF setting.指定根urlconf模板
- Django loads that Python module and looks for the variable urlpatterns. This should be a Python list of django.urls.path() and/or django.urls.re_path() instances.
- Django runs through each URL pattern, in order, and stops at the first one that matches the requested URL.按序匹配,找到第一个匹配项后返回。
- Once one of the URL patterns matches, Django imports and calls the given view, which is a simple Python function (or a class-based view). The view gets passed the following arguments:如果找到匹配模式,import and calls对应视图函数。视图函数接受以下参数:
An instance of HttpRequest.
If the matched URL pattern returned no named groups, then the matches from the regular expression are provided as positional arguments.
The keyword arguments are made up of any named parts matched by the path expression, overridden by any arguments specified in the optional kwargs argument to django.urls.path() or django.urls.re_path().
- If no URL pattern matches, or if an exception is raised during any point in this process, Django invokes an appropriate error-handling view. See Error handling below.如果没有可以匹配的模式或者出现异常,则调用异常处理视图函数。
1.3. url匹配函数
匹配函数有两个path and re_path。
一个是普通匹配,一个是正则匹配。
注意:路由匹配只是路由匹配,而不管它是get,post或其它访求方式。
/example.com/myapp
/example.com/myapp/?page=3会匹配到同一个视图myapp/
1.4. 传参
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),
]
The following path converters are available by default:
str - Matches any non-empty string, excluding the path separator, '/'. This is the default if a converter isn’t included in the expression.
int - Matches zero or any positive integer. Returns an int.
slug - Matches any slug string consisting of ASCII letters or numbers, plus the hyphen and underscore characters. For example, building-your-1st-django-site.
uuid - Matches a formatted UUID. To prevent multiple URLs from mapping to the same page, dashes must be included and letters must be lowercase. For example, 075194d3-6885-417e-a8a8-6c931e272f00. Returns a UUID instance.
path - Matches any non-empty string, including the path separator, '/'. This allows you to match against a complete URL path rather than just a segment of a URL path as with str.
也可以自定义传参解析类并添加。
1.5. 路由分组
一个大网站的页面很多,不方便把所有路由条目放在同一个文件中,django为此提供支持。
from django.urls import include, path
urlpatterns = [
# ... snip ...
path('community/', include('aggregator.urls')),
path('contact/', include('contact.urls')),
# ... snip ...
]
2. viewfuncions
2.1. HttpResponse略
2.2. Customizing error views
The default error views in Django should suffice for most Web applications, but can easily be overridden if you need any custom behavior. Simply specify the handlers as seen below in your URLconf (setting them anywhere else will have no effect).
The page_not_found() view is overridden by handler404:
handler404 = 'mysite.views.my_custom_page_not_found_view'
The server_error() view is overridden by handler500:
handler500 = 'mysite.views.my_custom_error_view'
The permission_denied() view is overridden by handler403:
handler403 = 'mysite.views.my_custom_permission_denied_view'
The bad_request() view is overridden by handler400:
handler400 = 'mysite.views.my_custom_bad_request_view'
这里只是重定义异常的视图函数指向,还需完善模板及视图函数。
注意:debug形状需要关掉,否则上列定义参数无法生效。
3. djangoshortcut functions
3.1.1. render
render()
render(request, template_name, context=None, content_type=None, status=None, using=None)
Combines a given template with a given context dictionary and returns an HttpResponse object with that rendered text.
参数释义:
request:The request object used to generate this response.
template_name:模板路径,如果给出一个序列,使用第一个有效的
context:变量传递
A dictionary of values to add to the template context. By default, this is an empty dictionary. If a value in the dictionary is callable, the view will call it just before rendering the template.
content_type
The MIME type to use for the resulting document. Defaults to the value of the DEFAULT_CONTENT_TYPE setting.
status
The status code for the response. Defaults to 200.
using
The NAME of a template engine to use for loading the template.
3.1.2. redirect
redirect(to, permanent=False, *args, **kwargs)[source]
Returns an HttpResponseRedirect to the appropriate URL for the arguments passed.
The arguments could be:
A model: the model’s get_absolute_url() function will be called.
A view name, possibly with arguments: reverse() will be used to reverse-resolve the name.
An absolute or relative URL, which will be used as-is for the redirect location.
By default issues a temporary redirect; pass permanent=True to issue a permanent redirect.
参数可以是:
一个模型: 将调用模型的get_absolute_url()函数
一个视图, 可以带有函数: 可以使用urlresolvers.reverse来反向解析名称
一个绝对的或相对的URL, 将原封不动的作为重定向的位置.
默认返回一个临时的重定向, 传递permanent=True可以返回一个永久的重定向.
示例:
你可以用多种方式使用redirect()函数.
传递一个具体的ORM对象(了解即可).
将调用具体ORM对象的get_absolute_url()方法来获取重定向的URL.
from django.shortcuts import redirect
def my_view(request):
...
object = MyModel.objects.get(...)
return redirect(object)
传递一个视图的名称
def my_view(request):
...
return redirect("some-view-name", foo="bar")
传递要重定向到的一个具体的网址
def my_view(request):
...
return redirect("/some/url/")
当然也可以是一个完整的网址
def my_view(request):
...
return redirect("http://example.com")
默认情况下, redirect()返回一个临时重定向. 以上所有的形式都接收一个permanent参数; 如果设置为True, 将返回一个永久的重定向:
def my_view(request):
...
object = MyModel.objects.get(...)
return redirect(object, permanent=True)
4. View decorators
Django provides several decorators that can be applied to views to support various HTTP features.
See Decorating the class for how to use these decorators with class-based views.
Allowed HTTP methods
The decorators in django.views.decorators.http can be used to restrict access to views based on the request method. These decorators will return a django.http.HttpResponseNotAllowed if the conditions are not met.
require_http_methods(request_method_list)[source]
Decorator to require that a view only accepts particular request methods. Usage:
from django.views.decorators.http import require_http_methods
@require_http_methods(["GET", "POST"])
def my_view(request):
# I can assume now that only GET or POST requests make it this far
# ...
pass
Note that request methods should be in uppercase.
require_GET()
Decorator to require that a view only accepts the GET method.
require_POST()
Decorator to require that a view only accepts the POST method.
require_safe()
Decorator to require that a view only accepts the GET and HEAD methods. These methods are commonly considered “safe” because they should not have the significance of taking an action other than retrieving the requested resource.
Note
Web servers should automatically strip the content of responses to HEAD requests while leaving the headers unchanged, so you may handle HEAD requests exactly like GET requests in your views. Since some software, such as link checkers, rely on HEAD requests, you might prefer using require_safeinstead of require_GET.
Conditional view processing
The following decorators in django.views.decorators.http can be used to control caching behavior on particular views.
condition(etag_func=None, last_modified_func=None)[source]
etag(etag_func)[source]
last_modified(last_modified_func)[source]
These decorators can be used to generate ETag and Last-Modified headers; see conditional view processing.
GZip compression
The decorators in django.views.decorators.gzip control content compression on a per-view basis.
gzip_page()
This decorator compresses content if the browser allows gzip compression. It sets the Vary header accordingly, so that caches will base their storage on the Accept-Encoding header.
Vary headers
The decorators in django.views.decorators.vary can be used to control caching based on specific request headers.
vary_on_cookie(func)[source]
vary_on_headers(*headers)[source]
The Vary header defines which request headers a cache mechanism should take into account when building its cache key.
See using vary headers.
Caching
The decorators in django.views.decorators.cache control server and client-side caching.
cache_control(**kwargs)[source]
This decorator patches the response’s Cache-Control header by adding all of the keyword arguments to it. Seepatch_cache_control() for the details of the transformation.
never_cache(view_func)[source]
This decorator adds a Cache-Control: max-age=0, no-cache, no-store, must-revalidate header to a response to indicate that a page should never be cached.
笔记-django-视图的更多相关文章
- Django:学习笔记(9)——视图
Django:学习笔记(9)——视图 基础视图 基于函数的视图,我们需要在使用条件语句来判断请求类型,并分支处理.但是在基于类的视图中,我们可以在类中定义不同请求类型的方法来处理相对应的请求. 基于函 ...
- Django:学习笔记(8)——视图
Django:学习笔记(8)——视图
- 《玩转Django2.0》读书笔记-探究视图
<玩转Django2.0>读书笔记-探究视图 作者:尹正杰 版权声明:原创作品,谢绝转载!否则将追究法律责任. 视图(View)是Django的MTV架构模式的V部分,主要负责处理用户请求 ...
- 《玩转Django2.0》读书笔记-Django建站基础
<玩转Django2.0>读书笔记-Django建站基础 作者:尹正杰 版权声明:原创作品,谢绝转载!否则将追究法律责任. 一.网站的定义及组成 网站(Website)是指在因特网上根据一 ...
- 1.2、Django 视图与网址__进阶
Django 视图与网址进阶 1.1.简单使用: 把我们新定义的app加到settings.py中的INSTALL_APPS中 修改 HelloDjango/HelloDjango/settings. ...
- 笔记-django第一个项目
笔记-django第一个项目 1. 创建项目 安装 Django 之后,现在有了可用的管理工具 django-admin.可以使用 django-admin 来创建一个项目: 看下djang ...
- [diango]理解django视图工作原理
前言:正确理解django视图view,模型model,模板的概念及其之间的关联关系,才能快速学习并上手使用django制作网页 本文主要讲解自己在学习django后对视图view的理解 在进入正文之 ...
- python学习笔记--Django入门四 管理站点--二
接上一节 python学习笔记--Django入门四 管理站点 设置字段可选 编辑Book模块在email字段上加上blank=True,指定email字段为可选,代码如下: class Autho ...
- Django 2.0 学习(03):Django视图和URL(下)
接上篇博文,继续分析Django基本流程. 编写第一个(view)视图函数 1.打开文件polls/views.py,输入下面的Python代码: from django.http import Ht ...
- 如何在django视图中使用asyncio(协程)和ThreadPoolExecutor(多线程)
Django视图函数执行,不在主线程中,直接 loop = asyncio.new_event_loop() # 更不能loop = asyncio.get_event_loop() 会触发 Runt ...
随机推荐
- python UI自动化实战记录五:测试页面2 pageobject
该部分记录测试页面2-StrategyPage,所有页面2上的元素定位.操作.获取属性等方法都写在该类中. 1 页面2继承自BasePage: 2 页面2第一部分写的是所有的定位器 3 页面2第二部分 ...
- [零基础学JAVA]Java SE基础部分-04. 分支、循环语句
转自:http://redking.blog.51cto.com/27212/116751 1.课程名称:分支.循环 本季为JAVA程序中最重要的部分,在讲解的时候除了讲解各种主要的控制语句(分支语句 ...
- PTA练习题之7-2 求交错序列前N项和(15 分)
本题要求编写程序,计算交错序列 1-2/3+3/5-4/7+5/9-6/11+... 的前N项之和. 输入格式: 输入在一行中给出一个正整数N. 输出格式: 在一行中输出部分和的值,结果保留三位小数. ...
- bzoj5152 [Wc2018]通道
题目链接 正解:不会做. 写一个爬山算法就过官方数据了(逃 具体来说就是每次随机一个根,然后迭代找最长路的那个点. 多随机几次取$max$就行了.正解以后再补.. #include <bits/ ...
- 「uoj#188. 【UR #13】Sanrd」
题目 不是很能看懂题意,其实就是求\([l,r]\)区间内所有数的次大质因子的和 这可真是看起来有点鬼畜啊 这显然不是一个积性函数啊,不要考虑什么特殊的函数了 我们考虑Min_25筛的过程 设\(S( ...
- 蓝牙BLE4.0的LL层数据和L2CAP层数据的区分与理解
一直搞不太清楚蓝牙BLE协议,不知道LL层和L2CAP层是如何划分的,后来博士给我讲了讲就理解了,写下来,做个记录: 1. 我们知道,除了蓝牙5.1新出的CTE,所有的BLE都是如下类型的包: 对于连 ...
- 刷题防止Time Limit Exceeded(TLE)技巧
1.C++ 不要使用cin,cout,该使用scanf和printf 2.Java 不要使用Scanner,改用BufferedReader 3.Python 在文件开始的地方加入 import ps ...
- 自动化构建工具grunt的学习
关于grunt的一些记录,记的比较乱... 0.删除node_modules文件夹 命令行: npm install rimraf -g //先运行 rimraf node_modules //然后运 ...
- PAT——1006. 换个格式输出整数
1006. 换个格式输出整数 (15) 时间限制 400 ms 内存限制 65536 kB 代码长度限制 8000 B 判题程序 Standard 作者 CHEN, Yue 让我们用字母B来表示“百” ...
- Hadoop 学习之——HDFS
HDFS是HADOOP中的核心技术之一——分布式文件存储系统.Hadoop的作者Doug Cutting 和Mike 是根据Google发布关于GFS 的研究报告所设计出的分布式文件存储系统. 一.H ...