본문으로 바로가기

[웹크롤링 개인프로젝트#3] Flask - url_for()

category 2019/1월 2018. 12. 22. 20:21

url_for()

flask 함수인 url_for()에 대해서 공부해보았다

route()은 인자로 설정해둔 주소로 들어오면 route 밑에 있는 함수가 실행되는 반면 url_for()은 함수를 찾아 실행한다.


@app.route('/')
def main_get():
return redirect('index')

@app.route('/index')
def test():
return "test 함수"

@app.route('/test')
def index():
return "index 함수"

index 페이지로 들어오면 test() 실행 하는 코드와 

test 페이지로 들어오면 index()를 실행하는 코드를 작성하고 테스트를 진행하였다.



redirect는 index페이지로 이동할 것이고 route('/index')를 타고 test()함수로 들어갔다.


@app.route('/')
def main_get():
return redirect(url_for('index'))

@app.route('/index')
def test():
return "test 함수"

@app.route('/test')
def index():
return "index 함수"

redirect에 url_for을 추가 시키면 url_for에 의해 index 페이지가 아닌 index함수를 찾을것이고 "index 함수" 문자를 리턴 한다


또한 url_for은 웹 페이지에서 파일들을 임포트 시킬때도 사용할 수 있다.


<link href="{{ url_for('static',filename='bootstrap.min.css')}}" rel="stylesheet">