万事开头难

02 django请求\响应相关信息,cbv\fbv,有名\无名分组

一. request请求相关信息

request 请求相关信息:
request.mothod  # 当前请求方法
request.path       # 请求路径
request.POST      # QueryDict是django加工出来的新的字典对象,其实还是继承的python的字典然后拓展的功能
request.boby # post请求方法写的数据的原始数据
b'username=root&password=123'
request.GET # 不是get请求方法携带的数据,而是网址上的查询参数数据
request.get_full_path() # 携带查询参数的路径 /index/?a=1&b=2

二.响应相关信息

from django.shortcuts import render,HttpResponse,redirect
from django.http import JsonResponse


render : 响应html文件数据的
HttpResponse  响应字符串数据
redirect : 重定向
JsonResponse: 响应json格式数据的

 

三.有名分组 and 无名分组

伪代码:
'''
请求来了之后
path = request.path
import re
for item in urlpatterns:
    if re.match('^home/',path):
        home()
        break
    
'''

1.匹配 / 路径

url(r'^$', views.home),  # 匹配根路径

2.无名分组


# 无名分组: 将匹配到的数据以位置传参的形式传递给了book函数

url:
# url(r'^book/(\d+)/(\d+)/', views.book) views: def book(request,month,year): print('year>>>>',year, type(year)) # year都是字符串数据 print('month>>>>',month, type(month)) # month都是字符串数据 # select * from ... where year=year res = f"{year}--{month}--book" # var a = `${name}` # '{}'.format return HttpResponse(res) # 这个month和year会自动接收url的两个\d+ 然后传入到book函数中

3. 有名分组

有名分组:
将匹配到的数据以关键字传参的形式传递给book函数,而book的形参名称必须有一个year和一个month,位置不固定
url:
    url(r'^book/(?P<year>\d+)/(?P<month>\d+)/', views.book),
views:
    def book(request,month,year):

      print('year>>>>',year, type(year))  # year都是字符串数据
    print('month>>>>',month, type(month))  # month都是字符串数据

    # select * from ... where year=year
    res = f"{year}--{month}--book"
    # var a = `${name}`
    # '{}'.format

    return HttpResponse(res)   

4.注意点

    # ^/book/ 错误的!  前置导航斜杠不需要自己写,django帮你做了
    # 写正则时,注意,别写冲突了,不然导致后面有些路径就失效了

四 cbv and fbv

fbv:

url:
    url(r'login/',views.home)
views:
def login(request):
    if request.method == 'GET':
        return render(request,'login.html')

    else:
        username = request.POST.get('username')
        if username == 'laobai':
            return redirect('/home/')
        else:
            return HttpResponse('你不是至尊会员')
    

cbv:

url:
    url(r'^book/',views.BookView.as_view())
views:
    先要引入
    from django.views import View

class BookView(View):
    def get(self,request):
        print('来了')
        return HttpResponse('book')
    def post(self,request):
        pass

 

posted @ 2021-02-01 22:17  Bo7-w  阅读(55)  评论(0编辑  收藏  举报