HttpRequest对象
1、url路径参数
http:127.0.0.1:8000/10/188
视图中函数,参数位置不能变
def shop(request,city_id,shop_id): # print(cat_id, goods_id) return JsonResponse({‘city_id’:city_id, ‘shop_id’:shop_id})
应用中的urls
path(’<city_id>/<shop_id>/’,shop),
http://127.0.0.1:8000/1/2/?order=readcount&page=1&order=commentcount
def shop(request,city_id,shop_id): query_params = request.GET print(query_params) print(query_params.get(‘order’)) print(query_params.getlist(‘order’)) return JsonResponse({‘city_id’:city_id, ‘shop_id’:shop_id})
2、post请求
403 默认禁止访问,禁用middleware
3、发送post数据
def json(request):
body = request.body
print(body)
body_str = body.decode()
print(body_str)
return HttpResponse('ok')
4、请求头
header = request.META print(header)
5、路径参数校验
path(‘int:city_id/<shop_id>/’,shop),
6、自定义转换器
# 1. 定义转换器
class MobileConverter:
# 验证数据的关键是: 正则
regex = '1[3-9]\d{9}'
# 验证没有问题的数据,给视图函数
def to_python(self, value):
return value
register_converter(MobileConverter,'phone')
path('<int:city_id>/<phone:shop_id>/',shop),
HttpResponse对象
1、响应结果
def response(request):
response = HttpResponse('res', status=200)
response['name']='张三'
# 1XX
# 2XX
# 200 成功
# 3XX
# 4XX 请求错误
# 403 禁止访问,权限问题
# 404 找不到页面,路由问题
#
# 5XX 响应错误
return response;
2、JsonResponse
dict = {‘name’:‘zhangsan’, ‘age’:18} response = JsonResponse(dict)
集合
girls = [
{
'name':'xiaoli',
'age':18
},
{
'name':'cunhua',
'age':'17'
}
]
response = JsonResponse(data=girls, safe=False)
3、redirect重定向
return redirect(‘www.baidu.com’)
状态保持
Cookie
http://127.0.0.1:8000/set_cookie/?username=ls&password=123
def set_cookie(request):
# 1. 获取查询字符串数据
username = request.GET.get('username')
password = request.GET.get('password')
print(username, password)
# 2. 服务器设置cookie信息
# 通过响应对象.set_cookie 方法
response = HttpResponse('set_cookie')
# key, value=''
# max_age 是一个秒数 从响应开始 计数的一个秒数
response.set_cookie('name', username, max_age=60*60)
response.set_cookie('password', password)
return response
http://127.0.0.1:8000/get_cookie
def get_cookie(request):
# 获取cookie
print(request.COOKIES)
# request.COOKIES 字典数据
name = request.COOKIES.get('name')
return HttpResponse(name)
session
http://127.0.0.1:8000/set_session/?username=zs
def set_session(request):
# 1. 模拟 获取用户信息
username = request.GET.get('username')
# 2. 设置session信息
# 假如 我们通过模型查询 查询到了 用户的信息
user_id = 1
request.session['user_id'] = user_id
request.session['username'] = username
# clear 删除session里的数据,但是 key有保留
# request.session.clear()
# flush 是删除所有的数据,包括key
# request.session.flush()
request.session.set_expiry(3600)
return HttpResponse('set_session')
http://127.0.0.1:8000/get_session/
def get_session(request):
# user_id=request.session['user_id']
# username=request.session['username']
user_id=request.session.get('user_id')
username=request.session.get('username')
# '%s'%username
content = '{} ,{}'.format(user_id,username)
return HttpResponse(content)
|