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(‘键’,默认值)

  • 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]\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})
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

爱学习de测试小白

你的鼓励将是我创作的最大动力!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值