Python_Flask视图类和蓝图

发布时间 2023-11-06 19:57:59作者: 辰令

Flask 视图类

 1.设置路由的新方法:将 URL 路径和一个视图类关联
  将 URL 路径和一个函数关联,这个函数又被称为视图函数
  在 Flask 中,也可以使用类来处理相关的 URL,这样的也被称为视图类。
      使用类视图的好处是支持继承,可以把一些共性的东西放在父类中,其他子类可以继承
 ###代码示例
  视图类的例子 basis.py:
  from flask import Flask, views
  
  app = Flask(__name__)
  class Index(views.View) :
      def dispatch_request(self):
          return 'hello world' 
 app.add_url_rule(rule='/', view_func = Index.as_view('Index'))
 app.run(debug = True)
 ###视图类的本质是视图函数,函数 View.as_view () 返回一个视图函数

###代码
from flask import Flask,render_template,request
from flask.views import MethodView
 
app = Flask(__name__)
 
class loginView(MethodView):
    def get(self):
        return render_template('login05.html')
    def post(self):        
        uname = request.form.get('uname')
        pwd = request.form.get('pwd')
        if uname == 'xiaolin' and pwd == '123456':
            return '登录成功!'
        else:
            return render_template('login05.html',msg='用户名或者密码错误!')
app.add_url_rule('/login/',view_func=loginView.as_view('login'))  
if __name__ == '__main__':

Flask 蓝图

使用蓝图进行应用模块化
    在蓝图被注册到应用之后,所要执行的操作的集合。
	当分配 请求时, Flask 会把蓝图和视图函数关联起来,并生成两个端点之前的 URL 。 
不需要对请求类型进行判断
###蓝图 Blueprint并不是一个完整的应用,它不能独立于应用运行,而必须要注册到某一个应用中
使用蓝图Blueprint来分模块组织管理 可以为蓝图添加一个独特的前缀,增加辨识度。
   user_pb = Blueprint('user',__name__)
   # user_bp = Blueprint('user',__name__,url_prefix='/user',template_folder='user_page')
   app.register_blueprint(user_bp, url_prefix='/user')


from flask import Blueprint, render_template

# 创建一个蓝图对象
bp = Blueprint('my_blueprint', __name__)

# 在蓝图上定义路由和视图函数
@bp.route('/hello')
def hello():
    return 'Hello, World!'

@bp.route('/greet/<name>')
def greet(name):
    return 'Hello, {}'.format(name)

# 在应用程序对象上注册蓝图
app = Flask(__name__)
app.register_blueprint(bp, url_prefix='/myapp')

快速开始

一个函数内部创建 Flask 实例来代替创建全局实例。这个函 数被称为 应用工厂 
   所有应用相关的配置、注册和其他设置都会在函数 内部完成,然后返回这个应用
创建 flaskr 文件夹并且文件夹内添加 __init__.py 文件。
    __init__.py 有两个作用:一是包含应用工厂; 
	二是告诉 Python flaskr 文件夹应当视作为一个包

代码示例

   ###flaskr/__init__.py
import os
from flask import Flask


def create_app(test_config=None):
    # create and configure the app
    app = Flask(__name__, instance_relative_config=True)
    app.config.from_mapping(
        SECRET_KEY='dev',
        DATABASE=os.path.join(app.instance_path, 'flaskr.sqlite'),
    )

    if test_config is None:
        # load the instance config, if it exists, when not testing
        app.config.from_pyfile('config.py', silent=True)
    else:
        # load the test config if passed in
        app.config.from_mapping(test_config)

    # ensure the instance folder exists
    try:
        os.makedirs(app.instance_path)
    except OSError:
        pass

    # a simple page that says hello
    @app.route('/hello')
    def hello():
        return 'Hello, World!'

    return app		
	
 url_for() 函数根据视图名称和发生成 URL 。视图相关联的名称亦称为 端点 ,缺省情况下,端点名称与视图函数名称相同。

项目可安装化

  项目可安装化是指创建一个 wheel 文件,以使项目可以安装到其他环境中
    pyproject.toml 文件描述项目及其构建方法
	setuptools 构建后端需要 MANIFEST.in 文件来说明需要包含的非 Python 文件
   当需要把应用部署到其他地方时,需要构建一个 wheel ( .whl )文件。 构建工作需要安装和使用 build 工具。

Sanic 蓝图

#将一系列路由注册到蓝图上而不是直接注册到应用上,然后再以可插拔的方式将蓝图注册到到应用程序
from sanic.response import json
from sanic import Blueprint
from sanic import Sanic

bp = Blueprint("my_blueprint")
@bp.route("/")
async def bp_root(request):
    return json({"my": "blueprint"})
	
authors = Blueprint("content_authors", url_prefix="/authors")
static = Blueprint("content_static", url_prefix="/static")
content = Blueprint.group(static, authors, url_prefix="/content")
 	
app = Sanic(__name__)
app.blueprint(bp)

基于类的视图(Class Based Views)

###基于类的视图现在拥有以下三种关联app的方式
  1.类
   class FooBar(HTTPMethodView):
    ...
  2.三种关联app
    01. app.add_route(FooBar.as_view(), "/dummy")
    02. FooBar.attach(app, "/")
	
###基于类的视图是一种实现了响应请求行为的类,该类提供了一种在同一路由上分隔处理不同 HTTP 请求类型的方法
from sanic.views import HTTPMethodView

class FooBar(HTTPMethodView):
    async def get(self, request):
        ...
  
    async def post(self, request):
        ...
        
app.add_route(FooBar.as_view(), "/foobar")

工厂应用(Factory applications)

 对于遵循工厂模式(一个返回 sanic.Sanic 实例的函数)的应用程序,您可以在 Sanic 命令行工具中添加 --factory 标志来启动它。	
 update() 方法可使用一个字典所包含的键值对来更新己有的字典。

dict() 在执行 update() 方法时,
   如果被更新的字典中己包含对应的键值对,那么原 value 会被覆盖;
   如果被更新的字典中不包含对应的键值对,则该键值对被添加进去

参考

https://blog.csdn.net/m0_67093160/article/details/127723186	
https://dormousehole.readthedocs.io/en/latest/blueprints.html