Flask Route

service firewalld status
#if Firewalld not running
service firewalld start
firewall-cmd --zone=public --permanent --add-port=5000/tcp
firewall-cmd --zone=public --list-all

#mkdir <flask_root> and into flask_root dir
mkdir /home/pyenv/versions/2.7.13/envs/flask_test
cd
/home/pyenv/versions/2.7.13/envs/flask_test
pyenv activate

#pip upgrade all pkg/moule
pip list -o | awk '{ print $1 }' | xargs pip install -U

pip install flask

#mkdir <ap_dir> for flask web use then into ap dir
mkdir www
cd www

vi hello.py

from flask import Flask
app = Flask(__name__)

@app.route("/")
def index():
     return "It's Flask!"

@app.route("/<name>")
def hello(name):
     return "Hello, %s! :)" %name

if __name__ == "__main__":
    app.run(host='0.0.0.0')

python hello.py

#Open web browser with http://<ip>:5000

===

1.
@app.route('<route>', options)
def func():
    ....

above is the same as below

def func():
    ....
app.add_url_rule('<route>', 'func', func, options)

2.
@app.route("/xxx/") -> <url>/xxx == <url>/xxx/ (like to a dir)
@app.route("/xxx") -> <url>/xxx/ -> 404 Not Found (like to a file)

3.
@app
.route('/<name>')
@app
.route('/<path/<int:var>') #type(var) == type(int)
@app
.route('/hello/<float:var>') #type(var) == type(float)

The variable rules of route():
http://flask.pocoo.org/docs/0.12/quickstart/#variable-rules

4.
url_for():

from flask import Flask, redirect, url_for

#static route(url path):

app.route('/admin')
def
hello_admin():

   
return 'Hello, Admin.'


@app
.route('/<guest>')

def
hello_guest(guest):

   
return 'Hello,
%s.' % guest

#dynamic route(url path):

app.route('/user/<name>')
def
hello(name):
   
if name =='admin':
       
return redirect(url_for('hello_admin.'))
   
else:
       
return redirect(url_for('hello_guest', guest=name)) #using keyword assign parameter into func()

5.
app.run(host, port, debug, **options)

The options of run():
http://werkzeug.pocoo.org/docs/0.14/serving/#werkzeug.serving.run_simple




Leave comments

authimage

Copyright(c) 2017 - PythonBlogs.com
By using this website, you signify your acceptance of Terms and Conditions and Privacy Policy
All rights reserved