def login(request):
# token 使用
# secret 字符串只有服务端知道,用来解析token。
# username 等字段存在payload中,和header 中的信息一起作为 base64编码。
# 最后的 signature 是根据 header,payload 和 secretKkey 加密之后的结果。
# header,payload,signature之间用 . 连在一起组成了 token
# header,payload 可以分别用base64 解密。
# token 是 btypes 类型,所以需要转换为 str才能 被json 序列化。
# btypes 和 str 互转 str(b, encoding = "utf-8") ,btypes(str, encoding = "utf-8")
# token = jwt.encode({'username':'roadaspen'},'secret',algorithm='HS256')
# data = {"status":"成功","token":str(token,encoding="utf-8")}
# return HttpResponse(json.dumps(data),content_type="application/json")
# Content-Type
# 如果是 form 需要上传文件时,或者单纯地使用form提交数据的时候, 用 content-type 为 multipe/form-data,用request.POST 接收,接收到的数据类型为 querydict ,使用 request.POST['key']获取相应的值。
# 如果是 ajax,content-type 默认为 x-www-form-urlencode,用request.body 接收,值的表现形式为 key=value&key=value 的 btypes类型,
# 当提交数据类型content-type 为 application/json时,用request.body 接收,值的表现形式为 {key:vaule,key:value} 的 json字符串,使用 json.loads()解析,使用get获取 key值对应的value
# form-data / application/x-www-form-urlencoded
# print(request.body)
# print(request.POST.get('username'))
# print(request.POST['username']) admin
# # application/json
# print(request.body) # b"{username:admin}"
# print(json.loads(request.body)) #admin
# print(json.loads(request.body)['username']) #admin
# 设置 session
# 使用 request.session[key] = value 来设置 session,直接存储进 django 的 django_session数据库中。
# 同样的浏览器的cookies中也出现一条session_id,每次请求时都会讲 session_id随着请求一起传递
#request.session['h1']='hello' # 登录时执行,写 session
# h1=request.session.get('h1') hello 读session
#del request.session['h1'] # 删除 session 中指定的值
#request.session.clear() # 删除 session 中的值
#request.session.flush() # 键和值一起清空
# 设置cookie
# resp = HttpResponse('ok')
# resp.set_cookie('hello', 'roadaspen', max_age=60*60*24*7)
# 删除cookie
# 删除的是请求传过来的cookie,浏览器的还是没有删掉
#del request.COOKIES['my']
# 浏览器 对应的 cookie 键值删除了
#resp.delete_cookie('hello')
# 获取cookie
# print(request.COOKIES.get('hello'))
# print(request.COOKIES['sessionid'])
return HttpResponse("ok")