Django 视图层

URL映射

1、分布式url映射

include()函数提供分布式url映射功能,使URL映射可以被编写在多个url.py文件中

from django.conf.urls import url
from django.contrib import admin
from django.conf.urls import include
urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^app/', include('app.urls')), # 反向解析到app/urls.py中
]

2、反向解析

from django.conf.urls import url
from . import views

urlpatterns = [
    url(r'moments_input',views.moments_input),
    url(r'wc',views.welcome,name='welcome'),# 通过name参数将该映射命名为welcome
]
  • 反向解析在模版中调用方法:在模版文件中用{%url%}标签反向解析
<a href="{% url 'welcome' %}">查看信息</a>
<a href="/app/welcome/">查看信息</a>
  • python中用django.core.urlresolvers.reverse()函数调用反向解析
from django.http import HttpResponseRedirect
from django.core.urlresolvers import reverse

def moments_input(request): 

  return HttpResponseRedirect(reverse('welcome'))

3、带参数的反向解析

from django.conf.urls import url
from . import views

urlpatterns = [
    url(r'^year/?P<year>([0-9]{4})/$',views.year_moments,name='moments')
]

在模版文件中反向解析,直接在{%url%}标签中添加参数

<a href="{% url 'moments' ,2014%}">查看信息</a>
<a href="/year/2014/">查看信息</a>

python 代码中带参数反向解析

from django.http import HttpResponseRedirect
from django.core.urlresolvers import reverse

def redirect_to_year_2014(request): 

  return HttpResponseRedirect(reverse('moments',args=(2014,)))
reverse()函数的args参数用于设置反向映射url参数

视图函数

  •  直接构造HTTP Body: 比如直接返回当前时间给客户端
  • 用数据渲染HTML模版文件:需要用django.shotcuts.render()函数实现
return render(request,'templates/moments.html',{'headline':m.headline,'user':m.user_name})
  • 返回HTTP错误
from django.http import HttpResponseNotFound

def my_view(request):
    return HttpResponseNotFound()
HttpResponseRedirect 302 用于URL重定向
HttpResponseNotModified 304 用于将上次请求缓存结果作为页面显示内容
HttpResponsePermanentRedirect 301 永久重定向
HttpResponseBadRequest 400 请求内容错误
HttpResponseForbidden 403 禁止访问错误
HttpResponseNotAllowed 405 用不允许的方法访问本页面
HttpResponseServerError 500 服务器内部错误

 

posted @ 2017-06-30 09:29  Erick-LONG  阅读(211)  评论(0编辑  收藏  举报