程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Python Flask Blueprint Blueprint

編輯:Python

Python Flask Blueprint

In this article, let's take a look at the Blueprint blueprint in Flask, what blueprint..It is just an extension of sub-modules, which is used to divide different business module apis into different python files, which is similar to @RequestMapping("/") at the class level of Spring mvc..

Antecedents:

Why introduce Blueprints?Because if the API interface is written into a py file by default, the file will become more and more complicated, and it will become more and more bloated and unmaintainable. Therefore, according to the normal development logic, it is necessary to divide the modules, so it is necessary to introduce Blueprint

1.Install Blueprint

You need to use pip to install the Blueprint extension in the environment first

pip install Blueprint

2. write Flask entry py file

from flask import Flaskapp = Flask(__name__)@app.route('/')def helloworld():return 'Hello world python flask'# The new version should not support this startup# if __name__ == '__main__':# app.run()

3. Write User module user.py file

According to the business, you can create a new module and then register the route through Blueprint

from flask import Blueprintuser = Blueprint('user',__name__)@user.route('/user/username')def username():return 'get username : johnny'

4.Blueprint registered to Flask app

Register the newly created Blueprint in the entry file

from flask import Flask#Introduce the blueprint just createdfrom user import userapp = Flask(__name__)#Register to flask appapp.register_blueprint(user)@app.route('/')def helloworld():return 'Hello world python flask'# if __name__ == '__main__':# app.run()

5.Verification

Access: /user/username gets the following:

Access: / Get as follows:

Summary:

Using Blueprint is easy follow the process below

  1. pip install Blueprint

  2. Create a new module file and create a Blueprint object in it, such as:

    # Blueprint two parameters ('blueprint name', blueprint location')user = Blueprint('user',__name__)
  3. Blueprint is registered to the Flask app

    #Introduce the blueprint just createdfrom user import userapp = Flask(__name__)app.register_blueprint(user)

Blueprint can be understood as Spring mvc's Class-level @RequestMapping("/user") is similar..

Welcome to my personal blogJohnny's house
Welcome to follow my personal accountp>


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved