python--Django(三)视图

Django的视图

不同于其他语言的MVC模式,Django采用的是MVT模式,即Model、View、Template,这里的View其实质就是其他语言中的Controller(emmm.....),而Template其实就是html文件,所以原理其实大同小异,这里就不多赘述

配置URL

Django中的默认路由在项目主目录下的urls.py中,基本路由配置如下所示:

from django.urls import path, include
from . import views

urlpatterns = [
    path('articles/2003/', views.special_case_2003),
    path('articles/<int:year>/', views.year_archive),
    path('articles/<int:year>/<int:month>/', views.month_archive),
    path('articles/<int:year>/<int:month>/<slug:slug>/', views.article_detail),
    path('', include('test.urls'))                                                                                # 引入不同应用的url配置
]

以上为普通匹配方式,其中有几种能够限制路由中参数类型的函数可以使用。

  • str: 匹配除路径分隔符'/'之外的任何非空字符串
  • int:匹配零或任何正整数
  • slug:匹配由ASCII字母或数字组成的任何slug字符串,以及连字符'-'和下划线'_'字符
  • uuid:匹配格式化的UUID
  • path:匹配任何非空字符串,包括路径分隔符 '/'

使用正则表达式匹配

from django.urls import path, re_path

from . import views

urlpatterns = [
    path('articles/2003/', views.special_case_2003),
    re_path(r'^articles/(?P<year>[0-9]{4})/$', views.year_archive),                                                                        # ?P<year>意为指定参数的名字
    re_path(r'^articles/(?P<year>[0-9]{4})/(?P<month>[0-9]{2})/$', views.month_archive),
    re_path(r'^articles/(?P<year>[0-9]{4})/(?P<month>[0-9]{2})/(?P<slug>[w-]+)/$', views.article_detail),
]

URL起别名
此例相对于PHP laravel框架中的route()用法,具体用法如下

# 路由中的配置
from django.urls import path, include
from test import views

urlpatterns = [
    path('', views.index, name='test-index'),
    path('/<int:num>', views.getNum)
    path('', include('test.urls', namespace = 'test'))            #为include起别名
]

# 在template中的运用
<a href="{% url 'test-index' 此处可以跟参数 %}"></a>

# 在views中的运用
from django.http import HttpResponseRedirect
from django.urls import reverse

def redirect_to_year(request):
    year = 2006                                                                                                                                # 参数
    return HttpResponseRedirect(reverse('test-index', args=(year,)))

HttpRequest对象

属性

  • path:一个字符串,表示请求的页面的完整路径,不包含域名
  • method:一个字符串,表示请求使用的HTTP方法,常用值包括:'GET'、'POST'
  • encoding:一个字符串,表示提交的数据的编码方式
    • 如果为None则表示使用浏览器的默认设置,一般为utf-8
    • 这个属性是可写的,可以通过修改它来修改访问表单数据使用的编码,接下来对属性的任何访问将使用新的encoding值
  • GET:一个类似于字典的对象,包含get请求方式的所有参数(QueryDict对象)
  • POST:一个类似于字典的对象,包含post请求方式的所有参数(QueryDict对象)
  • FILES:一个类似于字典的对象,包含所有的上传文件(QueryDict对象)
  • COOKIES:一个标准的Python字典,包含所有的cookie,键和值都为字符串
  • session:一个既可读又可写的类似于字典的对象,表示当前的会话,只有当Django 启用会话的支持时才可用。
    方法
  • is_ajax():如果请求是通过XMLHttpRequest发起的,则返回True

QueryDict对象
QueryDict对象定义在django.http.QueryDict,与python字典不同,QueryDict类型的对象用来处理同一个键带有多个值的情况,可以通过方法get()来获取值

  • 只能获取键的一个值
  • 如果一个键同时拥有多个值,获取最后一个值
dict.get('键名',默认值)
dict['键名']

另外还可以通过方法getlist()将键的值以列表的形式返回

dict.getlist('键名',默认值)

HttpResponse对象

属性

  • content:表示返回的内容,字符串类型
  • charset:表示response采用的编码字符集,字符串类型
  • status_code:响应的HTTP响应状态码
  • content-type:指定输出的MIME类型

方法

  • init :使用页内容实例化HttpResponse对象
  • write(content):以文件的方式写
  • flush():以文件的方式输出缓存区
  • set_cookie(key, value='', max_age=None, expires=None):设置Cookie
    • key、value都是字符串类型
    • max_age是一个整数,表示在指定秒数后过期
    • expires是一个datetime或timedelta对象,会话将在这个指定的日期/时间过期,注意datetime和timedelta值只有在使用PickleSerializer时才可序列化
    • max_age与expires二选一
    • 如果不指定过期时间,则两个星期后过期
  • delete_cookie(key):删除指定的key的Cookie,如果key不存在则什么也不发生

重定向HttpResponseRedirect

from django.http import HttpResponse,HttpResponseRedirect
def index(request):
    return HttpResponseRedirect('index/')

# 反向解析
from django.core.urlresolvers import reverse

def index(request):
    return HttpResponseRedirect(reverse('booktest:index2', args=(1,)))

返回json对象JsonResponse

from django.http import JsonResponse

def index2(requeset):
    return JsonResponse({'name': 'abc'})

渲染模版render

from django.shortcuts import render

def index(request):
    return render(request, 'booktest/index.html', {'h1': 'hello'})

重定向redirect

from django.shortcuts import redirect
from django.core.urlresolvers import reverse

def index(request):
    return redirect(reverse('booktest:index2'))

session的使用

使用session

  • request.session.get(key, default=None):根据键获取会话的值
  • request.session.clear():清除所有会话
  • request.session.flush():删除当前的会话数据并删除会话的Cookie
  • del request.session['member_id']:删除会话

会话过期时间

  • set_expiry(value):设置会话的超时时间
  • 如果没有指定,则两个星期后过期
  • 如果value是一个整数,会话将在values秒没有活动后过期
  • 若果value是一个timedelta对象,会话将在当前时间加上这个指定的日期/时间过期
  • 如果value为0,那么用户会话的Cookie将在用户的浏览器关闭时过期
  • 如果value为None,那么会话永不过期
原文地址:https://www.cnblogs.com/peilanluo/p/9589039.html