码迷,mamicode.com
首页 > 其他好文 > 详细

django-视图

时间:2016-04-09 17:15:38      阅读:166      评论:0      收藏:0      [点我收藏+]

标签:include   request   import   

视图

    url

        Django中url匹配是写在 urls.py 文件中,用正则表达式对应 views.py 中的一个函数

        配置url和对应视图函数之间的映射

        url(r‘^$‘, views.index),

        url(r‘^manage/(?P<name>\w*)/(?P<id>\d*)‘, views.manage),

        url(r‘^manage/(?P<name>\w*)‘, views.manage,{‘id‘:333}),        

        url(r‘^web/‘,include(‘web.urls‘)), 根据app对路由规则进行一次分类

视图

一个视图函数,简称视图,是一个简单的Python 函数,它接受Web请求并且返回Web响应。

下面是一个返回当前日期和时间作为HTML文档的视图:

from django.http import HttpResponse

import datetime

def current_datetime(request):

now = datetime.datetime.now()

html = "<html><body>It is now %s.</body></html>" % now

return HttpResponse(html)

快捷函数

render(request, template_name[, context][, context_instance][, content_type][, status][, current_app][, dirs][, using])

request 必选参数

用于生成响应的请求对象。

status

响应的状态码。默认为200。

redirect(to, [permanent=False, ]*args, **kwargs)


装饰器

require_http_methods(request_method_list)[source]

限制视图只能服务规定的http方法。用法:

from django.views.decorators.http import require_http_methods

@require_http_methods(["GET", "POST"])

def my_view(request):

pass

require_GET()

只允许视图接受GET方法的装饰器。

require_POST()

只允许视图接受POST方法的装饰器。

require_safe()

只允许视图接受 GET 和 HEAD 方法的装饰器。 这些方法通常被认为是安全的,因为方法不该有请求资源以外的目的。

请求和响应对象

Django 使用Request 对象和Response 对象在系统间传递状态。

HttpRequest.method

一个字符串,表示请求使用的HTTP 方法。必须使用大写。例如:

if request.method == ‘GET‘:

do_something()

elif request.method == ‘POST‘:

do_something_else()

HttpRequest.path 一个字符串,表示请求的页面的完整路径,不包含域名。

HttpRequest.POST 一个类似于字典的对象,如果请求中包含表单数据,则包含HTTP POST 的所有参数。

HttpRequest.COOKIES 一个标准的Python 字典,包含所有的cookie。键和值都为字符串。

HttpRequest.FILES 一个类似于字典的对象,包含所有的上传文件。FILES 中的每个键为<input type="file" name="" /> 中的name。

JsonResponse 对象

典型的用法如下:

from django.http import JsonResponse

response = JsonResponse({‘foo‘: ‘bar‘})


文件上传

当Django在处理文件上传的时候,文件数据被保存在request. FILES

from django import forms


class UploadFileForm(forms.Form):

title = forms.CharField(max_length=50)

file = forms.FileField()


def handle_uploaded_file(f):

with open(‘some/file/name.txt‘, ‘wb+‘) as destination:

for chunk in f.chunks():

destination.write(chunk)

def upload_file(request):

if request.method == ‘POST‘:

form = UploadFileForm(request.POST, request.FILES)

if form.is_valid():

handle_uploaded_file(request.FILES[‘file‘])


django-视图

标签:include   request   import   

原文地址:http://lxb994.blog.51cto.com/9805112/1762002

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!