Four, Django's views

Django view related (views)

  1. Property methods associated with the request (request - HttpRequest object)

request method:

  • request.method: acquisition request mode, 'GET', 'POST'
  • request.body: acquiring original data submitted over the post request, bytes type, b'username = alex '
  • request.GET: GET request to obtain data submitted
    request.POST: acquiring data POST request submitted
    request.GET.get ( 'year')
    request.POST.get ( 'year')
  • request.META: request header information, that is a big dictionary
  • request.path: Path, / index /
    request.path_info: Path, / index /
  • request.get_full_path (): ip and port on the back of all the get request, namely: a data path +, / index / username = dazhuang & password = 123?

    from django.shortcuts import render,HttpResponse

    def index(request):
    if request.method == 'GET':
    print(request.body) # b''
    print(request.GET) # <QueryDict: {'year': ['2018'], 'month': ['12']}>
    print(request.GET.get('year')) # 2018
    print(request.META) # 请求头相关信息,就是一个大字典
    print(request.path) # /index/ 路径
    print(request.path_info) # /index/ 路径
    print(request.get_full_path()) # /index/?year=2018&month=12
    return render(request,'index.html')
    else:
    print(request.body) # b'year=2018&month=12'
    print(request.POST) # <QueryDict: {'year': ['2018'], 'month': ['12']}>
    print(request.POST.get('year')) # 2018
    return HttpResponse ( 'queries ha ha ~ ~')

  1. Response related methods
  • HttpResponse --- reply string when used
  • Reply to render --- a html page when using
  • redirect - Redirect
    • After the operation, you can automatically jump to another page. For example, a Web site, some features need to be logged in to visit, so when the user clicks the function, the first page is returned to the user logged on, after the user is logged on automatically jump to the user clicks on the function of that page does not require user login after a successful go back clicks, improving the user experience
    • When the site updates, does not maintain the old site, and re-development of a new website. When users access the old site, redirect to the new site.
    • Redirect Status code 301 and 302 the difference between:
      • 301: A old address represents the resource has been permanently removed (this resource can not be visited), search engines crawl at the same time new content will also exchange the old URL to URL after redirection;
      • 302: A represents a resource old address still (still access), this is only a temporary redirect from the old address to jump A to address B, the search engine will crawl new content and save the old URL.

Example: The user visits the site, allowing users to enter a user name, password, determine if correct, enter the member page

  1. urls:
    from django.conf.urls import url
    from app01 import views

    urlpatterns = [
        url(r'^login/', views.login),
    ]
  2. login.html:

    Login page - please login Member

    <form action="" method="post">
        用户名:<input type="text" name="username">
        密码:<input type="text" name="password">
        <button>提交</button>
    </form>
  3. views
    from django.shortcuts import render,HttpResponse

    def login(request):
        if request.method == 'GET':
            return render(request,'login.html')
        else:
            username = request.POST.get('username')
            password = request.POST.get('password')
            if username == 'yangzm' and password == '17130':
                return render(request,'member.html')
    
            else:
                return HttpResponse('您不是我们的用户')

    This method does not use redirection, also completed the related functions, but will find that this time the domain name or login /, this is inappropriate, can not or the original address, need to jump to a new web address

    Improved views:
    the urls.py member a document which add the path of
    the urlpatterns = [
    URL (R & lt 'Login ^ /', views.login),
    URL (R & lt 'member ^ /', views.member),
    ]

    from django.shortcuts import render,HttpResponse
    
    def login(request):
        if request.method == 'GET':
            return render(request,'login.html')
        else:
            username = request.POST.get('username')
            password = request.POST.get('password')
            if username == 'yangzm' and password == '17130':
                # return render(request,'member.html')
                return redirect('/member/')
            else:
                return HttpResponse('您不是我们的用户')
    
    def member(request):
        return render(request, 'member.html')

    This time, the login is successful jump to a new address the

  4. FBV and CBV

FBV (function base views) is to use the processing functions in the view request.

CBV (class base views) in the view that the use of handling requests.

For example, processing a GET method of views, with the function writes:

FBV

from django.http import HttpResponse
  
def my_view(request):
     if request.method == 'GET':
            return HttpResponse('OK')

Then use the methods of the class to write:

CBV

views.py:
    from django.http import HttpResponse
    from django.views import View   # 需要导入View

    class MyView(View):   
        # 通过请求方法找到自己写的视图类里面对应的方法
        def get(self, request):    # 必须写的get,要和请求'GET'对应
            return HttpResponse('OK')
    
urls.py
    url(r'^myview/', views.MyView.as_view()),

CBV is how Corresponding trying to find a different class of request methods?

  • First urls.py in, views.MyView.as_view (), is called MyView as_view () This method, while MyView is a class of our own creation, there is no as_view () this method, the class MyView (View), is Inherited View inside as_view () method
  • Opening the source View: Key - reflecting
    class View (Object):
    http_method_names = [ 'GET', 'POST', 'PUT', 'Patch', 'Delete', 'head', 'Options',' the trace ']
    ......
    DEF as_view (CLS, initkwargs):
    ......
    DEF View (Request, args, kwargs):
    Self = CLS (
    initkwargs)
    ......
    return self.dispatch (Request ,
    args,
    kwargs) # main method

            return view
    
        def dispatch(self, request, *args, **kwargs):
            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)

    as_view () static method (i.e. class methods), calling this method creates an instance of a class, then call dispatch by way of example () method, dispatch () method will be processed request according to respective different calling method of request methods (e.g., get (), post (), etc.)

CBV method of dispatch

# 通过重写dispatch方法,可以在执行请求(get,post等)之前之后做一些拓展

class MyView(View):

    def dispatch(self, request, *args, **kwargs):
        print('请求之前的内容~~~~~')
        ret = super().dispatch(request,*args, **kwargs)
        print('请求之完事啦')
        return ret

    def get(self,request):
        print('get方法执行了')
        return render(request,'login.html')

    def post(self,request):
        username = request.POST.get('uname')
        password = request.POST.get('pwd')
        print(username,password)
        return HttpResponse('登录成功!')
    
    
# 结果:
    # 在访问页面时,get请求执行:
        请求之前的内容~~~~~
        get方法执行了
        请求之完事啦
    # 在input框输入用户名密码,提交,发送的post请求执行:
        请求之前的内容~~~~~
        yangzm 123
        请求之完事啦  
  1. Plus decorator

FBV plus decorator

# 就是正常写个装饰器,然后用语法糖就行

def warpper(f):
    def inner(*args,**kwargs):
        print('请求之前')
        ret = f(*args,**kwargs)
        print('请求之后')
        return ret
    return inner

@warpper
def my_view(request):
    if request.method == 'GET':
        return HttpResponse('OK')

CBV plus decorator

# 先导入 method_decorator 
# 有三种方法:
    # 方式一: 
        @method_decorator(warpper) # 给某个请求添加装饰器
        def get(self,request):
            pass
    # 方式二: 
        @method_decorator(warpper) # 给所有方法加装饰器
        def dispatch(self,request, *args, **kwargs):
            pass
    # 方式三:
        @method_decorator(warpper,name='get') # 给某个方法加装饰器
        class MyView(View):
            pass
        
        
from django.views import View
from django.utils.decorators import method_decorator # Django提供的装饰器

def warpper(f):
    def inner(*args,**kwargs):
        print('请求之前')
        ret = f(*args,**kwargs)
        print('请求之后')
        return ret
    return inner

@method_decorator(warpper,name='get') # 方式三:只给get请求加
class MyView(View):

    @method_decorator(warpper) # 方式二:给所有请求加
    def dispatch(self, request, *args, **kwargs):
        print('请求之前的内容~~~~~')
        ret = super().dispatch(request,*args, **kwargs)
        print('请求之完事啦')
        return ret
    
    @method_decorator(warpper) # 方式一:只给get请求加
    def get(self,request):
        print('get方法执行了')
        return render(request,'login.html')

    def post(self,request):
        username = request.POST.get('uname')
        password = request.POST.get('pwd')
        print(username,password)
        return HttpResponse('登录成功!')

5. A brief summary

Request the relevant request

request.method  请求方法
request.body    post请求原始数据
request.POST
request.GET
request.path  获取路径
request.path_info  
request.get_full_path()  获取路径及参数

request.META 请求头相关信息

Response correlation

HttpResponse  
render  
redirect

FBV and CBV

def index(request):
    return render(request,'xx.html')
    

from django.views import View   
class Index(View):
    def dispatch(self,request,*args,**kwargs):
        请求前干点儿事
        ret = super().dispatch(request,*args,**kwargs)
        请求后干点儿事儿
        return ret
    def get(self,request):
        ...
    def post(self,request):
        ...

Decorator

def wrapper(f):
    def inner(*args,**kwargs):
        前戏
        ret = f(*args,**kwargs)
        收工
        return ret
    return inner

@wrapper
def index(request):
    return render(request,'xx.html')

from django.utils.decorators import method_decorator

@method_decorator(wrapper,name='get')
class Index(View):
    
    @method_decorator(wrapper)
    def dispatch(self,request,*args,**kwargs):
        请求前干点儿事
        ret = super().dispatch(request,*args,**kwargs)
        请求后干点儿事儿
        return ret
        
    @method_decorator(wrapper)
    def get(self,request):
        ...
    def post(self,request):
        ...

Guess you like

Origin www.cnblogs.com/yangzm/p/11209944.html