小男孩‘自慰网亚洲一区二区,亚洲一级在线播放毛片,亚洲中文字幕av每天更新,黄aⅴ永久免费无码,91成人午夜在线精品,色网站免费在线观看,亚洲欧洲wwwww在线观看

分享

Flask后端實踐 連載十二 Flask優(yōu)雅的注冊藍圖及自定義MethodView

 看見就非常 2020-04-29

tips:

  • 介紹如何有效的統(tǒng)一注冊藍圖及自定義MethodView
  • 本文基于python3編寫
  • 代碼倉庫

目的

在項目開發(fā)中,通常采用工程模式來創(chuàng)建app,如果注冊接口寫在工廠函數(shù)中,不僅不好管理,而且代碼也看起來很臃腫。并且項目中會有很多模塊,每個模塊又有不同的功能,由此分割出來的接口也非常多。所有需要有統(tǒng)一的地方來管理接口及相關模塊。

解決方法

  1. 編寫藍圖(user.py)

    from flask import Blueprint
    
    bp = Blueprint("test", __name__, url_prefix='/')
    
    
    @bp.route('/testBP', methods=["GET"])
    def test_bp():
        return "藍圖測試"
    
    
  2. 編寫自定義MethodView(auth.py)

    from flask.views import MethodView
    
    class AuthMethodView(MethodView):
        # 指定需要啟用的請求方法
        __methods__ = ["GET", "POST", "PUT"]
    
        def get(self):
            return "測試自定義MethodView"
    
        def post(self):
            return "測試自定義MethodView"
    
        def put(self):
            return "測試自定義MethodView"
    
        def delete(self):
            return "測試自定義MethodView"    
    
  3. 統(tǒng)一管理藍圖和自定義MethodView(router.py)

    from user import bp as user_bp
    from auth import AuthMethodView
    
    router = [
        user_bp, # 用戶藍圖接口
        AuthMethodView, # 權限自定義MethodView
    ]
    
  4. 統(tǒng)一注冊藍圖和自定義MethodView(app.py)

    from flask import Flask, Blueprint
    from router import router
    
    
    def create_app():
        """
        工廠模式創(chuàng)建APP
        """
        app = Flask(__name__)
        # 注冊接口
        register_api(app, router)
    
        return app
    
    
    def register_api(app, routers):
        """
        注冊藍圖和自定義MethodView
        """
        for router in routers:
            if isinstance(router, Blueprint):
                app.register_blueprint(router)
            else:
                try:
                    endpoint = router.__name__
                    view_func = router.as_view(endpoint)
                    # url默認為類名小寫
                    url = '/{}/'.format(router.__name__.lower())
                    if 'GET' in router.__methods__:
                        app.add_url_rule(url, defaults={'key': None}, view_func=view_func, methods=['GET', ])
                        app.add_url_rule('{}<string:key>'.format(url), view_func=view_func, methods=['GET', ])
                    if 'POST' in router.__methods__:
                        app.add_url_rule(url, view_func=view_func, methods=['POST', ])
                    if 'PUT' in router.__methods__:
                        app.add_url_rule('{}<string:key>'.format(url), view_func=view_func, methods=['PUT', ])
                    if 'DELETE' in router.__methods__:
                        app.add_url_rule('{}<string:key>'.format(url), view_func=view_func, methods=['DELETE', ])
                except Exception as e:
                    raise ValueError(e)
    
    
    if __name__ == '__main__':
        app = create_app()
        app.run()
    
    
  5. 測試,啟動app

  • 瀏覽器訪問http://127.0.0.1:5000/testBP,頁面返回藍圖測試

  • 瀏覽器訪問http://127.0.0.1:5000/authmethodview/ ,頁面返回測試自定義MethodView

總結

  • 統(tǒng)一管理了藍圖和自定義的MethodView,并減少了代碼的冗余,保持代碼的整潔性。
  • 下一篇將介紹使用flask輸出excel報表

    本站是提供個人知識管理的網(wǎng)絡存儲空間,所有內(nèi)容均由用戶發(fā)布,不代表本站觀點。請注意甄別內(nèi)容中的聯(lián)系方式、誘導購買等信息,謹防詐騙。如發(fā)現(xiàn)有害或侵權內(nèi)容,請點擊一鍵舉報。
    轉藏 分享 獻花(0

    0條評論

    發(fā)表

    請遵守用戶 評論公約

    類似文章 更多