Flaskで別サイトにリダイレクト(flask.redirect)する
Flaskで別のサイトにリダイレクトをするには、flask.redirectを利用する。
redirect('https://www.○○○')
とすると、redirect関数の中で指定したサイトにリダイレクトする。
では、以下に具体例を記述する。
Example
- views.pyの定義
app = Flask(__name__)
@app.route('/redirect')
def redirect_func():
return redirect('https://www.google.com') # Googleにリダイレクトする
if __name__ == '__main__':
app.run()
- http://127.0.0.1:5000/redirectに遷移する(Googleに遷移されて、表示される)
- アクセスログ(ログ上には、ステータスコード302(redirect)が表示される)
上で見たようにステータスコード302になるが、これを変更することができる。
- ステータスコードを200にする
app = Flask(__name__)
@app.route('/redirect')
def redirect_func():
return redirect('https://www.google.com', code=200) # ステータスコードを200に変更する
if __name__ == '__main__':
app.run()
url_forを用いて特定の関数に遷移する。
flask.url_for, flask.redirectを用いると、自分の作成した関数に遷移する。
以下のように記述する。
redirect(url_for('add', variable=foo))
Example
- 別の関数に遷移
app = Flask(__name__)
@app.route('/use')
def user():
return render_template('user.html')
@app.route('/redirect')
def redirect_func():
return redirect(url_for('user'))# user関数に遷移する。
- 別の関数に遷移(引数のある関数)
app = Flask(__name__)
@app.route('/idx/
def index(msg):
return render_template('index.html', msg=msg)
@app.route('/redirect')
def redirect_func():
return redirect(url_for('index', msg='hello'))# index関数に引数msgをhelloとして遷移する。