Django view和url

文章目录

      • view 视图
        • FBV
        • CBV
        • HttpRequest
        • HttpResponse
        • 文件上传
        • JsonResponse
      • url 路由器
        • 基本格式
        • 分组匹配
        • 分组命名匹配
        • 命名URL和URL反向解析

Django view和url_第1张图片

view 视图

FBV

函数视图,(function base view)

urlpatterns = [
	url(r'^view_fbv/', views.view_fbv),
]
def view_fbv(request):
    return render(request, 'view_fbv.html', {'desc': '函数视图'})

CBV

类视图,(class base view)

urlpatterns = [
    url(r'^view_cbv/', views.ViewCBV.as_view()),
]
class ViewCBV(View):
    def get(self, request):
        return render(request, 'view_cbv.html', {'desc': '类视图'})

HttpRequest

# 请求路径,不包括ip地址
path = request.path
# http请求方法
method = request.method
# 提交数据编码,默认值为None
encoding = request.encoding
# get请求所有参数,返回一个字典对象
get = request.GET
# 返回post请求所有参数
post = request.POST
# 返回所有文件对象
files = request.FILES
# 返回所有cookie值
cookies = request.COOKIES
# session = request.session
# print(f'session:{session}')
# 返回请求头
header = request.META
# 返回请求体
body = request.body
# 返回请求协议
scheme = request.scheme

# 获取主机地址
host = request.get_host()
# 获取端口号
port = request.get_port()
# 获取请求地址,不包括ip,和path类似
full_path = request.get_full_path()
# 获取完整请求路径
build_absolute_uri = request.build_absolute_uri()
# 是否是ajax请求
is_ajax = request.is_ajax()

HttpResponse

response = HttpResponse()

# 设置返回内容
response.content = 'hello django'

# 设置字符编码集
response.charset = 'utf-8'

# 设置http响应码
response.status_code = 200

# 将内容写入报文主体
response.write('还有index内容')

# 以文件的方式输出缓存区
response.flush()

# 设置cookie
response.set_cookie('cookie_key', 'cookie_value')
# 删除cookie
response.delete_cookie('cookie_key')

文件上传

urlpatterns = [
    url(r'^upload/', views.upload),
]
<form action="/upload/" method="post" enctype="multipart/form-data">
    <input type="file" name="upload_file">
    <input type="submit" value="文件上传">
</form>
def upload(request):
    if request.method == 'POST':
        print(request.FILES)
        filename = request.FILES['upload_file'].name
        with open(filename, 'wb') as file:
            for i in request.FILES["upload_file"].chunks():
                file.write(i)
        return HttpResponse('ok')
    else:
        return render(request, 'upload.html')

JsonResponse

JsonResponse是HttpResponse的子类,专门用来生成JSON编码的响应。

def json_test(request):
    data = {'name': 'Tom', 'age': 12, 'class': '班级一'}
    return JsonResponse(data)

默认只能传递字典类型,如果要传递非字典类型需要设置一下safe关键字参数。

response = JsonResponse([1, 2, 3], safe=False)

其他json转换:

import json

def json_test(request):
    data = {'name': 'Jim', 'age': 22, 'class': '班级二'}
    json_str = json.dumps(data)
    return HttpResponse(json_str)

url 路由器

django的路由系统作用就是使views里面处理数据的函数与请求的url建立映射关系。

基本格式

from django.conf.urls import url

urlpatterns = [
     url(正则表达式, views视图函数,参数,别名),
]
  1. urlpatterns中的元素按照书写顺序从上往下逐一匹配正则表达式,一旦匹配成功则不再继续。

  2. 若要从URL中捕获一个值,只需要在它周围放置一对圆括号(分组匹配)。

  3. 是否自动在网址结尾加/

    APPEND_SLASH=True
    
  4. 是否强制开头^,结尾$

分组匹配

urlpatterns = [
    url(r'^time/([0-9]{4})/([0-9]{2})/([0-9]{2})/$', views.time),
]
def time(request, year=1111, month=11, day=11):
    return HttpResponse(f'year:{year},month:{month},day:{day}')

调用:http://127.0.0.1:8001/time/2018/12/12/

正则表达式分组匹配(通过圆括号)来捕获URL中的值并以位置参数形式传递给视图

分组命名匹配

urlpatterns = [
    url(r'^articles/(?P[0-9]{4})/(?P[0-9]{2})/(?P[0-9]{2})/', views.articles),
]
def articles(request, year=2012, month=11, day=11):
    return HttpResponse(f'year:{year},month:{month},day:{day}')

调用:http://127.0.0.1:8001/articles/2018/11/23/

分组命名匹配的正则表达式组来捕获URL中的值并以关键字参数形式传递给视图

命名URL和URL反向解析

project下urls:

from django.conf.urls import url, include
from django.contrib import admin
from app import views

urlpatterns = [
    # 命名空间
    url(r'^school/', include('school.urls', namespace='school')),
    url(r'^home/', include('home.urls', namespace='home')),
]

home下urls:

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

urlpatterns = [
    # 命名url
    url(r'^detail/$', views.detail, name='detail')
]

home下views:

from django.shortcuts import render

def detail(request):
    return render(request, 'home.html')

home.html:

<h1>这里是home</h1>

<a href="{% url 'school:detail' %}">跳转school页面</a>

school下urls:

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

urlpatterns = [
    url(r'^detail/$', views.detail, name='detail')
]

school下views:

from django.shortcuts import render

def detail(request):
    return render(request, 'school.html')

school.html:

<h1>这里是school</h1>

<a href="{% url 'home:detail' %}">跳转home页面</a>

你可能感兴趣的:(Django)