@orangleliu
2016-12-20T11:52:04.000000Z
字数 1718
阅读 2536
django
以问题的形式记录一些请求和响应的常见写法,django1.8为例子。
def hello(request):
data = json.loads(request.body)
...
json格式还有一些 非表单序列化
的格式,都可以从 request.body 中获取请求体中的数据,对于ajax请求可以使用 request.is_ajax()
来判断
# url http://wificdn.com:8888/wxpay/qrcode2/16122010404238801544?name=lzz
request.get_host() # wificdn.com:8888
request.get_full_path() # u'/wxpay/qrcode2/16122010404238801544?name=lzz'
request.build_absolute_uri('/') # 'http://wificdn.com:8888/'
request.build_absolute_uri('/hello') # 'http://wificdn.com:8888/hello'
request.build_absolute_uri() # 'http://wificdn.com:8888/wxpay/qrcode2/16122010404238801544?name=lzz'
request.path # u'/wxpay/qrcode2/16122010404238801544'
request.scheme # 'http'
JsonResponse
, from django.http import JsonResponse
就可以使用了,低版本的django可以参照源码自己写一个,几行代码就行了。how to use session, 主要是get和set,和删除
def post_comment(request, new_comment):
if request.session.get('has_commented', False):
return HttpResponse("You've already commented.")
c = comments.Comment(comment=new_comment)
c.save()
request.session['has_commented'] = True
return HttpResponse('Thanks for your comment!')
def logout(request):
try:
del request.session['member_id']
except KeyError:
pass
return HttpResponse("You're logged out.")
def login(request):
response = HttpResponseRedirect('/url/to_your_home_page')
response.set_cookie('cookie_name1', 'cookie_name1_value')
response.set_cookie('cookie_name2', 'cookie_name2_value')
return response
def logout(request):
response = HttpResponseRedirect('/url/to_your_login')
response.delete_cookie('cookie_name1')
response.delete_cookie('cookie_name2')
return response
# 获取
coo = request.COOKIES.get('coofilter')
# cookies 过期时间
hr.set_cookie('user_id', user_id, max_age=300)