20181030django day2 請求、響應、cookie、session、類檢視
一、請求
1、url擷取,例如http://127.0.0.1:8000/class/room/tianye/19
子app路由擷取:
url(r'room/([a-z]+)/([0-9]+)', views.room),
檢視:
def room(request,name,age):
return HttpResponse('name:'+name+'age'+age)
2、查詢字串,如http://127.0.0.1:8000/class/room/?name=tianye&age=19
路由:
# 1.2、get去引數 url(r'room/$',views.person)
檢視:
# 1.2、get方式獲取資料
def person(request):
name = request.GET.get('name')
age = request.GET.get('age')
return HttpResponse('name:'+name+',age:'+age)
3、請求體(body)中傳送的資料,比如表單資料、json、xml;
# 1.3、路由請求體(body)中傳送的資料,比如表單資料、json、xml;
url(r'json_data/$',views.get_json)
# 1.3、請求體(body)中傳送的資料,比如表單資料、json、xml; def get_json(request): body = request.body print(body) json_data = json.loads(body) print(json_data) return HttpResponse(json.dumps(json_data))
4、在http報文的頭(header)中,包括自定義頭和取系統的頭。
注意:自定義頭的key,系統會自動新增HTTP_,所以取得時候需要處理!
# 1.4、系統請求頭和自定義請求頭獲取 def get_head(request): content_type = request.META['CONTENT_TYPE'] content_name = request.META['HTTP_NAME'] print(content_type) print(content_name) return HttpResponse('nihao')
二、響應:
1、通過Httpresponse,可以通過res['name'] = 'ty',新增響應頭
# 2.1、HttpResponse響應:Response(content=響應體, content_type=響應體資料型別, status=狀態碼)
def get_res(request):
# 方式一:
# return HttpResponse('python','Content-Type: text/Html',status=200)
#方式二:
res = HttpResponse('python1', 'Content-Type: text/Html', status=200)
res['name'] = 'ty' # 自定義響應頭
return res
2、
若要返回json資料,可以使用JsonResponse來構造響應物件,作用:
- 幫助我們將資料轉換為json字串
- 設定響應頭Content-Type為 application/json
# 2.2JsonResponse響應返回json,注意返回的放一個字典即可
def get_json(request):
return JsonResponse({"name": "田野", "age": "18"})
三、cookie
1、cookie特點:
- Cookie以鍵值對的格式進行資訊的儲存。
- Cookie基於域名安全,不同域名的Cookie是不能互相訪問的
- 當瀏覽器請求某網站時,會將瀏覽器儲存的跟網站相關的所有Cookie資訊提交給網站伺服器。
2、設定Cookie
可以通過HttpResponse物件中的set_cookie方法來設定cookie。
HttpResponse.set_cookie(cookie名, value=cookie值, max_age=cookie有效期)
- max_age 單位為秒,預設為None。如果是臨時cookie,可將max_age設定為None。
示例:
3 讀取Cookie
可以通過HttpRequest物件的COOKIES屬性來讀取本次請求攜帶的cookie值。request.COOKIES為字典型別。
# 3、cookie
def get_cookie(request):
# 1、讀取cookie
cookie1 = request.COOKIES.get('my_cookie')
print(cookie1)
# print('*'*100)
# 2、設定cookie HttpResponse.set_cookie(cookie名, value=cookie值, max_age=cookie有效期)
res = HttpResponse('ok')
res.set_cookie('my_cookie','ty',max_age=3600)
return res
四、類檢視
# 4、配置類檢視as_view()
url(r'register/$',views.RegisterView.as_view())
通過
views.RegisterView.as_view()方法內部是一個閉包,返回一個view,執行view方法,進入dispatch()
dispatch()方法內部判斷request.method方法是否是類裡的方法,如果是則執行。
@classonlymethod
def as_view(cls, **initkwargs):
"""Main entry point for a request-response process."""
for key in initkwargs:
if key in cls.http_method_names:
raise TypeError("You tried to pass in the %s method name as a "
"keyword argument to %s(). Don't do that."
% (key, cls.__name__))
if not hasattr(cls, key):
raise TypeError("%s() received an invalid keyword %r. as_view "
"only accepts arguments that are already "
"attributes of the class." % (cls.__name__, key))
def view(request, *args, **kwargs):
self = cls(**initkwargs)
if hasattr(self, 'get') and not hasattr(self, 'head'):
self.head = self.get
self.request = request
self.args = args
self.kwargs = kwargs
return self.dispatch(request, *args, **kwargs)
view.view_class = cls
view.view_initkwargs = initkwargs
# take name and docstring from class
update_wrapper(view, cls, updated=())
# and possible attributes set by decorators
# like csrf_exempt from dispatch
update_wrapper(view, cls.dispatch, assigned=())
return view
def dispatch(self, request, *args, **kwargs):
# Try to dispatch to the right method; if a method doesn't exist,
# defer to the error handler. Also defer to the error handler if the
# request method isn't on the approved list.
if request.method.lower() in self.http_method_names:
handler = getattr(self, request.method.lower(), self.http_method_not_allowed)
else:
handler = self.http_method_not_allowed
return handler(request, *args, **kwargs)
檢視類裝飾方法一:
在路由中裝飾:
在視圖裡寫閉包函式my_decorator(func)
def my_decorator(func):
def wrapper(request, *args, **kwargs):
print('自定義裝飾器被呼叫')
print('請求路徑%s' % request.path)
return func(request, *args, **kwargs)
return wrapper
路由中對as_view()進行裝飾
url(r'register/$', my_decorator(views.RegisterView.as_view()))
檢視類裝飾方法二:
給類裝飾
需要引入包
from django.utils.decorators import method_decorator
使用method_decorator原因是,如果直接給方法裝飾,方法裡第一個引數是self,但是閉包裡的方法第一個屬性是request,所以method_decorator預設會給方法第一個引數加入self。
# 單獨裝飾函式,name寫入函式名,如果裝飾所有的函式需要name='dispatch'
@method_decorator(my_decorator, name='get')
class RegisterView(View):
'''類檢視:處理註冊'''
def get(self, request):
'''處理註冊頁面,返回註冊頁面'''
print(request.method)
# return render(request, './static_files/register.html')
return HttpResponse('get')
def post(self, request):
'''處理註冊頁面,返回註冊頁面'''
print(request.method)
# return render(request, './static_files/register.html')
return HttpResponse('post')
檢視類裝飾方法三:
用一個擴充套件類去模擬View的as_view()方法,並去裝飾
# 4.3第三種方式裝飾檢視類
url(r'DemoView/$', views.DemoView.as_view())
class MyDecoratorMixin(View):
@classmethod
def as_view(cls, *args, **kwargs):
view = super().as_view(*args, **kwargs)
view = my_decorator(view)
return view
class DemoView(MyDecoratorMixin):
def get(self, request):
print('get方法')
return HttpResponse('ok')
def post(self, request):
print('post方法')
return HttpResponse('ok')