Django视图简介

一,视图函数介绍

  一个视图函数,简称视图,是一个简单的Python 函数,它接受Web请求并且返回Web响应。响应可以是一张网页的HTML内容,一个重定向,一个404错误,一个XML文档,或者一张图片. . . 是任何东西都可以。无论视图本身包含什么逻辑,都要返回响应。代码写在哪里也无所谓,只要它在你的Python目录下面。除此之外没有更多的要求了——可以说“没有什么神奇的地方”。为了将代码放在某处,约定是将视图放置在项目或应用程序目录中的名为views.py的文件中。

二,三种响应形式

  1:HttpResponse()

  2:render()

render(request, template_name[, context])

  结合一个给定的模板和一个给定的上下文字典,并返回一个渲染后的Httpresponse对象

  参数:

    request:用于生成响应的请求对象

    template_name:要使用的模板完整名称,可选得到参数

    context:添加到模板上下文的一个字典。如果字典中的某一个值是可调用的,视图将在渲染模板之前调用它。

# render内部原理
from django.template import Template,Context
def test(request):
  tmp = Template("<h1>{{ user }}</h1>")
  con = Context({'user':'jason'})
  res = tmp.render(con)
  print(res)
  return HttpResponse(res)

  3:redirect(传递要重定向的一个URL)

三,JsonResponse

  向前端返回一个json格式字符串的两种方式

  方式一:

import json
data={'name':'lqz','age':18}
data1=['lqz','egon']
return HttpResponse(json.dumps(data1))

  方式二:

from django.http import JsonResponse
data = {'name': 'lqz', 'age': 18}
data1 = ['lqz', 'egon']
return JsonResponse(data)
return JsonResponse(data1,safe=False)

四,CBV和FBV

  class base view 和 Function base view

from django.views import View
class AddPublish(View):
    def dispatch(self, request, *args, **kwargs):
        print(request)
        print(args)
        print(kwargs)
        # 可以写类似装饰器的东西,在前后加代码
        obj=super().dispatch(request, *args, **kwargs)
        return obj

    def get(self,request):
        return render(request,'index.html')
    def post(self,request):
        request
        return HttpResponse('post')

五,简单文件上传

  form表单上传文件的注意事项,encytpe编码指定为formdata

def uploadfile(request):
  if request.method == 'POST':
    # print(request.FILES)
    # print(request.FILES.get('myfile'))
    file_obj = request.FILES.get('myfile')
    with open(file_obj.name,'wb') as f:
      for line in file_obj.chunks():
      # 或者直接对文件对象for循环for line in file_obj
        f.write(line)
    return HttpResponse("OK!")
  return render(request,'index.html')

    

    

猜你喜欢

转载自www.cnblogs.com/ay742936292/p/10999645.html