zoukankan      html  css  js  c++  java
  • 【Flask】CBV模式

    Flask中的CBV模式

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    '''
    flask中的CBV模式:
    (1)导入views模块: from flask import views
    (2)定义类,继承views.MethodView类: class 类名(views.MethodView)
    (3)在类中定义函数名为允许的请求方式的小写形式,进行函数定义,如def get(self):...
    (4)添加路由规则:
         CBV:app.add_url_rule(rule,endpoint='',view_func=类名.as_view(name=''))
         FBV:app.add_url_rule(rule,endpoint='',view_func=函数名))(直接替代@app.route()方式)
     
         参数:
            rule 请求路径
            endpoint设置mapping路由映射函数rule:{endpoint:func}
            view_func路由映射的视图函数或者类(as_view()中的name参数设置当前路由映射函数名,唯一指定,不设置endpoint自动为name值)
    (5)methods=[]类中设置属性,添加允许的请求方式,不写默认都支持
    (6)decorators = []对类中的函数都加上装饰器,列表中可以放多个装饰器函数名,以此执行
    '''
    复制代码
    from flask import Flask,views,render_template,request
    app = Flask(__name__)
    
    class Login(views.MethodView):
        # methods = ["GET","POST"]  # 指定请求方法,这里可以省略不写,根据请求方法自动找到对应的方法去执行
        decorators = [] #对类中的函数都加上装饰器,列表中可以放多个装饰器函数名,依次执行
        def get(self):
            return render_template("login.html")
    
        def post(self):
            username = request.form.get("username")
            password = request.form.get("password")
            # 判断用户名和密码是否正确
            if username == "henry" and password == "123456":
                return "200 ok"
            else:
                return "用户名或密码错误"
    app.add_url_rule("/login",endpoint=None,view_func=Login.as_view(name="login"))  # name其实就是用来填充endpoint的,如果endpoint有值那么name就没有用,且name这个参数是必填的,相当于别名
    app.run("0.0.0.0",9527)
  • 相关阅读:
    [编程题]多多的数字组合
    mac传输文件到服务器
    git 清除缓存、查看add内容
    go build
    vim编辑器
    Git: clone指定分支
    查看端口占用以及kill
    curl小记录
    Python3.9 malloc error: can’t allocate region
    设计模式-策略模式
  • 原文地址:https://www.cnblogs.com/youxiu123/p/11624305.html
Copyright © 2011-2022 走看看