[PYTHON] Flask introduction-Blueprint application memo

Let's do the title as easily as possible.

Blueprint allows you to split and implement the functionality of your application. Blueprints are officially recommended as a way to organize bloated projects.

Flask installation

$ sudo pip3 install flask

Directory structure

$ cd ~/workspace/sample-flask/

$ ls
server.py

server.py


from flask import Flask

app = Flask(__name__)

@app.route('/')
def func_1():
    return 'Hello world'

@app.route('/test')
def func_2():
    return 'Test'

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=80, debug=True)

Execution command

$ python3 server.py
 * Serving Flask app "server" (lazy loading)
 * Environment: production
   WARNING: This is a development server. Do not use it in a production deployment.
   Use a production WSGI server instead.
 * Debug mode: on
 * Running on http://0.0.0.0:80/ (Press CTRL+C to quit)
 * Restarting with stat
 * Debugger is active!
 * Debugger PIN: 337-601-528
127.0.0.1 - - [02/Mar/2020 11:18:06] "GET / HTTP/1.1" 200 -

Ignore WARNING for the time being When I access 127.0.0.1 from a browser, it says Hello world. Then, when you access 127.0.0.1 / test in your browser, it will be displayed as Test.

Split with Blueprint

Try splitting "/ test" into separate files. I created a directory called func and created test.py under it.

Directory structure

$ cd ~/workspace/sample-flask/func

$ ls
__init__.py
test.py

Import Blueprint, Create a Blueprint object with the cut out test.py.

test.py


from flask import Blueprint

#Create a Blueprint object
app = Blueprint('func', __name__)

@app.route('/test')
def func_2():
    return 'Test'

Register the divided Blueprint on the server.py side.

server.py


from flask import Flask
from func import test

app = Flask(__name__)
#Register the split blueprint
app.register_blueprint(test.app)

@app.route('/')
def func_1():
    return 'Hello world'

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=80, debug=True)

Let's run it and see if the routing is working.

When you access 127.0.0.1 from the browser as before, Hello world is displayed and Then, when you access 127.0.0.1 / test in your browser, it will be displayed as Test.

If all goes well, you can use Blueprint to split it.

reference

https://www.subarunari.com/entry/2017/10/11/003225

Recommended Posts

Flask introduction-Blueprint application memo
Flask memo
Flask Primer Memo
Flask basic memo
Flask application settings
Web application with Python + Flask ② ③
Web application with Python + Flask ④
Creating a web application using Flask ②
[Memo] Links for developing with Flask
Web application development memo in python
flask
Hello World in Flask [Appropriate memo]
flask
Creating a web application using Flask ①
Creating a web application using Flask ③
Creating a web application using Flask ④
Application development with Docker + Python + Flask
Try using the web application framework Flask