3.Django--views视图函数

Django--views视图函数

1.views视图

1.request请求对象:

views.py

from django.shortcuts import render, HttpResponse
def home(request):
    print(request.method) #当前请求方法
    print(request.POST) #post请求携带的数据,QueryDict类型
    #QueryDict类型 <QueryDict: {'aa': ['11'], 'bb': ['22']}>
    print(request.body) #post请求携带的数据的原始数据
    print(request.GET) #不是get请求方法携带的数据,而是请求路径(网站)的查询参数--?后面的数据
        #http://127.0.0.1:8000/index/?a=1&b=2
        #QueryDict类型 <QueryDict: {'a': ['1'], 'b': ['2']}>

    #例如: http://127.0.0.1:8000/index/?a=1&b=2
    print(request.path) #当前请求的路径 /index/
    print(request.get_full_path()) #携带查询参数的路径/index/?a=1&b=2
	
    print(request.FIELS) #获取上传来的文件对象
    
    return HttpResponse('hello world')
2.response响应对象:

views.py

from django.shortcuts import render, HttpResponse,redirect
from django.http import JsonResponse

# render : 响应回复html文件数据的
# HTTPResponse : 响应字符串数据
# redirect : 重定向,响应浏览器,响应状态码302,响应头键值对location:/路径/
# JsonResponse: 响应json格式数据的

def home(request):
    info = {'xx':'oo','xxx':'ooo'}
    return render(request,'home.html',info)

def login(request): # redirect : 重定向
    if request.method == 'GET':
        return render(request,'login.html')
    else:
        username = request.POST.get('username')
        if username == 'jia':
            #把得到的 数据加载到页面中
            # return render(request,'home.html',{'username':username})
            return redirect('/home/') #重定向,重新发出请求,不会丢失home页面中的数据
        else:
            return HttpResponse('你不行')

def data(request): ## JsonResponse: 响应json格式数据的
    d1 = {'xx':'oo'}
    # return HttpResponse(d1) # 不支持字典,只显示xx
    return JsonResponse(d1) # {"xx": "oo"}先算序列化后的数据

urls.py

from django.conf.urls import url
from django.contrib import admin
from app01 import views
urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^home/', views.home),
    url(r'^login/', views.login),
    url(r'^data/', views.data),
]

template目录下的HTML文件

home.html

<h1>
    欢迎
{#    <span style="color: aqua">{{ username }} </span>#}
{#    接收views视图函数传来的数据#}
    {{ xx }}--{{ xxx }}
</h1>

login.html

<form action="" method="post">
    <input type="text" name="username">
    <input type="submit">
</form>

2.书写views视图的方法:CBV和FBV

FBV(function base views): 就是在视图里使用函数处理请求。

CBV(class base views): 就是在视图里使用类处理请求

CBV关键点

反射: 通过dispatch请求方法来反射获取对应的类方法逻辑

  def dispatch(self, request, *args, **kwargs):
        # Try to dispatch to the right method; if a method doesn't exist,
        # defer to the error handler. Also defer to the error handler if the
        # request method isn't on the approved list.
        # GET--get  in http_method_names = ['get', 'post', 'put', 'patch', 'delete', 'head', 'options', 'trace']
        if request.method.lower() in self.http_method_names:
            handler = getattr(self, request.method.lower(), self.http_method_not_allowed)
        else:
            handler = self.http_method_not_allowed
        return handler(request, *args, **kwargs)

优点:

1.提高了代码的复用性,可以使用面向对象的技术,比如Mixin(多继承)
2.可以用不同的函数针对不同的HTTP方法处理,而不是通过很多if判断,提高代码可读性

views.py

from django.shortcuts import render, HttpResponse
from django.views import View 
# 基于类写视图,需要先引入View,定义的类继承View
class BookView(View):
    
    #视图类处理get请求时,定义get函数
    def get(self,request):
        return HttpResponse('book')
    
    # 视图类处理post请求时,定义post函数
    def post(self,request):
        pass

urls.py

from django.conf.urls import url
from django.contrib import admin
from app01 import views
urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^book/', views.BookView.as_view()), #视图类路径写法
]

3.视图加装饰器

视图函数加装饰器:FBV
def outer(f): #装饰器
    def inner(request,*args,**kwargs):
        print('xxxx')
        ret = f(request,*args,**kwargs)
        print('oooo')
        return ret
    return inner

@outer  #给函数加装饰器
def home(request):
    info = {'xx':'oo','xxx':'ooo'}
    return render(request,'home.html',info)
视图类加装饰器:CBV
def outer(f): #装饰器
    def inner(request,*args,**kwargs):
        print('xxxx')
        ret = f(request,*args,**kwargs)
        print('oooo')
        return ret
    return inner

from django.views import View
from django.utils.decorators import method_decorator # django提供的方法装饰器

@method_decorator(outer,name='post')
@method_decorator(outer,name='get') #方式二:给类加装饰器,给某个方法加装饰器,只能一个一个方法加
class BookView(View):
    #在请求方法分发对应类方法执行之前,先做一些处理
    @method_decorator(outer) # 方式一:类中函数加装饰器,也可以单独给某个方法加
    def dispatch(self, request, *args, **kwargs):
        print('分发方法')
        ret = super().dispatch(request, *args, **kwargs) #执行父类方法
        print('请求方法完了')
        return ret

    #视图类处理get请求时,定义get函数
    @method_decorator(outer) # 方式三:单独给某个方法加装饰器
    def get(self,request):
        print('get方法来了')
        return HttpResponse('book')

    # 视图类处理post请求时,定义post函数
    def post(self,request):
        pass
原文地址:https://www.cnblogs.com/jia-shu/p/14589765.html