Flaskのurl_forの使い方を解説
2024年7月8日

こんにちは!
FlaskはPythonで作られた軽量のWebフレームワークであり、そのシンプルや使いやすさから多くの開発者につかわれています。
今回の記事では、Flaskの主要な機能の一つであるurl_for関数の使い方について詳しく解説したいと思います。
Flaskのurl_for関数とは?
まずは、url_for関数の概要から説明します!
url_for関数の概要
url_for関数は、FlaskでURLを生成するために使用される関数です。
主に、指定されたエンドポイントのURLを構築するために使用されます。
FlaskアプリケーションでURLのハードコーディングをせずに、動的にURLを生成することができます。
url_for関数の基本的な使い方
url_for関数の基本的な使い方はこちらです。
url_for('[関数名]',[オプション])
例えば、以下のようなapp.pyを作成します。これは、2つのルーティングがあります。
from flask import Flask, url_for
app = Flask(__name__)
@app.route('/')
def index():
return 'Index Page'
@app.route('/hello')
def hello():
return 'Hello, World!'
この場合、url_for関数を実行してみると、それぞれのパス(URL)が生成されます。
print(url_for('index')) # 出力: /
print(url_for('hello')) # 出力: /hello
このようにurl_for関数を使います。
url_for関数の引数
url_for関数にはさまざまな引数を指定することができます。
引数名 | 説明 | 使用例 |
---|---|---|
endpoint | URLを生成するためのエンドポイントの名前。通常はビュー関数の名前。 | url_for(‘index’) |
values | URLルールで指定された動的セグメントに対するキーワード引数。 | url_for(‘profile’, username=’John’) |
_external | 完全なURLを生成するかどうかを指定するブール値。Trueを指定するとスキームとホスト名を含む完全なURLを生成。 | url_for(‘index’, _external=True) |
_scheme | URLのスキーム(通常はhttpまたはhttps)を指定。 _external=Trueと併用する。 | url_for(‘index’, _external=True, _scheme=’https’) |
_anchor | URLのアンカー(フラグメント)部分を指定。 | url_for(‘index’, _anchor=’section’) |
_method | 特定のHTTPメソッドに対応するURLを生成するために使用。通常はカスタムルールと併用。 | url_for(‘submit’, _method=’POST’) |
それぞれの引数の使い方について解説します。
values
動的なURLパラメータを使用する場合、url_for
にキーワード引数として渡します。
例えば、URLが動的に変更するユーザーページやブログ記事などです。
以下のように、/user/[ユーザー名]のようなパスの際にurl_forに値を渡します。
@app.route('/user/<username>')
def profile(username):
return f'User: {username}'
with app.test_request_context():
print(url_for('profile', username='JohnDoe')) # 出力: /user/JohnDoe
_external
_external=Trueを指定すると、完全なURLが生成されます。
with app.test_request_context():
print(url_for('index', _external=True)) # 出力: http://localhost/
_scheme
_schemeを使用してURLのスキームを指定することができます。通常はhttpまたはhttpsを指定します。
ith app.test_request_context():
print(url_for('index', _external=True, _scheme='https')) # 出力: https://localhost/
_anchor
_anchorを使用してURLのアンカー部分を指定できます。
with app.test_request_context():
print(url_for('index', _anchor='section')) # 出力: /#section
_method
特定のHTTPメソッドに対応するURLを生成する場合に使用します。
@app.route('/submit', methods=['POST'])
def submit():
return 'Submitted'
with app.test_request_context():
print(url_for('submit', _method='POST')) # 出力: /submit
url_forの使用例
url_for関数は、テンプレート内のURLとリダイレクト処理の際によく使われます。
それぞれの使用例をご紹介します。
テンプレート内のURL
url_forはテンプレート内でのリンクの生成によく使用されます。
<ul>
<li><a href="{{ url_for('index') }}">Home</a></li>
<li><a href="{{ url_for('profile', username='JohnDoe') }}">Profile</a></li>
</ul>
リダイレクト
リダイレクトにもurl_forを使用します。
from flask import redirect
@app.route('/old-page')
def old_page():
return redirect(url_for('new_page'))
@app.route('/new-page')
def new_page():
return 'This is the new page'
このような状況で、url_forを使います。
まとめ
今回の記事では、Flaskの主要な機能の一つであるurl_for関数の使い方について詳しく解説しました。
url_for関数の概要から、引数の使い方、よくある使用例などをご紹介しました。
url_for関数は、FlaskでWebアプリを作成するときによく使う関数なので覚えておきましょう。
ここまでお読みいただきありがとうございました。
Pythonの基礎から応用まで学べる
Python WebAcademy
Python WebAcademyでは、Pythonの基礎からアーキテクチャなどの応用的な内容まで幅広く学べます。また、ブラウザ上で直接Pythonコードを試すことができ、実践的なスキルを身につけることが可能です。

インフラの学習はInfraAcademy

おすすめの記事









