写视图

写视图

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

这个响应可以是web页面的HTML内容,或者一个重定向,或者一个404 错误,或者一个XML 文档,或者一个image.

视图本身包含任意需要的逻辑来返回响应

这个代码可以在你需要的任何地方,只要它是在你的Python路径。

没有其他需要 没有magic,为了把代码放在某个地方,通常是放在一个叫做views.py文件里,放置在你的项目或者应用目录下。

一个简单的视图:

这里有一个视图 返回当前的日期,作为一个HTML 文档


def current_datetime(request):
    now = datetime.datetime.now()
    html = "<html><body>It is now %s.</body></html>" % now
    return HttpResponse(html)
	
 url(r'^current_datetime/$', newview.current_datetime),	

http://192.168.137.3:9000/current_datetime/

It is now 2018-01-28 15:51:09.914744.

<html><body>It is now 2018-01-28 15:51:31.546347.</body></html>


让我们一次一行的调试这个代码:

1.首选 我们需要从django.http module 导入HttpResponse 和 Python’s datetime library.

2.接下来,我们顶一个一个函数称为current_datetime。这是视图函数,每个视图函数有一个HttpRequest

对象作为它的第一个参数,通常命名为request

3. 注意视图函数的名字没有关系,它不会以某种特定的命名方式为了让Django识别它。

我们是调用它的current_datetime here,因为那个名字明确的表明它做什么

4. 视图返回一个HttpResponse对象 包含生成的响应,每个视图函数是负责返回一个HttpResponse object

Django’s Time Zone

Django 包含一个TIME_ZONE 设置,默认是America/Chicago

Mapping URLs to views

所以,总的来说,这个视图函数返回一个HTML 页面,表明当前的日期和事件。

显示这个视图在一个特定的URL,你需要创建你一个URLconf

Returning errors 返回错误

返回HTTP 错误代码在Django 是简单的,有几个HttpResponse的子类对于一个HTTP 状态码 比如200 意味着OK

你可以找到可用的子类在request/response documentation

from django.http import HttpResponse, HttpResponseNotFound

def my_view(request):
    # ...
    if foo:
        return HttpResponseNotFound('<h1>Page not found</h1>')
    else:
        return HttpResponse('<h1>Page was found</h1>')
		
没有一个特定的子类用于每个可能的HTTP 请求code,

因为它们中的许多不常见。
from django.http import HttpResponse

def my_view(request):
    # ...

    # Return a "created" (201) response code.
    return HttpResponse(status=201)
	

def current_datetime(request):
    now = datetime.datetime.now()
    html = "<html><body>It is now %s.</body></html>" % now
    return HttpResponse(html)
	
	默认返回状态是200
	
def current_datetime(request):
    now = datetime.datetime.now()
    html = "<html><body>It is now %s.</body></html>" % now
    return HttpResponse(html,status=301)


The Http404 exception

class django.http.Http404

当你返回一个错误,比如HttpResponseNotFound,你是定义错误页面的HTML


def current_datetime(request):
    now = datetime.datetime.now()
    html = "<html><body>It is now %s.</body></html>" % now
    #return HttpResponse(html,status=301)
    return HttpResponseNotFound('<h1>Page not found</h1>')

返回404 错误

为了方便,因为它是一个好主意有一个一致的404错误页面 在你的网站

Django 提供一个Http404异常 如果你抛出Http404 在任何节点在一个视图函数,

Django 会捕获它返回标准错误页面对于你的应用,以及一个HTTP 错误代码404

原文地址:https://www.cnblogs.com/hzcya1995/p/13349281.html