Django(五)

Django(五)

request对象

# GET POST FILES method
path path_info get_full_path() body

def index(request):
    print(request.path)  # /index/
    print(request.path_info)  # /index/
    print(request.get_full_path_info())  # 接收路径的全部内容连参数也能拿到
    print(request.body)  # 浏览器发过来的二进制数据
    return HttpResponse('OK')

CBV(class based view)和FBV(function based view)

# 之前写的都是FBV
# 也可以写CBV
在视图中写类

path('login/', views.MyLogin.as_view()),  # 在urls中写

# CBV必须继承View
class MyLogin(View):
    def get(self, request):  # 通过get请求方式会访问到这个方法
        return HttpResponse('get')

    def post(self, request):  # 通过post请求方式会访问到这个方法
        return HttpResponse('post')

CBV的源码剖析

# 看源码先找入口,入口在路由
path('login/', views.MyLogin.as_view()),

"""
    类来调用方法:
        1. 被@classmethod装饰器修饰的方法
        2. 被@staticmethod装饰器修饰的方法
    我们在MyLogin类中并没有写as_view(), 可能会在父类中

    views.MyLogin.as_view()-------------------->View类里面的as_view方法中得view方法的内存地址
"""

@classonlymethod  # 本质上就是@classmethod只是比他更强大

path('login/', views.MyLogin.as_view()), # 本质上放的还是函数的内存地址
path('index/', views.index),
# 当请求来了,会自定触发view函数的执行
def view(request, *args, **kwargs):
   self = cls(**initkwargs) #  # self = MyLogin(**initkwargs)
   return self.dispatch(request, *args, **kwargs)  # 执行完毕调用这个方法


def dispatch(self, request, *args, **kwargs):
    if request.method.lower() in self.http_method_names:  # 获取request的请求方式并转为小写,然后去往MyLogin的http_method_names里找
        handler = getattr(self, request.method.lower(), self.http_method_not_allowed)  # 反射,当request.method.lower()不存在的时候就返回http_method_not_allowed
    else:
        handler = self.http_method_not_allowed  # 没找到也返回值这个
        return handler(request, *args, **kwargs)  # 加上括号,直接调用这个方法
    
    
def http_method_not_allowed(self, request, *args, **kwargs):  # 主动抛出异常的方法
    logger.warning(
        'Method Not Allowed (%s): %s', request.method, request.path,
        extra={'status_code': 405, 'request': request}
    )
    return HttpResponseNotAllowed(self._allowed_methods())


http_method_names = ['get', 'post', 'put', 'patch', 'delete', 'head', 'options', 'trace']

# 权限 频率等的源码稍微复杂

'''源码时让你用来看的,不是让你用来改的,当你想要改源码的时候可以在自己写的继承了源码的类里面进行属性的重写'''
class MyLogin(View):
    http_method_names = ['get', 'post']  
    # 我写的这个类只允许get请求,怎么做?
    # 通过get请求方式会访问到这个方法
    def get(self, request):
        return HttpResponse('get')

    # 通过post请求方式会访问到这个方法
    def post(self, request):
        return HttpResponse('post')

模板层

{{ }}  跟变量相关的

{% %} 跟逻辑相关的

# 简单来说,模板层就是html文件,在html文件里面django给你提供了一些模板语法,是html自身不带的
# 模板变量的分配

'''模板里面取值一律使用点语法 .'''

# 在模板语法里面,函数的时候,不需要加括号,直接使用函数名,它会自动给你加括号调用。不可传参

模版之过滤器

django提供的过滤器:filter__name,我们需要学10个左右
# 语法
{{obj|filter__name:param}}  变量名字|过滤器名称:变量
from django.utils.safestring import mark_safe
s1 = mark_safe('<h1>hello</h1>')
{{ h|default:'nothing' }}
{{ c|length }}
{{ filesize|filesizeformat }}
{{ ctime|date:'Y-m-d' }}
{{ s|truncatechars:5 }}
{#{{ s1|safe }}#}
{#{{ s2|safe }}#}

{{ s1 }}

模版之标签

# 遍历字典
# 字典的三剑客
keys values items
forloop.counter            The current iteration of the loop (1-indexed) 当前循环的索引值(从1开始)
forloop.counter0           The current iteration of the loop (0-indexed) 当前循环的索引值(从0开始)
forloop.revcounter         The number of iterations from the end of the loop (1-indexed) 当前循环的倒序索引值(从1开始)
forloop.revcounter0        The number of iterations from the end of the loop (0-indexed) 当前循环的倒序索引值(从0开始)
forloop.first              True if this is the first time through the loop 当前循环是不是第一次循环(布尔值)
forloop.last               True if this is the last time through the loop 当前循环是不是最后一次循环(布尔值)
forloop.parentloop         本层循环的外层循环


if 标签

# {% if %}会对一个变量求值,如果它的值是True(存在、不为空、且不是boolean类型的false值),对应的内容块会输出。

{% if num > 100 or num < 0 %}
    <p>无效</p>
{% elif num > 80 and num < 100 %}
    <p>优秀</p>
{% else %}
    <p>凑活吧</p>
{% endif %}

# if语句支持 and 、or、==、>、<、!=、<=、>=、in、not in、is、is not判断。
csrf_token: {% csrf_token%}

模板的继承和导入

# 一个模板页面中应该至少有3块内容可以被替换
1. css
2. js
3. html
{% extends 'home.html' %}

{% block css %}
    <style>
        h1 {
            color: red;
        }
    </style>
{% endblock %}


{% block js %}
    <script>

    </script>
{% endblock %}

# 模板的导入
 {% include 'welcome.html' %}

posted @ 2023-04-25 15:32  橘子熊何妨  阅读(25)  评论(0)    收藏  举报