[关闭]
@orangleliu 2016-12-20T11:52:04.000000Z 字数 1718 阅读 2536

django views中 request, response的常用操作

django


以问题的形式记录一些请求和响应的常见写法,django1.8为例子。

request

  1. def hello(request):
  2. data = json.loads(request.body)
  3. ...

json格式还有一些 非表单序列化 的格式,都可以从 request.body 中获取请求体中的数据,对于ajax请求可以使用 request.is_ajax() 来判断

  1. # url http://wificdn.com:8888/wxpay/qrcode2/16122010404238801544?name=lzz
  2. request.get_host() # wificdn.com:8888
  3. request.get_full_path() # u'/wxpay/qrcode2/16122010404238801544?name=lzz'
  4. request.build_absolute_uri('/') # 'http://wificdn.com:8888/'
  5. request.build_absolute_uri('/hello') # 'http://wificdn.com:8888/hello'
  6. request.build_absolute_uri() # 'http://wificdn.com:8888/wxpay/qrcode2/16122010404238801544?name=lzz'
  7. request.path # u'/wxpay/qrcode2/16122010404238801544'
  8. request.scheme # 'http'

response

session

how to use session, 主要是get和set,和删除

  1. def post_comment(request, new_comment):
  2. if request.session.get('has_commented', False):
  3. return HttpResponse("You've already commented.")
  4. c = comments.Comment(comment=new_comment)
  5. c.save()
  6. request.session['has_commented'] = True
  7. return HttpResponse('Thanks for your comment!')
  8. def logout(request):
  9. try:
  10. del request.session['member_id']
  11. except KeyError:
  12. pass
  13. return HttpResponse("You're logged out.")

cookies

  1. def login(request):
  2. response = HttpResponseRedirect('/url/to_your_home_page')
  3. response.set_cookie('cookie_name1', 'cookie_name1_value')
  4. response.set_cookie('cookie_name2', 'cookie_name2_value')
  5. return response
  6. def logout(request):
  7. response = HttpResponseRedirect('/url/to_your_login')
  8. response.delete_cookie('cookie_name1')
  9. response.delete_cookie('cookie_name2')
  10. return response
  11. # 获取
  12. coo = request.COOKIES.get('coofilter')
  13. # cookies 过期时间
  14. hr.set_cookie('user_id', user_id, max_age=300)
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注