Flask 快速开始一个hello world

  • 安装INSTALL
pip install Flask
  • 快速开始quickstart

app.py

from flask import Flask
# 引入Flask类,他的实例将是我们的WSGI应用
app = Flask(__name__)
# 创建Flask的实例,传入参数,当前模块的名字,一般默认当前模块为主模块,名称为__main__,也可使用__name__代替

@app.route('/')
def hello_world():
    return 'Hello, World!'
# 使用route标识URL

if __name__ == '__main__':
    app.run(debug=True)
# 在命令行输入python app.py即可启动,传入参数debug=True即可进入调试模式

可参考blog

  • 变量规则
from markupsafe import escape

@app.route('/user/')
def show_user_profile(username):
    # show the user profile for that user
    return 'User %s' % escape(username)

@app.route('/post/')
def show_post(post_id):
    # show the post with the given id, the id is an integer
    return 'Post %d' % post_id

@app.route('/path/')
def show_subpath(subpath):
    # show the subpath after /path/
    return 'Subpath %s' % escape(subpath)

可以在route中传递变量 ,也可以指定传递的变量的格式

converter desc
string (default) accepts any text without a slash
int accepts positive integers
float accepts positive floating point values
path like string but also accepts slashes
uuid accepts UUID strings
  • URL唯一性与重定向
    @app.route('/projects/')URL带斜杠时,如果输入的地址不带斜杠,会被重定向,@app.route('/projects')URL不带斜杠时,如果输入的地址带有斜杠会404

  • 地址构建 url_for()

from flask import Flask, url_for
from markupsafe import escape

app = Flask(__name__)

@app.route('/')
def index():
    return 'index'

@app.route('/login')
def login():
    return 'login'

@app.route('/user/')
def profile(username):
    return '{}\'s profile'.format(escape(username))

with app.test_request_context():
    print(url_for('index'))
    print(url_for('login'))
    print(url_for('login', next='/'))
    print(url_for('profile', username='John Doe'))
/
/login
/login?next=/
/user/John%20Doe

使用url_for()之后,可以不用每次修改URL之后都去修改别的地方引用的URL。

  • HTTP方法
from flask import request

@app.route('/login', methods=['GET', 'POST'])
def login():
    if request.method == 'POST':
        return do_the_login()
    else:
        return show_the_login_form()
  • 使用模板
from flask import render_template

@app.route('/hello/')
@app.route('/hello/')
def hello(name=None):
    return render_template('hello.html', name=name)

你可能感兴趣的:(Flask 快速开始一个hello world)