Flask in Python!
Flask is a Micro Web Framework.
Web Framework is a set of tools used to help create Web Services and Web APIs.
1
2
3
4
5
6
| from flask import Flask
app = Flask(__name__)
@app.route("/")
def index():
return "Welcome to Index Page"
|
1
| FLASK_APP=flask_app flask run
|
1
2
3
4
| @app.route('/index/', defaults={'num' : 0 })
@app.route('/index/<num>')
def index_number(num):
return f'Welcome to Index {num}'
|
Now lets take a look at using blueprint.
1
2
3
4
5
6
7
8
9
10
11
12
| .
├── Pipfile
├── Procfile
├── README.md
├── requirements.txt
├── flask_app
│ ├── templates
│ │ └── index.html
│ └── views
│ ├── admin.py
│ └── frontend.py
└── __init__.py
|
1
2
3
4
5
6
7
8
9
| # frontend.py
from flask import Blueprint
frontend = Blueprint('frontend', __name__, url_prefix='/user')
@bp.route('/')
def index():
return "User frontend index page"
|
1
2
3
4
5
6
7
8
9
| # admin.py
from flask import Blueprint
admin = Blueprint('admin', __name__, url_prefix='/user')
@bp.route('/')
def index():
return "User admin index page"
|
Blueprint takes name, modulename, urlprefix as arguments.
The name is used to find url with the function url_for().
ex) url_for(“main”)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
| # __init__.py
from flask import Flask
def create_app():
app = Flask(__name__)
from flask_app.views.admin import admin
from flask_app.views.frontend import frontend
app.register_blueprint(admin)
app.register_blueprint(frontend)
return app
if __name__ == "__main__":
app = create_app()
app.run()
|
Leave a comment