A detailed explanation of the common operation of request and response in django views
- 2021-07-22 10:13:44
- OfStack
request
Getting json data from an post request
def hello(request):
data = json.loads(request.body)
...
json format also has 1 non-form serialization format, all of which can get the data in the request body from request. body. For ajax request, you can use request.is_ajax () to judge
Obtain base url according to the requested information (sometimes there are many domain names for service, or need to dynamically splice url information under 1)
# 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'
Get the selected checkbox information in the form, for example, name of checkbox is checks
var_list = request.POST.getlist('checks')
Returns an list object, if it does not return [], and if it does not have this key in the form, it also returns []
response
json format response version 1.8 has provided JsonResponse, from django. http import JsonResponse can be used, the lower version of django can refer to the source code to write one, just a few lines of code. Setting cookies and header in response
def xxxxview(request):
....
resp = HttpResponseRedirect('/account/portal/?token=%s' % es)
resp.set_cookie("coofilter", es, max_age=300)
resp['Erya-Net-Type'] = NET_TYPE
resp['Erya-Auth-Host'] = AUTH_HOST
resp['Erya-Auth-Port'] = AUTH_PORT
resp['Erya-Auth-Uip'] = ip
resp['Erya-Auth-Token'] = es
return resp
session
how to use session, mainly get and set, and delete
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.")
cookies
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
# Get
coo = request.COOKIES.get('coofilter')
# cookies Expired time
hr.set_cookie('user_id', user_id, max_age=300)