32_URLConf_1
Django如何处理一个请求
当一个用户通过网页发送一个请求给Django网站,Django执行过程如下:
- 首先访问项目下的settings.py文件中 ROOT_URLCONF = 'test1.urls'
- 执行项目包下的urls.py文件中的urlpatterns列表
- 执行应用包下的urls.py文件中的urlpatterns列表
- 根据匹配的url正则调用相应的视图函数/通用视图
- 如果没有匹配的正则,将会自动调用Django错误处理页面
url函数配置方式
- 方式1
#student/urls.py
#coding=utf-8
from django.conf.urls import url
from . import views
urlpatterns=[
url(r'^query$',views.queryAll)
]
#student/views.py
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.http import HttpResponse
from django.shortcuts import render
# Create your views here.
def queryAll(request):
return HttpResponse('hello world')
#访问地址
http://127.0.0.1:8000/student/query
- 方式2:位置传参
#student/urls.py
#coding=utf-8
from django.conf.urls import url
from . import views
urlpatterns=[
url(r'^query/(\d{2})$',views.queryAll),
]
#student/views.py
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.http import HttpResponse
from django.shortcuts import render
# Create your views here.
def queryAll(request,sno):
print sno
return HttpResponse('hello world')
#访问地址
http://127.0.0.1:8000/student/query/12
- 方式3:关键字传参
urlpatterns=[
url(r'^query/(?P<year>[0-9]{4})/(?P<month>[0-9]{2})/(?P<day>[0-9]{2})/$', views.queryAll),
]
def queryAll(request,year,day,month):
print year,month,day
return HttpResponse('hello world')
#访问地址
http://127.0.0.1:8000/student/query/2008/10/12/
- 方式4:加载其他映射文件
from django.conf.urls import include, url
urlpatterns = [
url(r'^community/', include('aggregator.urls')),
]
- 方式5:传参(参数名必须保持一致)
urlpatterns=[
url(r'^query/(?P<num1>\d{3})/$',views.queryAll,{'hello':'123'}),
]
def queryAll(request,num1,hello):
print num1,hello
return HttpResponse('hello world')
#访问地址
http://127.0.0.1:8000/student/query/888/
补充:Django 2.X 以后的写法和 Django 1.X 写法对比
student/urls.py
# coding=utf-8
from django.conf.urls import url
from django.urls import path, re_path, include
from . import views
urlpatterns = [
# url函数配置
# 方式1-普通字符串 # 访问地址 http://127.0.0.1:8000/student/query
# url(r'^query$', views.queryAll),
path('query', views.queryAll),
# 方式2:位置传参 # 访问地址 http://127.0.0.1:8000/student/query/12
# url(r'^query/(\d{2})$', views.queryAll2),
re_path(r'^query/(\d{2})$', views.queryAll2),
# path('query/<sno>', views.queryAll2), # 没有限定类型和长度
# path('query/<int:sno>', views.queryAll2), # 限定类型为int
# 方式3:关键字传参 # 访问地址 http://127.0.0.1:8000/student/query/2008/10/12/
# url(r'^query/(?P<year>[0-9]{4})/(?P<month>[0-9]{2})/(?P<day>[0-9]{2})/$', views.queryAll3),
re_path(r'^query/(?P<year>[0-9]{4})/(?P<month>[0-9]{2})/(?P<day>[0-9]{2})/$', views.queryAll3),
# 方式4:加载其他映射文件(多用于根路由中
# url(r'^community/', include('aggregator.urls')),
path('community/', include('aggregator.urls')),
# 方式5:传参(参数名必须保持一致) # 访问地址 http://127.0.0.1:8000/student/query/888/
# url(r'^query/(?P<num1>\d{3})/$', views.queryAll, {'hello': '123'}),
re_path(r'^query/(?P<num1>\d{3})/$', views.queryAll4, {'hello': '123'}),
]
student/views.py
from django.http import HttpResponse
# Create your views here.
def queryAll(request):
return HttpResponse('hello world')
def queryAll2(request, sno):
print(sno)
return HttpResponse('hello world')
def queryAll3(request, year, day, month):
print(year, month, day)
return HttpResponse('hello world')
def queryAll4(request, num1, hello):
print(num1, hello)
return HttpResponse('hello world')
33_URLConf_2
逆向解析(防止硬编码)
#student/urls.py
# from django.conf.urls import url
from django.urls import path, re_path
from . import views
urlpatterns=[
# url(r'^query1/([0-9]{4})/$', views.queryAll, name='hello'),
# url(r'^$', views.index_view),
re_path(r'^query1/([0-9]{4})/$', views.queryAll, name='hello'),
path('', views.index_view),
]
#student/views.py
# -*- coding: utf-8 -*-
from django.http import HttpResponse
from django.shortcuts import render
# Create your views here.
def queryAll(request,num1):
print num1
return HttpResponse('hello world')
# 通过模板页面逆向访问
def index_view(request):
return render(request,'index.html')
# 通过Python代码逆向访问
def index_view(request):
# return render(request,'index.html')
return HttpResponseRedirect(reverse('hello',args=(2018,)))
#templates/index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<a href="{% url 'hello' 2008 %}">访问</a>
</body>
</html>
- 方式2
#项目包/urls.py
# from django.conf.urls import url, include
from django.urls import path, include
from django.contrib import admin
urlpatterns = [
# url(r'^admin/', admin.site.urls),
# url(r'^student/', include('student.urls',namespace='stu',app_name='student')),
path('admin/', admin.site.urls),
# path('student/', include('student.urls')),
path('student/', include('student.urls', namespace='stu')),
]
#应用包/urls.py
#coding=utf-8
# from django.conf.urls import url
from django.urls import path, re_path
from . import views
urlpatterns=[
# url(r'^$', views.Index.as_view()),
# url(r'^query2/',views.Login.as_view(),name='login')
path('', views.Index.as_view()),
path('query2/',views.Login.as_view(),name='login')
]
#应用包/views.py
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render
from django.urls import reverse
from django.views import View
class Index(View):
def get(self,request):
return render(request,'index.html')
class Login(View):
def get(self,request):
return HttpResponse('hello')
#templates/index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<a href="{% url 'stu:login' %}">访问</a>
</body>
</html>
34_HttpRequest和HttpResponse
HttpRequest请求对象(只读)
- 当用户访问一个视图函数时,Django会创建一个request对象(HttpRequest)
- HttpRequest对象中封装了所有的Http协议中的请求信息
常见属性和方法
HttpRequest.scheme:返回协议类型(http/https)
HttpRequest.body:返回请求实体内容
HttpRequest.path:返回请求地址
HttpRequest.method:返回当前请求方式(GET/POST)
HttpRequest.GET:返回当前请求参数的字典QueryDict
HttpRequest.POST:返回当前请求参数的字典QueryDict
HttpRequest.COOKIES:返回客户端所有的cookie信息
HttpRequest.FILES:获取上传文件(1.要求POST请求2.enctype="multipart/form-data)
HttpRequest.META:返回请求报文信息
HttpRequest.get_host():返回请求主机名和端口号
HttpRequest.get_full_path():返回请求地址(包括请求参数)
举例:
student/views.py
from django.http import HttpResponse
from django.shortcuts import render
# Create your views here.
def getRequestInfo(request):
print(request)
print(type(request))
# GET / HTTP / 1.1
# 获取请求行信息
print('请求方式:%s' % request.method)
print('请求地址:%s' % request.path)
print('请求协议类型:%s' % request.scheme)
print("=" * 30)
for k, v in request.META.items():
if k.startswith("HTTP"):
print("%s:%s" % (k, v))
if request.method == "GET":
return render(request, "index.html")
elif request.method == "POST":
print(request.POST.get("uname", ""))
print(request.body)
return HttpResponse("hello")
补充:
python字符串前面加u,r,b的含义
1、字符串前加 u
例:u"我是含有中文字符组成的字符串。" 作用:后面字符串以 Unicode 格式 进行编码,一般用在中文字符串前面,防止因为源码储存格式问题,导致再次使用时出现乱码。
2、字符串前加 r
例:r"\n\n\n\n\n\n”
作用:声明后面的字符串是普通字符串,相对的,特殊字符串中含有:转义字符 \n \t 什么什么的。
用途:一般用在 正则表达式、文件绝对地址、等等中。。。
3、字符串前加 b
作用:python3.x里默认的str是(py2.x里的)unicode, bytes是(py2.x)的str, b”“前缀代表的就是bytes
python2.x里, b前缀没什么具体意义, 只是为了兼容python3.x的这种写法
HttpResponse 响应对象
用法
#响应内容
>>> from django.http import HttpResponse
>>> response = HttpResponse("Here's the text of the Web page.")
>>> response = HttpResponse("Text only, please.", content_type="text/plain")
>>> response = HttpResponse()
>>> response.write("<p>Here's the text of the Web page.</p>")
>>> response.write("<p>Here's another paragraph.</p>")
>>> response = HttpResponse(my_data, content_type='application/vnd.ms-excel')
>>> response['Content-Disposition'] = 'attachment; filename="foo.xls"'
#设置响应头信息
response = HttpResponse('hello')
response.__setitem__('hello','123')
response = HttpResponse('hello')
response['uname']='zhangsan'
response.setdefault('Server','WBS')
随堂笔记:
def setRequestInfo(request):
# mimetype : text/plain text/html
# 第一个参数对应响应实体内容 ---> 页面显示内容
# 后面的可变参数接收到的都是响应头信息和响应行
# response = HttpResponse("hello world!", content_type="text/plain")
response = HttpResponse("<h1>hello world!</h1>", content_type="text/html")
# 设置响应头信息
response["Server"] = "ZidingyiServer/1.5" # 更改已有的
response["Age"] = "123" # 添加自定义的
response.status_code = 302 # 状态码
return response
HttpResponse 对象
常见的子类对象:
HttpResponseRedirect() 302 重定向
HttpResponsePermanentRedirect() 301 永久性重定向
JsonResponse()
FileResponse()