• 12-Django-基础篇-HttpRequest对象



    前言

    • 本篇来学习Django中的HttpRequest对象

    URL路径参数

    • urls.py
    from django.urls import path
    from book01.views import index, shop
    
    urlpatterns = [
        path('index/', index),
        path('/', shop),
    ]
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 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 格式数据
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

    查询字符串

    • 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对象 
    
        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 格式数据
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20

    在这里插入图片描述

    表单类型

    # 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('/', shop),
        path('register/', register),  
    ]
    
    # views.py
    def register(request):
        print(request.POST)  # 
    
        name = request.POST.get('name')
        age = request.POST.get('age')
        city = request.POST.get('city')
    
        return JsonResponse({'name': name, 'age': age, 'city': city})
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    curl --location --request POST 'http://127.0.0.1:8000/book01/register/' \
    --form 'name="小白"' \
    --form 'age="28"' \
    --form 'city="北京"'
    
    • 1
    • 2
    • 3
    • 4

    *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('/', 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))  # 
        res = json.loads(body)
        print(res)  # {'name': '大海', 'age': 28, 'city': '北京'}
        print(type(res))  # 
        return JsonResponse(res)
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    curl --location --request POST 'http://127.0.0.1:8000/book01/json/' \
    --header 'Content-Type: application/json' \
    --data-raw '{
        "name": "大海",
        "age": 28,
        "city": "北京"
    }'
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

    在这里插入图片描述

    请求头

    #  urls.py
    from django.urls import path
    from book01.views import index, shop, register, json_view, get_headers
    
    urlpatterns = [
        path('index/', index),
        path('/', 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)
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17

    常见请求头
    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('/', 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})
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26

    在这里插入图片描述

    验证路径中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('/', shop),
        path('register/', register),
        path('json/', json_view),
        path('header/', get_headers),
        path('method/', method),
        # 转换器:变量名
        path('//', phone),
    ]
    # urls.py
    def phone(request, city, phone_number, age):
        return JsonResponse({'city': city, 'phone_number': phone_number, 'age': age})
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
  • 相关阅读:
    如何快速集成Android版Serverless认证服务-手机号码篇
    Jacobi迭代的MPI进阶——计算通信重叠和虚拟进程的使用
    机器学习_10、集成学习-随机森林
    优先级队列的使用及模拟实现
    新学期的分享,立个flag吧
    开闭环系统性能分析(稳定性、收敛性、可控性)
    【Python】从0开始的Django基础
    (附源码)springboot高校宿舍交电费系统 毕业设计031552
    详细设计结构化程序和人机界面设计
    “JS逆向 | Python爬虫 | 动态cookie如何破~”
  • 原文地址:https://blog.csdn.net/IT_heima/article/details/126089251