??hello!我是wakeyo_J,每天一个小知识,一起学python,让技术无限发散。
1. 请求
1.1 什么是请求?
??在应用网络中,请求是浏览器(客户端)通过http协议或https向服务器发送请求并获取数据。 
1.2 Django中前后端传递参数的方式
?①查询字符串参数 ?②请求体参数 ??- form表单传参 ??- json格式参数 ??- 上传文件 ?③请求头传参 ?④路径参数 ??- url路径中的参数
1.3 简单的Django项目请求操作
1.4 请求的分类
①请求路径(路由)的方式,地址带上参数的方式
- 127.0.0.1:8000/weather/beijing/20220503/ 查询一个城市的天气
def weather(request,city,date):
print(city)
print(date)
return HttpResponse('天气查询成功!')
from django.urls import path
from django.urls import re_path
from . import views
urlpatterns = [
path(r"index/",views.index,name='index'),
re_path('^index1/$',views.index1,name='index1'),
re_path(r'^weather/(?P<city>[a-z]+)/(?P<date>\d{8})/$',views.weather),
]
②查询的请求方式:即请求的参数不需要写到url,到请求(request)中去获取
def weather(request,city,date):
print(city)
print(date)
return HttpResponse('天气查询成功!')
def querys(request):
print(request)
a = request.GET.get('a')
b = request.GET.get('b')
print(a)
print(type(a))
print(b)
return HttpResponse('请求获取数据')
③表单类型的查询和数据获取  在开始表单的请求参数获取前,我们需要安装一个软件postman,具体的软件使用方式可访问https://www.jianshu.com/p/6c9b45994c34
- 表单请求参数的获取采用的是post请求,先进行相应的代码编写,在原有的函数中新增代码即可
def querys(request):
print(request)
a = request.GET.get('a')
b = request.GET.get('b')
print(a)
print(type(a))
print(b)
print('--'*40)
print(request)
name = request.POST.get('name')
print(name)
return HttpResponse('请求获取数据')
- 然后运行项目,点击postman中的send发送请求,你会出现如下错误
 现在,需要我们到项目的setting的中间件中将 'django.middleware.csrf.CsrfViewMiddleware’这行代码注释,我们就能够看到获取到的数据被打印出来。   postman的响应结果  ④非表单参数请求(除表单以外的数据为非表单数据,如json,xml等,可用get或post请求) - json数据请求数据获取
- (1)先编写相应的视图函数
def get_body_json(request):
"""
# 非表单数据
:param request:
:return:
"""
print(request)
data = request.body
print(data)
sr_data = data.decode()
print(sr_data,type(sr_data))
import json
json_data = json.loads(sr_data,encoding="utf-8")
print(json_data,type(json_data))
return HttpResponse('json数据请求成功!')
path('json/',views.get_body_json),
path('image/',views.Image),
2. 响应
在网络应用中有请求就存在响应,这部分主要使用HttpResponse,JsonResponse(JsonResponse继承HttpResponse)。 
①写一个简单的响应视图函数
from django.http import HttpResponse,JsonResponse
def demo_fun(request):
data = {
'city':'bj','subject':'123'
}
return JsonResponse(data=data,safe=True)
②写相应的子路由
path('demo/',views.demo_fun),
③通过postman发送 
3. GET和POST的区别

总结
??本文属于作者原创,转载请注明出处,不足之处,希望大家能过给予宝贵的意见,如有侵权,请私信。每天一个小知识,一起学python,让技术无限发散
|