URL调度器
urlpatterns
当接收一个
HttpRequest
对象时,Django
会自按顺序遍历urlpatterns
进行匹配.
它是django.urls.path()
和(或)django.urls.re_path()
实例的序列
urlpatterns = [ |
URL匹配
变量匹配 ---
path()
path('<int:question_id>/vote/', views.vote, name='vote'),
- 要捕获的部分由
<>
包围. int
代表数据类型, 也可以是str
.- 默认是在路径的结尾添加
/
.
- 要捕获的部分由
正则匹配 ---
re_path()
re_path(r'^(?P<question_id>\d+)/vote/$', views.vote, name='vote')
- 本质上是
re
模块的封装 ^
和$
注意加上, 防止上级路径捕获次级路径
- 本质上是
include()
include()
可以将其他urlconf
添加到当前的urlpatterns
序列当中.
path('polls/', include('polls.urls')),
也可以将相同的路径前缀下后面的部分一起声明.
path('<page_slug>-<page_id>/', include([
path('history/', views.history),
path('edit/', views.edit),
path('discuss/', views.discuss),
path('permissions/', views.permissions),
]))
HttpRequest
属性
HttpRequest.path
当前请求路径HttpRequest.body
当前请求体
HttpRequest.method
当前请求方法HttpRequest.GET
GET携带的
params
参数HttpRequest.POST
POST携带的data
参数HttpRequest.COOKIES
cookies 字典HttpRequest.FILES
上传的文件HttpRequest.content_type
当前传输数据类型HttpRequest.session
请求的服务器信息HttpRequest.META
包含了 HTTP 头文件的字典
方法
get_host()
获取请求主机
HttpResponse
模板使用
from django.shortcuts import render
return render(request, 'polls/results.html', {'question': question})返回字符串
from django.http import HttpResponse
return HttpResponse("Here's the text of the Web page.")返回JSON格式的字符串
本质上和
HttpResponse(json.dumps({}))
一样,, 但提供了更多功能.
默认只接受dict
格式, 需要设置safe
为False
才能传入其它格式.from django.http import JsonResponse
return JsonResponse({'foo': 'bar'}, safe=False)返回文件
主要是
Content-Disposition
里的内容, 这里没有Django
特有的语法.response = HttpResponse('test', headers={
'Content-Type': 'application/octet-stream',
'Content-Disposition': 'attachment; filename="test.txt"',
})
return response返回异常
from django.http import Http404
raise Http404('Page not found')
视图
简单了解下4种HTTP协议请求方式
GET 获取资源
POST 新建资源(更新资源)
PUT 更改资源
DELETE 删除资源
基于函数的视图
def index(request): |
实现RESTful api
def index_get(request): |
绑定url
path('get', views.xxx, name='index_get'), |
基于类的视图
不用写多个绑定, 而且层次分明, 模块开发时优选.
绑定url
path('', views.IndexView.as_view(), name='index'),
只需要绑定一次
path
, 会根据HttpRequest.method
自动选择相应的处理方法.class IndexView(generic.View):
def get(self, *args, **kwargs):
pass
def post(self, *args, **kwargs):
pass
def put(self, *args, **kwargs):
pass
def delete(self, *args, **kwargs):
pass