Django学习日志05
视图层
三板斧的使用
HttpResponse: 字符串
render:渲染html页面
redirect:重定向的
"""在视图文件中写视图函数的时候不能没有返回值了,默认返回的是None,页面上就会报错"""
def render(request, template_name, context=None, content_type=None, status=None, using=None):content = loader.render_to_string(template_name, context, request, using=using)return HttpResponse(content, content_type, status)
JsonResponse序列化类的使用
序列化
json格式的数据
{"a":1}
json有什么用:
跨语言传输
序列化:json.dumps
反序列化:json.loads
from django.http import JsonResponse
def index(request):# user_dict = {'username':'kevin你好'}user_dict = [1, 2, 3, 4]# res=json.dumps(user_dict,ensure_ascii=False)# return HttpResponse(res)# 通过看源码学技术# return JsonResponse(user_dict,json_dumps_params={'ensure_ascii':False})return JsonResponse(user_dict,safe=False)# return render(request,'index.html')
form表单上传文件
表单上传数据需要满足的条件
<form action="" method="post">
1. 请求方式必须是post
2. enctype="multipart/form-data"
print(request.POST) # 接收的都是普通的数据,非文件数据# <MultiValueDict: {'myfile': [<InMemoryUploadedFile: 234.png (image/png)>]}>
print(request.FILES) # 只接受文件数据,普通数据还在request.POST里面
def index(request):# user_dict = {'username':'kevin你好'}user_dict = [1, 2, 3, 4]# res=json.dumps(user_dict,ensure_ascii=False)# return HttpResponse(res)# 通过看源码学技术# return JsonResponse(user_dict,json_dumps_params={'ensure_ascii':False})# return JsonResponse(user_dict,safe=False)# return JsonResponse(user_dict,safe=False)# <QueryDict: {'myfile': ['234.png']}># <QueryDict: {}>print(request.POST)# <MultiValueDict: {'myfile': [<InMemoryUploadedFile: 234.png (image/png)>]}>file_obj=request.FILES.get('myfile')# file_list = file_obj.name.split('.') # 123.png# import uuid# random_str=str(uuid.uuid4())# file_name = random_str + file_obj.name.split('.')[-1]# with open(file_name, 'wb') as f:# for line in file_obj:# f.write(line)# print(request.body) # 接收纯原生的二进制数据,没有任何的处理 b''----> str---->decode---->dict...# print(request.POST.get('')) # 之所以你能够直接按照字典的方式取值,是因为django给做了封装print(request.path) # /index/ /index/print(request.path_info) # /index/ /index/print(request.get_full_path()) # /index/ /index/?a=1&b=2print(request.GET.get(''))return render(request,'index.html')
CBV的写法
FBV: function based view # 写的都是函数
CBV: class based view # 写的都是类
from django.views import Viewclass MyLogin(View):def get(self, request):print('get。。。')return HttpResponse("get")def post(self, request):return HttpResponse("hello postman!!!")url(r'^login/', views.MyLogin.as_view()),
CBV的源码分析
# 入口
url(r'^login/', views.MyLogin.as_view()),# View类中得as_view方法的返回值是view函数名
# 当请求来的时候,会触发view函数的执行
def view(request, *args, **kwargs):# cls:Mylogin()------>self对象self = cls(**initkwargs)return self.dispatch(request, *args, **kwargs) # View类里的dispatchdef dispatch(self, request, *args, **kwargs):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_allowedreturn handler(request, *args, **kwargs)from django.views import Viewclass MyLogin(View):http_method_names = ['get', 'post']def get(self, request):print('get。。。')self.index()return HttpResponse("get")def post(self, request):return HttpResponse("hello postman!!!")def index(self):pass
权限、频率、jwt的源码
模板层值模版变量
在html页面中写一个python的代码
PHP:不是后端语言,前端 操作数据量,写逻辑,都可以
python也有点像
{{ 写变量 }}
{% 写逻辑 %}
{{ d.0 }}
{{ d.1 }}
{{ d.3 }}
{{ user_dict.hobby.2 }}
{{ index }}
{{ obj.score }}