Dev/Flask

Python Flask url_for()

nolzaheo 2021. 7. 22. 10:33
728x90

url을 다른 url로 리다이렉트 할 때 사용한다. 따라서 url을 동적으로 처리하는데 유용하다.

기본적으로 `url_for`함수는 엔드포인트 함수명을 인자로 받는다. 따라서 이동하고자 하는 라우트의 함수 이름을 url_for() 내에 적어줘야한다. 

@app.route('/index')
def index():
    return render_template('index.html', posts=posts)
 <a href="{{ url_for('index') }}">Flask 블로그</a>

이 때 인자 전달도 가능하다.

@app.route('/guest/<guest>')
def hello(guest):
	return 'guest name :%s' % guest
redirect(url_for('hello', guest=name))

 

또한 `url_for`함수로 `static` 폴더 내에 있는 리소스의 주소를 생성할 수도 있는데, 이는 `url_for('static', filename=<파일 이름>>)`를 이용한다.

 

🔗 공식문서

 

API — Flask 0.11-dev documentation

bool. True if able to load config, False otherwise.

flask-docs-kr.readthedocs.io

 

728x90

'Dev > Flask' 카테고리의 다른 글

Python Flask Routing  (0) 2021.07.21