Django View 进阶
返回404
from django.http import HttpResponse, HttpResponseNotFound def not_found(request): return HttpResponse('Not found', status=404) 或 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"
posted on 2017-09-08 15:25 Jonathan1314 阅读(237) 评论(0) 编辑 收藏 举报