12-Django-基础篇-HttpRequest对象
Posted 爱学习de测试小白
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了12-Django-基础篇-HttpRequest对象相关的知识,希望对你有一定的参考价值。
HttpRequest对象
前言
- 本篇来学习Django中的HttpRequest对象
URL路径参数
- urls.py
from django.urls import path
from book01.views import index, shop
urlpatterns = [
path('index/', index),
path('<city_id>/<shop_id>', shop),
]
- views.py
from django.http import HttpResponse, JsonResponse
def index(request):
return HttpResponse("Book01")
def shop(request, city_id, shop_id):
return JsonResponse('city_id': city_id, 'shop_id': shop_id) # 返回json 格式数据
查询字符串
-
HttpRequest对象的属性GET、POST都是QueryDict类型的对象
-
与python字典不同,QueryDict类型的对象用来处理同一个键带有多个值的情况
-
方法get():根据键获取值
-
如果一个键同时拥有多个值将获取最后一个值
-
如果键不存在则返回None值,可以设置默认值进行后续处理
-
get(‘键’,默认值)
-
-
方法getlist():根据键获取值,值以列表返回,可以获取指定键的所有值
-
如果键不存在则返回空列表[],可以设置默认值进行后续处理
-
getlist(‘键’,默认值)
-
-
-
URL:http://127.0.0.1:8000/book01/2022/0806?city=北京&city=鞍山&name=小白&age=28
# views.py
from django.http import HttpResponse, JsonResponse
from django.shortcuts import render
def index(request):
return HttpResponse("Book01")
def shop(request, city_id, shop_id):
print(request.GET) # QueryDict对象 <QueryDict: 'city': ['北京', '鞍山'], 'name': ['小白'], 'age': ['28']>
city = request.GET.get('city') # 鞍山
print(city)
city_list = request.GET.getlist('city')
print(city_list) # ['北京', '鞍山']
name = request.GET.get('name') # 小白
age = request.GET.get('age') # 28
return JsonResponse('city_id': city_id, 'shop_id': shop_id, 'city': city,
'city_list': city_list, 'name': name, 'age': age) # 返回json 格式数据
表单类型
# settings.py
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
# 'django.middleware.csrf.CsrfViewMiddleware', # 需注释,否则post请求返回403
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
# urls.py
from django.urls import path
from book01.views import index, shop, register
urlpatterns = [
path('index/', index),
path('<city_id>/<shop_id>', shop),
path('register/', register),
]
# views.py
def register(request):
print(request.POST) # <QueryDict: 'name': ['小白'], 'age': ['28'], 'city': ['北京']>
name = request.POST.get('name')
age = request.POST.get('age')
city = request.POST.get('city')
return JsonResponse('name': name, 'age': age, 'city': city)
curl --location --request POST 'http://127.0.0.1:8000/book01/register/' \\
--form 'name="小白"' \\
--form 'age="28"' \\
--form 'city="北京"'
*URL: http://127.0.0.1:8000/book01/register/ 后面没有“/”,将返回500错误码
json类型
# urls.py
from django.urls import path
from book01.views import index, shop, register, json_view
urlpatterns = [
path('index/', index),
path('<city_id>/<shop_id>', shop),
path('register/', register),
path('json/', json_view),
]
# views.py
def json_view(request):
body = request.body.decode()
print(body)
"""
必须使用双引号
"name": "大海",
"age": 28,
"city": "北京"
"""
print(type(body)) # <class 'str'>
res = json.loads(body)
print(res) # 'name': '大海', 'age': 28, 'city': '北京'
print(type(res)) # <class 'dict'>
return JsonResponse(res)
curl --location --request POST 'http://127.0.0.1:8000/book01/json/' \\
--header 'Content-Type: application/json' \\
--data-raw '
"name": "大海",
"age": 28,
"city": "北京"
'
请求头
# urls.py
from django.urls import path
from book01.views import index, shop, register, json_view, get_headers
urlpatterns = [
path('index/', index),
path('<city_id>/<shop_id>', shop),
path('register/', register),
path('json/', json_view),
path('header/', get_headers),
]
# views.py
def get_headers(request):
content_type = request.META['CONTENT_TYPE']
print(content_type) # application/json
return HttpResponse(content_type)
常见请求头
CONTENT_LENGTH– The length of the request body (as a string).
CONTENT_TYPE– The MIME type of the request body.
HTTP_ACCEPT– Acceptable content types for the response.
HTTP_ACCEPT_ENCODING– Acceptable encodings for the response.
HTTP_ACCEPT_LANGUAGE– Acceptable languages for the response.
HTTP_HOST– The HTTP Host header sent by the client.
HTTP_REFERER– The referring page, if any.
HTTP_USER_AGENT– The client’s user-agent string.
QUERY_STRING– The query string, as a single (unparsed) string.
REMOTE_ADDR– The IP address of the client.
REMOTE_HOST– The hostname of the client.
REMOTE_USER– The user authenticated by the Web server, if any.
REQUEST_METHOD– A string such as"GET"or"POST".
SERVER_NAME– The hostname of the server.
SERVER_PORT– The port of the server (as a string).
其他请求对象
# urls.py
from django.urls import path
from book01.views import index, shop, register, json_view, get_headers, method
urlpatterns = [
path('index/', index),
path('<city_id>/<shop_id>', shop),
path('register/', register),
path('json/', json_view),
path('header/', get_headers),
path('method/', method),
]
# viwes.py
def method(request):
fun = request.method
print(fun)
user = request.user
print(user)
path = request.path
print(path)
e = request.encoding
print(e)
file = request.FILES
print(file)
return JsonResponse('fun': fun)
验证路径中path参数
# urls.py
from book01.views import index, shop, register, json_view, get_headers, method, phone
from django.urls import register_converter
class MobileConverter:
"""自定义路由转换器:匹配手机号"""
# 匹配手机号码的正则
regex = '1[3-9]\\d9'
def to_python(self, value):
# 将匹配结果传递到视图内部时使用
return int(value)
def to_url(self, value):
# 将匹配结果用于反向解析传值时使用
return str(value)
# 注册自定义路由转换器
# register_converter(自定义路由转换器, '别名')
register_converter(MobileConverter, 'phone_num')
urlpatterns = [
path('index/', index),
path('<city_id>/<shop_id>', shop),
path('register/', register),
path('json/', json_view),
path('header/', get_headers),
path('method/', method),
# 转换器:变量名
path('<int:city>/<phone_num:phone_number>/<age>', phone),
]
# urls.py
def phone(request, city, phone_number, age):
return JsonResponse('city': city, 'phone_number': phone_number, 'age': age)
- 验证
以上是关于12-Django-基础篇-HttpRequest对象的主要内容,如果未能解决你的问题,请参考以下文章