Django View 进阶
返回404
from django.http import HttpResponse, HttpResponseNotFound def not_found(request):
return HttpResponse('Not found', status=)
或
return HttpResponseNotFound('Not found')
注意 返回的页面和status=200一样都是'Not found'
自定义错误视图
1. 修改配置文件
# settings.py DEBUG = False
ALLOWED_HOSTS = ['*']
2. 创建视图函数
# views.py
from django.http import HttpResponse
def not_found_view(request):
return HttpResponse('404页面') def server_error(request):
return HttpResponse('500页面')
3. 配置项目路由
# urls.py
from . import views handler404 = views.not_found_view
handler500 = views.server_error # handler403 = views.403_view
# handler400 = views.400_view
render()函数
render(request, template_name, context=None, content_type=None, status=None, using=None)
必填项
request:request用户生成response
template_name:模板名称,可以是列表会使用先找到的那个
可选项
context:渲染模板的context字典,默认是{}
content_type:响应的 MIME type,默认使用 settings.py中 DEFAULT_CONTENT_TYPE
status:响应状态码 默认 status=200
using:模板引擎,可更改默认引擎,如jinja2
redirect()函数
redirect(to, permanet=False, *args, **kwargs),返回一个HttpResponseRedirect
to参数可以是:
model对象、视图名称、相对或绝对URL地址
object = MyModel.objects.get(...)
return redirect(object)
return redirect('some-view-name', foo='bar' )
return redirect('/some/url/')
return redirect('https://example.com/', permanent=True)
get_object_or_404() 函数
from django.shortcuts import get_object_or_404
def my_view(request):
my_object = get_object_or_404(MyModel, pk=1) # 代码等同于
from django.http import Http404
def my_view(request):
try:
my_object = MyModel.objects.get(pk=1)
except MyModel.DoesNotExist:
raise Http404("No MyModel matches the given query.")
其他 get_list_or_404()函数
reverse() 反向解析URL
reverse(viewname, urlconf=None, agrs=None, kwargs=None, current_app=None)
reverse_lazy(viewname, urlconf=None, agrs=None, kwargs=None, current_app=None) 惰性解析,Django启动加载顺序 如类中用reverse_lazy(),类视图
装饰器
require_http_methods(request_method_list)
require_GET()
require_POST()
require_safe() 安全性请求 GET、HEAD
gzip_page() 内容压缩, 一般会在代理服务器里处理,Nginx
cache_control(**kwargs),告诉浏览器的缓存,和memecache不同,可用在password
never_cache()
login_required() 验证页面必须登录,常用
transaction.atmoic 事务功能
from django.views.decorators.http import require_http_methods
from django.db.transaction import atomic @require_http_methods(["GET", "POST"])
@atomic
def my_view(request):
pass
HttpRequest and HttpResponse
https://docs.djangoproject.com/en/1.11/ref/request-response/
用户请求属性
HttpReqeust.scheme
HttpReqeust.body
HttpReqeust.path
HttpReqeust.method
HttpReqeust.GET
HttpReqeust.POST
HttpReqeust.COOKIES
HttpReqeust.FILES
HttpReqeust.META
应用程序设置的属性
HttpReqeust.current_app
HttpReqeust.urlconf
中间件设置的属性
HttpReqeust.session
HttpReqeust.site
HttpReqeust.user
HttpReqeust.user.is_authenticated
......
发送邮件(Django自带)
django.core.mail.send_mail(subject, message, from_email, recipient_list,
fail_sliently=False, auth_user=None, auth_password=None, connection=None, html_message=None)
# settings.py
EMAIL_HOST = 'smtp.126.com'
EMAIL_PORT = 25
EMAIL_HOST_USER = '******'
EMAIL_HOST_PASSWORD = '******'
# EMAIL_USE_SSL = True # if port is 587, set True
# EMAIL_USE_TLS = True # if port is 465, set True # views.py
from django.core.mail import send_mail def send_email(request): if request.method == "POST":
subject = request.POST.get('subject', '')
message = request.POST.get('message', '')
from_email = request.POST.get('from_email', '')
if subject and message and from_email:
try:
send_mail(subject, message, from_email, ['nin@jianxin.com.cn'])
except Exception as e:
return HttpResponse(str(e)) return HttpResponse('发送成功!')
else:
return HttpResponse("确保字段填写正确!") elif request.method == "GET":
return render(request, 'send_email.html')
导出CSV
import csv
def download_csv(request):
response = HttpResponse(content_type='text/csv')
response['Content-Disposition'] = 'attachment;filename="download.csv"' writer = csv.writer(response)
writer.writerow(['First Row', 'Foo', 'Bar', 'Baz'])
writer.writerow(['SecondRow', 'A', 'B', 'C', '"Testing"', "Here's a quote"])
return response def download(request):
f = open('601318.csv', 'rb')
response = HttpResponse(f, content_type='application/csv')
response['Content-Disposition'] = 'attachment;filename="601318.csv"'
f.close()
return response
上传文件
# views.py
def upload(request):
if request.method == "POST":
upload_file = request.FILES.get('file', None)
if upload_file is None:
return HttpResponse('No file get')
else:
with open(upload_file.name, 'wb') as f:
for chunk in upload_file.chunks():
f.write(chunk) # f.write(upload_file.read())
return HttpResponse('OK')
elif request.method == "GET":
return render(request, 'upload.html') # upload.html
<h1>Upload</h1>
<form method="post" enctype="multipart/form-data">
{% csrf_token %}
<label for="file">Upload: </label><input type="file" id="file" name="file"/><br/> <input type="submit" value="upload"/>
</form>
说明:
request.FILES
enctype 默认是 "application/x-www-form-urlencoded"
Django View 进阶的更多相关文章
- Python之路【第十七篇】:Django【进阶篇 】
Python之路[第十七篇]:Django[进阶篇 ] Model 到目前为止,当我们的程序涉及到数据库相关操作时,我们一般都会这么搞: 创建数据库,设计表结构和字段 使用 MySQLdb 来连接 ...
- Python之路【第十七篇】:Django【进阶篇】
Python之路[第十七篇]:Django[进阶篇 ] Model 到目前为止,当我们的程序涉及到数据库相关操作时,我们一般都会这么搞: 创建数据库,设计表结构和字段 使用 MySQLdb 来连接 ...
- Python开发【第二十二篇】:Web框架之Django【进阶】
Python开发[第二十二篇]:Web框架之Django[进阶] 猛击这里:http://www.cnblogs.com/wupeiqi/articles/5246483.html 博客园 首页 ...
- Python之路,Day15 - Django适当进阶篇
Python之路,Day15 - Django适当进阶篇 本节内容 学员管理系统练习 Django ORM操作进阶 用户认证 Django练习小项目:学员管理系统设计开发 带着项目需求学习是最有趣 ...
- django view 装饰器
Django提供了几个可以应用于视图以支持各种HTTP特性的装饰器 Allowed HTTP django.views.decorators.http里的装饰器可以根据请求方法限制对视图的访问. re ...
- Django 2.0 学习(07):Django 视图(进阶-续)
接Django 2.0 学习(06):Django 视图(进阶),我们将聚焦在使用简单的表单进行处理和精简代码. 编写简单表单 我们将用下面的代码,来替换之前的detail模板("polls ...
- Django View(视图系统)
Django View 官方文档 一个视图函数(类),简称视图,是一个简单的 Python 函数(类),它接受Web请求并且返回Web响应.响应可以是一张网页的HTML内容,一个重定向,一个404错误 ...
- Django orm进阶查询(聚合、分组、F查询、Q查询)、常见字段、查询优化及事务操作
Django orm进阶查询(聚合.分组.F查询.Q查询).常见字段.查询优化及事务操作 聚合查询 记住用到关键字aggregate然后还有几个常用的聚合函数就好了 from django.db.mo ...
- 安卓自定义View进阶-Canvas之画布操作 转载
安卓自定义View进阶-Canvas之画布操作 转载 https://www.gcssloop.com/customview/Canvas_Convert 本来想把画布操作放到后面部分的,但是发现很多 ...
随机推荐
- linux 僵尸进程查看方式
ps -A -ostat,ppid,pid,cmd |grep -e '^[Zz]' # 结果 Z 169925 49893 [sw] <defunct> Z 169925 120690 ...
- PHP安装Commposer
一先把php加到环境变量里面测试 看一下版本号: 二,composer得安装注意安装的时候 php必须在5.59以上版本,openssl的扩展开启,pdo的扩展开启,mbstring的扩展开启 1,下 ...
- 触发full gc的条件
1.调用System.gc 2.老年代空间不足 3.永生区空间不足 4.CMS GC时出现promotion failed和concurrent mode failure 5.统计得到的Minor G ...
- jquery中的 deferred之 deferred对象 (一)
案例: var def=$.Deferred(); console.log(def);//答案见 图1 图1: deferred就是一个有这些方法的对象. 看源码分析: Deferred: funct ...
- 并发系列3:Lock锁以及核心类AQS
Java Lock类提供了语言级别的Synchronized,Lock与Condition配合与Synchronized配合object一样实现了等待/通知机制.但它提供了更高的灵活性,有:1尝试非阻 ...
- mui之上拉刷新和mui-content结合解决ios上拉不回弹的bug
打电话.发短信 https://blog.csdn.net/itguangit/article/details/78210770
- 使用 Composer 安装Laravel扩展包的几种方法
使用 Composer 安装Laravel扩展包的几种方法 以下的三种方法都是需要你在项目的根目录运行 第一种:composer install 如有 composer.lock 文件,直接安装,否则 ...
- 37 【kubernetes】搭建dashboard
官方的操作步骤是:https://github.com/kubernetes/dashboard 我自己的步骤是: 1,下载yaml文件 wget https://raw.githubusercont ...
- [剑指Offer]5-替换空格
链接 https://www.nowcoder.com/practice/9023a0c988684a53960365b889ceaf5e?tpId=13&tqId=11210&tPa ...
- Git-git push -u为何第二次不用指定-u?
1,如果当前分支只有一个追踪分支,那么主机名都可以省略,如:git push origin 将当前分支推送到origin主机的对应分支 2,$ git push 如果当前分支与多个主机存在追踪关系,那 ...