본문으로 바로가기

 

 

리다이렉트와 에러

 

 

Quickstart — Flask Documentation (1.1.x)

For web applications it’s crucial to react to the data a client sends to the server. In Flask this information is provided by the global request object. If you have some experience with Python you might be wondering how that object can be global and how

flask.palletsprojects.com

 

리다이렉트 또는 없는 페이지에 대한 에러 처리는 다음 문서에서 참고합니다.

 

 

지난 포스팅까지 두 개의 페이지를 만들었었는데요.

from flask import Flask, render_template

app = Flask(__name__)

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

@app.route('/review')
def review():
    return render_template('review.html')

if __name__ == '__main__':
    app.run(debug=True)

 

 

없는 페이지에 접근을 시도하면 404 Not Found 에러가 발생합니다.

 

 

 

위 예제의 에러처리 코드를 추가하고, 에러 페이지(page_not_found.html) 을 생성합니다.

from flask import Flask, render_template

app = Flask(__name__)

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

@app.route('/review')
def review():
    return render_template('review.html')

@app.errorhandler(404)
def page_not_found(error):
    return render_template('page_not_found.html'), 404

if __name__ == '__main__':
    app.run(debug=True)
{% extends 'base.html' %}

{% block title %} 페이지를 찾을 수 없습니다. {% endblock %}
{% block desc %} 다음에 다시 시도하여 주시기 바랍니다. {% endblock %}

 

 

 

리다이렉트로 처리해보겠습니다.

redirect(), url_for() 함수를 사용하구요. 메인 페이지에 라우트(/index)를 추가해주었습니다.

from flask import Flask, render_template, redirect, url_for

app = Flask(__name__)

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

@app.route('/review')
def review():
    return render_template('review.html')

# @app.errorhandler(404)
# def page_not_found(error):
#     return render_template('page_not_found.html'), 404

@app.errorhandler(404)
def page_not_found(error):
    return redirect(url_for('index'))

if __name__ == '__main__':
    app.run(debug=True)

 

디버그 모드에서 302 코드를 확인할 수 있습니다.

302 는 리다이렉트을 의미합니다.

127.0.0.1 - - [29/Jul/2020 13:08:18] "GET / HTTP/1.1" 200 -
127.0.0.1 - - [29/Jul/2020 13:08:24] "GET /sdafffsfds HTTP/1.1" 302 -
127.0.0.1 - - [29/Jul/2020 13:08:24] "GET /index HTTP/1.1" 200 -