温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

django-视图

发布时间:2020-07-02 19:25:40 来源:网络 阅读:326 作者:lixiaobo994 栏目:开发技术

视图

    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'])


向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI