【django】HttpRequest对象的属性和路由补充

导读:本篇文章讲解 【django】HttpRequest对象的属性和路由补充,希望对大家有帮助,欢迎收藏,转发!站点地址:www.bmabk.com

在这里插入图片描述


一、HttpRequest对象的常用属性

1、request.GET:获取查询字符串参数

/crm/login?name=kobe&age=22
查询字符串参数:问号后面的key=value表示查询字符串参数。

路径参数表示:path(‘students/int:year/int:mouth/
路径参数在视图函数中用形式参数接收
get(self,request,mouth,year):

如果查询字符串参数中多个相同的参数,用get获取的是最后一个参数
可以采用getlist来进行获取多个相同的参数

案例:

http://127.0.0.1:8000/crm/login?name=kobe&age=22&name=zilv
print(self.request.GET.get('name',None))			zilv
print(self.request.GET.getlist('name','age'))		['kobe', 'zilv']

特别注意:

在drf框架中获取查询字符串参数也使用:request.query_params和request.GET

2、request.POST:post请求数据,只能获取表单参数

在这里插入图片描述

3、request.body:请求body,响应结果为字节类型

self.request.body

输出结果:

b'{\r\n    "name":"kobe",\r\n    "age":18\r\n}'

解码后并转化为字典格式的数据:

value=json.loads(self.request.body.decode(encoding='utf-8'))

输出结果

{'name': 'kobe', 'age': 18}

4、request.method:获取请求方法

5、request.user:获取当前访问的用户

6、request.path:当前请求路径

7、request.encoding:当前编码方式

8、request.FILES:客户端上传的文件

9、request.headers:客户端传递的请求头

二、路由

1、路径转换器

str(多):默认就是使用字符串类型的,匹配除了路径分隔符/之外的任何非空字符串

path('student/<str:pk>/',views.student_detail)
等同于
path('student/pk',views.student_detail)

案例:

路由:

urlpatterns=[
	path('students/<year>/<mouth>/',views.LoginView.as_view()),
	等同于	
	path('students/<str:year>/<str:mouth>/',views.LoginView.as_view()),
]

视图

class LoginView(View):

    def get(self,request,year,mouth):
        print(year)
        print(mouth)
        return JsonResponse({'year':year,'mouth':mouth})

输出结果:

{
    "year": "2022",
    "mouth": "12"
}

int(多):匹配0或者任意整数。并且返回的参数也是整数类型

案例

http://127.0.0.1:8000/crm/students/2022/dfg/

当传入非数字时:会报错

urlpatterns=[
	path('students/<int:year>/<int:mouth>/',views.LoginView.as_view()),
]

输出结果:

{
    "year": 2022,
    "mouth": 12
}

slug:匹配任何由ascii字符或者数字、下划线组成的

uuid:匹配格式化的uuid

path:匹配任何非空字符,包含路径分隔符

2、正则路由匹配re_path

1、re_path需要导入:from django.urls import path,re_path
路由开头将path替换为re_path
2、括号中以r开头,防止转义
3、路由路径最开始使用^开头:^students:表示路径最开始以students开头
4、路由路径结尾使用$结尾:/$:表示路由以/结尾

案例:不分组命名

当将mouth和year进行调换位置

class LoginView(View):

    def get(self,request,mouth,year):
        print(year)
        print(mouth)
        return JsonResponse({'year':year,'mouth':mouth})

路由

urlpatterns=[
    re_path(r'^students/(\d{4})/([1-9]|1[0-2])/$',views.LoginView.as_view())
]

输出结果:不正常了

{
    "year": "12",
    "mouth": "2022"
}

案例:分组命名

当将mouth和year进行调换位置

class LoginView(View):

    def get(self,request,mouth,year):
        print(year)
        print(mouth)
        return JsonResponse({'year':year,'mouth':mouth})
urlpatterns=[
    re_path(r'^students/(?P<year>\d{4})/(?P<mouth>[1-9]|1[0-2])/$',views.LoginView.as_view())
]

输出结果:

{
    "year": "2022",
    "mouth": "12"
}

在这里插入图片描述

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

文章由极客之家整理,本文链接:https://www.bmabk.com/index.php/post/73923.html

(0)
小半的头像小半

相关推荐

极客之家——专业性很强的中文编程技术网站,欢迎收藏到浏览器,订阅我们!