django_day03
2024-10-20 16:17:51
django_day03
Django的view(视图)
CBV和FBV
FBV:function based view 基于函数的视图
CBV:class based view 基于类的视图
from django.views import View class Xxx():
def get(self,request):
#专门处理get请求
return response
def post(self,request):
#专门处理post请求
return responseurl(r'xx/',Xxx.as_view())
class PublisherAdd(View): def get(self,request):
print("get请求被执行")
#处理get请求
return render(request, 'publisher_add.html') def post(self,request):
print("post请求被执行")
#处理post请求
pub_name = request.POST.get('pub_name')
#print(pub_name)
if not pub_name:
# 输入为空
return render(request, 'publisher_add.html', {'error': '不能为空!!'})
if models.Publisher.objects.filter(name=pub_name):
return render(request, 'publisher_add.html', {'error': '已存在!'})
ret = models.Publisher.objects.create(name=pub_name)
#print(ret, type(ret))
return redirect('/publisher_list/')
urlpatterns = [
url(r'^publisher_add/', views.PublisherAdd.as_view()),
]
as_view流程
项目运行时加载urls.py的文件 执行类as_view方法
as_view()执行后 内部定义了一个view函数 并且返回
请求到来的时候,执行view函数:
实例化类--》self
self.request = request
执行self.dispatch(request, *args, **kwargs)的方法
判断请求方式是否被允许
允许:
通过反射获取请求方式对应的请求方法 ——》 handler
获取不到 self.http_method_not_allowed ——》 handler
不允许:
self.http_method_not_allowed ——》 handler
执行handler,返回结果
from functools import wraps def timer(func):
@wraps(func)#不加的话获取的方法一直时inner wraps原理
def inner(request, *args, **kwargs): start = time.time()
ret = func(request, *args, **kwargs)
print('执行的时间是:{}'.format(time.time() - start))
return ret return inner
FBV
直接加在函数上就行
CBV加装饰器:
需要使用一个装饰器
from django.utils.decorators import method_decorator
加在方法上
@method_decorator(timer)
def get(self, request):
加在dispatch方法上
@method_decorator(timer)
def dispatch(self, request, *args, **kwargs):
# 之前的操作
ret = super().dispatch(request, *args, **kwargs) # 执行View中的dispatch方法
# 之后的操作
return ret3 @method_decorator(timer,name='dispatch')
class PublisherAdd(View):
加在类上
@method_decorator(timer,name='post')
@method_decorator(timer,name='get')
class PublisherAdd(View):
request
request.method 请求方法 GET POST
request.GET URL上携带的参数 ?k1=v1&k2=v2 { }
request.POST post请求提交的数据 {} 编码方式是URLencode
request.path_info 路径信息 不包含IP和端口 也不包含参数
request.body 请求体 bytes类型 #post请求才有 数据
request.COOKIES cookie
request.session session
request.FILES 长传的文件
request.META 头的信息 小写——》大写 HTTP_ 开头 - ——》 _ request.get_full_path() 完整的路径信息 不包含IP和端口 包含参数
request.is_ajax() 请求是否是ajax请求response
from django.shortcuts import render, HttpResponse, redirect HttpResponse('字符串') # 返回字符串
render(request,'模板的文件名',{'k1':v1}) # 返回一个HTML页面
redirect('地址') # 重定向 Location:‘地址’ 301 302
from django.http.response import JsonResponse
JsonResponse({'k1':'v1'})
JsonResponse(data,safe=False)
上传文件
urls.py
url(r'^upload/', views.Upload.as_view()),
视图:
class Upload(View): def get(self, request):
return render(request, 'upload.html')
def post(self, request):
file = request.FILES.get('f1')
with open(file.name, 'wb') as f:
for i in file:
f.write(i)
return HttpResponse('ok')
upload.html
<form action="" method="post" enctype="multipart/form-data">
{% csrf_token %} <input type="file" name="f1">
<button>上传</button>
</form>
最新文章
- Intent属性详解三 data、type和extra
- 【转】Java中try catch finally语句中含有return语句的执行情况(总结版)
- 优酷、YouTube、Twitter及JustinTV视频网站架构设计笔记
- 【M17】考虑使用缓式评估
- string的操作
- Nothing
- ADO。net学习笔记
- showmemory.c 和 hello.s 源码
- Ubuntu server 16.04安装,无网卡驱动解决
- Java中Sax解析XML
- Unity5 Shader Stripping 导致 LightMap 全部丢失的解决方法
- 关于RAS加密中pfx格式提取字符串私钥 (转)
- 20145214 《Java程序设计》第2周学习总结
- mysql无法输入中文排错
- 我的npm笔记
- JSON之—— JSON.parse()和JSON.stringify() (插曲)
- 如何打造你的独特观点(一) ——形成“自己的想法”的基础课zz
- uwsgi 热启动
- 在JavaScript中";+";什么时候是链接符号,什么时候是加法运算?
- oracle 行转列函数pivot和unpivot