Django視圖層
'''
HttpResponse,返回字符串
render,返回html頁面,并且可以給html文件傳值
redirect,重定向
視圖函數一定會返回一個HttpResponse對象
'''
JsonResponse
from django.http import JsonResponse
user_dict = {'姓名': '123', '年齡': '123'}
return JsonResponse(user_dict, {'ensure_ascii': False})
'''ensure_ascii=True是json關鍵字參數默認值,通過向JsonResponse類傳入用于修改這個默認值的字典可以使json不再將中文字符轉為unicode編碼'''
user_hobby_list = [1,2,3,4,5,6]
return JsonResponse(user_hobby_list,safe=False)
# 將非字典類型序列化需要將safe參數值設置為False
# 前后端序列化與反序列化
javascript | python
---|---
JSON.stringify() | json.dumps()
JSON.parse() | json.loads()
form表單上傳文件及后端獲取
# form表單上傳文件類型的數據:1.method指定為post 2.enctype指定為form-data
# request.POST只能獲取普通鍵值對信息
'''
<form action="" method="post" enctype="multipart/form-data">
<p>username:<input type="text" name="username" class="form-control"></p>
<p>password:<input type="text" name="password" class="form-control"></p>
<p>file:<input type="file" name="file"></p>
<input type="submit" value="提交">
</form>
def upload_file(request):
if request.method == 'POST':
file_obj = request.FILES.get('file')
with open(file_obj.name,'wb') as f: # 沒有指定文件路徑,默認保存在項目文件夾下
for line in file_obj:
f.write(line)
return render(request,'form.html')
'''
request對象方法
'''
request.method
request.POST
request.GET
request.Files
request.path/request.path_info 只獲取路由部分
request.get_full_path() 獲取用戶提交url中除去ip和port后所有的路徑信息(包含?后的參數)
request.body 瀏覽器發來的原生二進制數據
'''
FBV與CBV
# 視圖層既可以是視圖函數,也可以是類
url(r'^login/', views.MyLogin.as_view(), name='app02_login'),
class MyLogin(View):
def get(self, request):
return HttpResponse('你提交了get請求,這個請求被django識別并交由這里的代碼處理')
def post(self,request):
return HttpResponse('你提交了post請求,這個請求被django識別并交由這里的代碼處理')
CBV源碼
url('login/',views.MyLogin.as_view()),
# 回顧,函數名/方法名()執行優先級最高
@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(
'The method name %s is not accepted as a keyword argument '
'to %s().' % (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) # self = MyLogin(**initkwargs) 產生一個Mylogin對象
self.setup(request, *args, **kwargs)
if not hasattr(self, 'request'):
raise AttributeError(
"%s instance has no 'request' attribute. Did you override "
"setup() and forget to call super()?" % cls.__name__
)
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
# as_view()內定義了閉包函數view(),并且返回值就是view函數的內存地址,在django啟動后立即執行as_view(),即得:
url('login/',views.view),
浙公網安備 33010602011771號