setting
Create a project and a venv folder within
mkdir 01_project
cd 01_project
sudo apt-get install python3-venv
sudo apt-get install python3-wheel
python3 -m venv venv
Activate the environment
. venv/bin/activate
Install flask
pip install Flask
Living on the edge(latest flask)
pip install -U https://github.com/pallets/flask/archive/master.tar.gz
first program
Coding
# hello.py
from flask import Flask
app = Flask(__name__)
@app.route('/')
def hello_world():
return 'hello flask'
Run
sudo apt-get install python3-flask
$ export FLASK_APP=hello.py
$ flask run
or python -m flask run
or flask run --host=0.0.0.0 (this can tells your system to listen on all public IPs)
* Running on http://127.0.0.1:5000/
Debug mode
change you code and needn’t to restart
$ export FLASK_APP=***.py
$ export FLASK_ENV=development
$ flask run
Variable Rules
from flask import Flask
app = Flask(__name__)
@app.route('/')
def index():
return 'Index Page'
@app.route('/hello')
def hello_world():
return 'Hello, world!'
@app.route('/user/<username>')
def show_user_profile(username):
# show the user profile for that user
return 'User %s' % username
@app.route('/post/<int:post_id>')
def show_post(post_id):
# show the post with the given id , the id is a integer
return 'Post %s' % post_id
@app.route('/path/<path:subpath>')
def show_subpath(subpath):
# show the subpath after /path/
return 'Subpath %s' % subpath
'''
string: (default) access any text with a slash 削减/斜线
int: accept positive integers
float: accepts positive floating point values
path: like string but also accepts slashs
uuid: accepts UUID strings
'''
Unique URLs/Redirection Behavior
The following two rules differ in their use of a trailing slash.
@app.route('/projects/')
def projects():
return 'The project page'
@app.route('/about')
def about():
return 'The about page'