Flask 快速開始一個(gè)hello world

pip install Flask

app.py

from flask import Flask
# 引入Flask類,他的實(shí)例將是我們的WSGI應(yīng)用
app = Flask(__name__)
# 創(chuàng)建Flask的實(shí)例,傳入?yún)?shù),當(dāng)前模塊的名字,一般默認(rèn)當(dāng)前模塊為主模塊,名稱為__main__,也可使用__name__代替

@app.route('/')
def hello_world():
    return 'Hello, World!'
# 使用route標(biāo)識(shí)URL

if __name__ == '__main__':
    app.run(debug=True)
# 在命令行輸入python app.py即可啟動(dòng),傳入?yún)?shù)debug=True即可進(jìn)入調(diào)試模式

可參考blog

  • 變量規(guī)則
from markupsafe import escape

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

@app.route('/post/<int:post_id>')
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/<path:subpath>')
def show_subpath(subpath):
    # show the subpath after /path/
    return 'Subpath %s' % escape(subpath)

可以在route中傳遞變量 <variable_name>,也可以指定傳遞的變量的格式<converter:variable_name>

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帶斜杠時(shí),如果輸入的地址不帶斜杠,會(huì)被重定向,@app.route('/projects')URL不帶斜杠時(shí),如果輸入的地址帶有斜杠會(huì)404

  • 地址構(gòu)建 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/<username>')
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/<name>')
def hello(name=None):
    return render_template('hello.html', name=name)
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

友情鏈接更多精彩內(nèi)容