敵のいない勉強部屋

日々学んだことや感じたことを書きます

英語字幕DB作成への道_Flask編③ (Variable Rules)

前回作成したコードには問題がありました。
それは、URLから取得した変数の値が、すべてstr型になってしまっていること。

解決策はこちらにありました。
flask.palletsprojects.com

from markupsafe import escape

@app.route('/user/<username>')
def show_user_profile(username):
    # show the user profile for that user
    return f'User {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 f'Post {post_id}'

@app.route('/path/<path:subpath>')
def show_subpath(subpath):
    # show the subpath after /path/
    return f'Subpath {escape(subpath)}'

要は <型:変数名> の書式で書けば良いようです。
とても簡単! この辺はDjangoと同じですね。

シンプルで使いやすい!