12-Django-基础篇-HttpRequest对象

简介: 12-Django-基础篇-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(‘键’,默认值)
# 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]\d{9}'
    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})
  • 验证

相关文章
|
3月前
|
JSON 数据库 数据格式
使用 Django Q 对象构建复杂查询条件
通过本文示例,我们展示了如何使用Django的Q对象来构建复杂的查询条件,以及如何实现分页功能。Q对象的强大之处在于它能够轻松地组合多个查询条件,支持“与”、“或”关系,极大地提高了查询的灵活性和可读性。希望本文对你在实际项目中使用Django ORM构建复杂查询有所帮助。
|
10月前
|
JSON 缓存 程序员
16 Django视图 - HttpResponse对象
16 Django视图 - HttpResponse对象
27 0
|
10月前
|
中间件 API Python
15 Django视图 - HttpReqeust对象
15 Django视图 - HttpReqeust对象
36 0
|
JSON 数据格式 Python
13-Django-基础篇-HttpResponse对象
13-Django-基础篇-HttpResponse对象
|
数据库 Python
Django ORM F对象和Q对象查询
F对象用于操作数据库中某一列的值,它可以在没有实际访问数据库获取数据值的情况下对字段的值进行引用 使用F对象之前需要将它引入当前的环境中:
140 0
Django ORM F对象和Q对象查询
|
Python
Python编程:Django中的Request对象常用属性
Python编程:Django中的Request对象常用属性
145 0
|
JSON 缓存 程序员
Django Response对象3.4
Django Response对象3.4
100 0
Django Response对象3.4
|
中间件 API Python
Django Request对象3.3
Django Request对象3.3
108 0
|
JSON 缓存 JavaScript
Django入门-6:视图-HttpResponse对象
Django入门-6:视图-HttpResponse对象
215 0
|
中间件 API 数据安全/隐私保护
Django入门-6:视图-HttpReqeust对象
Django入门-6:视图-HttpReqeust对象
128 0