Part IV: Django view layer

The method of the view layer

HttpResponse

Returns the string

def index(request):
    return HttpResponse('你好啊小妹妹')

render

Return html page and can transfer data to html page

def login(request):
    return render(request, 'login.html', {'user_dic': {'username': 'json', 'password': 123}, 'mes': 'hello'})
 
# 返回html页面,并可以给html传入字典
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
{#取字典中的值#}
{{ user_dic.username }}
</body>
</html>
 

render the principle of

from django.template import Template, Context
def ab_render(request):
    temp = Template('<h3>{{user_dict}}<br>{{user_dict.name}}<br> {{user_dict.password}}</h3>')
    context = Context({'user_dict': {'name': 'jason', 'password': 123}})
    res = temp.render(context)
    return HttpResponse(res)

redirect

Redirect

def home(request):
    return redirect('https://www.baidu.com')

JsonResponse

import json from django.http import JsonResponse
def xxx(request):
    user_dict = {'username':'jason好帅哦 我好喜欢!','password':'123'}
    # json_str = json.dumps(user_dict,ensure_ascii=False)
    # return HttpResponse(json_str)
    l = [1,2,3,4,5,6,7,8,9,]
    # return JsonResponse(user_dict,json_dumps_params={'ensure_ascii':False})
    return JsonResponse(l,safe=False)  # 序列化非字典格式数据 需要将safe改为False
 
from django.http import JsonResponse
def xxx(request):
    user_dict = {'username':'jason好帅哦 我好喜欢!','password':'123'}
    # json_str = json.dumps(user_dict,ensure_ascii=False)
    # return HttpResponse(json_str)
    l = [1,2,3,4,5,6,7,8,9,]
    # return JsonResponse(user_dict,json_dumps_params={'ensure_ascii':False})
    return JsonResponse(l,safe=False)  # 序列化非字典格式数据 需要将safe改为False

Front and rear ends data exchange

form form to upload files

action   什么都不写,默认朝当前页面提交数据
 
method   post  什么都不写默认为get请求,不会提交数据,需要改为post
 
enctype  formdata  更改为上传文件

示例:
Home.Html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="https://cdn.bootcss.com/jquery/3.4.1/jquery.min.js">    </script>
    <link href="https://cdn.bootcss.com/twitterbootstrap/3.4.1/css/bootstrap.min.css" rel="stylesheet">
    <script src="https://cdn.bootcss.com/twitterbootstrap/3.4.1/js/bootstrap.min.js"></script>
</head>
<body>
<form action="" method="post" enctype="multipart/form-data">
    <input type="file" name="myfile">
    <input type="submit">
</form>
 
</body>
</html>

views.py

def home(request):
    if request.method == 'POST':
        # 获取用户上传的文件数据
        print(request.FILES)
        file_obj = request.FILES.get('myfile')  # 文件句柄
        print(file_obj.name)  # 获取文件名
 
        # 下面的for循环可以写成django推荐的写法
        # for chunk in file_obj.chunks():
        #       print(chunk)
        with open(file_obj.name,'wb') as f:
            for line in file_obj:
                f.write(line)
 
   return render(request,'home.html')

And a function of CBV view FBV

FBV: function-based view

CBV: class-based view

CBV basic writing:

# views.py
from django.views import View
 
 
class MyLogin(View):
    def get(self, request):
        return render(request, 'login.html')
 
    def post(self, request):
        return HttpResponse('我是类里面的POST方法')
 
 
# urls.py
url(r'login/', views.MyLogin.as_view())

North Korea login to submit requests get executed automatically MyLogin inside the get method

Post requests submitted automatically performed inside the post method MyLogin

Why MyLogin can automatically execute the corresponding method for different request methods?

Study the source code of a breakthrough

url(r'^login/', views.MyLogin.as_view())

as_view either a normal function inside the class definition @staticmethod
is either binding to the class which defines the class method @classmethod
point into view:

We found that the final return is a view, so we outside the url equivalent to the following:

url(r'^login/', views.MyLogin.view)

Then go view function:

url(r'^login/', views.MyLogin.dispatch)

Back MyLogin create their own classes, see the class inherits View, point to go to find this dispatch method:

Read on:

Thus, this case corresponds to the url:

url(r'^login/', views.MyLogin.get)

See the source code does not need to understand every sentence, you can look can understand

CBV源码(******)
    MyClass.as_view()
    # 函数名加括号执行优先级最高
    @classonlymethod
    def as_view(...):
        def view(...):
            ...
        return view
    # 变形
    url(r'^index/',views.view)  # CBV与FBV在路由匹配上本质是一样的
    
    def view(...):
        self = cls(...)  # 生成的是我们自己写的类的对象
        ...
        return self.dispatch(...)
        """
        当你看到self.属性或方法的时候 不要想当然 
        一定要遵循对象的属性和方法的查询顺序
        对象本身  产生对象的类  类的父类
        """
    def dispatch(...):
        # 先判断当前请求方式是否在默认的八个合法请求方式内
        if request.method.lower() in ['get','post','delete','options'...]
            # 利用反射获取对象中对应的属性
            handler = getattr(self,request.method.lower(),报错信息)
        
        return handler(...)  # 执行获取到的方法

Django Settings Source

First, let's get inside django configuration file:

from django.conf import global_settings, settings

global_settings file has a lot of configuration information
django exposed to a user can customize the configuration but also internal default configuration
you configure a user to use the user does not have to use the default distribution
point settings to see inside:

Global large dictionary is initially empty, so is equivalent to:

os.environ.get(ENVIRONMENT_VARIABLE)

Point into ENVIRONMENT_VARIABLE:

at this time:

{}.get("DJANGO_SETTINGS_MODULE")

Therefore, we need to find who gave a big dictionary set DJANGO_SETTINGS_MODULE key to our point of view the open manage.py:

therefore:

And then look down:

Call Settings category, passing mysite, produce objects, so click through Sttings in:

from django.conf import global_settings,settings

settings = LazySettings()


class LazySettings(...):
    def _setup(...):
        # 获取暴露给用户的配置文件字符串路径
        setting_module = os.environ.get(纯大写变量名)
        """
        manage.py
        os.environ.setdefault(纯大写变量名,'暴露给用户的配置文件字符串路径')
        """
        
        Settings(setting_module)
def Settings(...)
    # 先遍历全局默认的配置文件       给对象设置键值对
    for setting in dir(global_settings):
        if setting.isupper():
            setattr(self,setting,getattr(global_settings,setting))
            
    
    # 再遍历暴露给用户的配置文件     给对象设置键值对
    md = importlib.import_module(setting_module)
    for setting in dir(md):
        if setting.isupper():
            setattr(self,setting,getattr(md,setting))
    """
    利用的其实就是字典的键存在和不存在 下面语句的作用
    dict[key] = value
    """

Guess you like

Origin www.cnblogs.com/cnhyk/p/12173521.html