Django 视图层

视图层更注重业务上的实现, 了解一些常用知识就够用了b( ̄▽ ̄)d

0%

URL调度器

urlpatterns

当接收一个HttpRequest对象时, Django会自按顺序遍历urlpatterns进行匹配.
它是 django.urls.path() 和(或) django.urls.re_path() 实例的序列

urlpatterns = [
path('articles/2003/', views.special_case_2003),
...
]

URL匹配

  • 变量匹配 --- path()

    path('<int:question_id>/vote/', views.vote, name='vote'),
    • 要捕获的部分由<>包围.
    • int代表数据类型, 也可以是str.
    • 默认是在路径的结尾添加/.
  • 正则匹配 --- re_path()

    re_path(r'^(?P<question_id>\d+)/vote/$', views.vote, name='vote')
    • 本质上是re模块的封装
    • ^$ 注意加上, 防止上级路径捕获次级路径
  • include()

    • include()可以将其他urlconf添加到当前的urlpatterns序列当中.
    path('polls/', include('polls.urls')),
    • 也可以将相同的路径前缀下后面的部分一起声明.

      path('<page_slug>-<page_id>/', include([
      path('history/', views.history),
      path('edit/', views.edit),
      path('discuss/', views.discuss),
      path('permissions/', views.permissions),
      ]))

HttpRequest

属性

  • HttpRequest.path
    当前请求路径

  • HttpRequest.body

    当前请求体

  • HttpRequest.method
    当前请求方法

  • HttpRequest.GET

    GET携带的params参数

  • HttpRequest.POST
    POST携带的data参数

  • HttpRequest.COOKIES
    cookies 字典

  • HttpRequest.FILES
    上传的文件

  • HttpRequest.content_type
    当前传输数据类型

  • HttpRequest.session
    请求的服务器信息

  • HttpRequest.META
    包含了 HTTP 头文件的字典

方法

  • get_host()

    获取请求主机

HttpResponse

  • 模板使用

    from django.shortcuts import render

    return render(request, 'polls/results.html', {'question': question})
  • 返回字符串

    from django.http import HttpResponse

    return HttpResponse("Here's the text of the Web page.")
  • 返回JSON格式的字符串

    本质上和HttpResponse(json.dumps({}))一样,, 但提供了更多功能.
    默认只接受dict格式, 需要设置safeFalse才能传入其它格式.

    from django.http import JsonResponse

    return JsonResponse({'foo': 'bar'}, safe=False)
  • 返回文件

    主要是 Content-Disposition 里的内容, 这里没有Django特有的语法.

    response = HttpResponse('test', headers={
    'Content-Type': 'application/octet-stream',
    'Content-Disposition': 'attachment; filename="test.txt"',
    })

    return response
  • 返回异常

    from django.http import Http404

    raise Http404('Page not found')

视图

简单了解下4种HTTP协议请求方式

GET 获取资源
POST 新建资源(更新资源)
PUT 更改资源
DELETE 删除资源

基于函数的视图

def index(request):
return HttpResponse("Hello, world. You're at the polls index.")

实现RESTful api

def index_get(request):
pass

def index_post(request):
pass

def index_put(request):
pass

def index_delete(request):
pass

绑定url

path('get', views.xxx, name='index_get'),
...

基于类的视图

不用写多个绑定, 而且层次分明, 模块开发时优选.

  1. 绑定url

    path('', views.IndexView.as_view(), name='index'),
  2. 只需要绑定一次path, 会根据HttpRequest.method自动选择相应的处理方法.

    class IndexView(generic.View):
    def get(self, *args, **kwargs):
    pass

    def post(self, *args, **kwargs):
    pass

    def put(self, *args, **kwargs):
    pass

    def delete(self, *args, **kwargs):
    pass
------------ 已触及底线了 感谢您的阅读 ------------
  • 本文作者: OWQ
  • 本文链接: https://www.owq.world/80aa4d4c/
  • 版权声明: 本站所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处( ̄︶ ̄)↗