目录
Django拾遗
url配置
是多个的,具有一定的层级关系
当接受一个HTTPRequest对象是,django会自上而下寻找urlpattern进行匹配
起点是ROOT RRL_CONF中设置的路径
它是 django.urls.path() 和(或) django.urls.re_path() 实例的序列(sequence)。
-
url匹配
-
变量匹配
path('study01/<int:pk>/', views.DetailView.as_view(), name='detail'),
-
要捕获的部分由<>包围
-
int代表数据类型,也可以是str
-
默认是在路径的结尾添加/(不是必须的,是Django提倡的)
-
-
正则匹配
其实是封装了re正则表达式的模块
import re # path('study01/<int:pk>/', views.DetailView.as_view(), name='detail'), path="5/" m=re.match(r'^(?P<question_id>\d+)/$',path) print(m.group("question_id"))
re._path(r'^(?P<question_id>\d+)/$',view.detail,name='detail')
===
path('study01/<int:pk>/', views.DetailView.as_view(), name='detail'),
-
-
include:可以加其他urlconf添加到当前的urlpattern序列中
全局url
项目url
HTTPRequest
-
获取当前url路径
request.path
-
获取当前请求方法的method
method:POST或GET
-
获取当前请求体
body
-
获取POST携带的data参数
#data_dict=request.POST choice=request.POST['choice']
-
获取GET携带的params参数
parasm=request.GET
-
-
获取当前请求的session(存在于客户端)
reques.session
-
获取当前的cookie
cookie_dict=request.cookies
-
获取当前域名的地址
request.get_host()
-
获取当前的一个路径
request.path() request.get_full_path()
-
获取当前传输类型
request.content_type
HttpResponse类型
-
模板对象
from http.django import render return render(request,'result.html',{"question":question})
-
返回字符串
from http.django import HttpResponse return HttpResponse('test')
-
返回JSON格式字符串
虽然本质和HttpResponse(json.dumps({}))一致,但是JsonResponse()提供更多的功能
from http.django import JsonResponse return JsonResponse({'choice':2},safe=False)
-
返回文件
def file_test(request): filename="views.py" with open("api01/views.py","r",encoding="utf-8") as f: response=FileResponse(f.read()) response['content-type']="application/octet-stream" response['content-disposition']=f"attachment;filename='{filename}'" return response
-
返回异常
return Http404()#第一找不到页面 第二 服务器进制访问(端口没开) return Http502()#服务器内部问题
视图
HTTP协议的请求方式
GET (查),PSOT(增)Delete(删)put(改)
-
基于函数的视图:适合单一的操作
def vote(request, question_id): question=get_object_or_404(Question,pk=question_id) try: select_choice=question.choice_set.get(pk=request.POST['choice']) except(KeyError,Choice.DoesNotExist): return render(request, 'detail.html',{ 'question':question, 'error_message':'you did not select a choice', }) else: select_choice.votes+=1 select_choice.save() return HttpResponseRedirect(reverse('results',args=(question.id,))) def file_test(request): filename="views.py" with open("api01/views.py","r",encoding="utf-8") as f: response=FileResponse(f.read()) response['content-type']="application/octet-stream" response['content-disposition']=f"attachment;filename='{filename}'" return response
path('study01/<int:question_id>/vote/', views.vote, name='vote'),
-
基于类的视图:适合功能多的方式
class Index(generic.View): def get(*args,**kwargs): pass def post(*args,**kwargs): pass def put(*args,**kwargs): pass def delete(*args,*kwargs): pass
path('study01/',views.IndexView.as_view(),name='index'),
path('study01/<int:pk>/', views.DetailView.as_view(), name='detail'),