development

url_for ()를 사용하여 Flask에서 동적 URL 만들기

big-blog 2020. 6. 11. 07:49
반응형

url_for ()를 사용하여 Flask에서 동적 URL 만들기


내 플라스크 노선의 절반은 변수 말을 필요로 /<variable>/add하거나 /<variable>/remove. 해당 위치에 대한 링크를 작성하는 방법

url_for() 함수가 전달할 인수를 하나만 사용하지만 인수를 추가 할 수 없습니까?


변수에 키워드 인수가 필요합니다.

url_for('add', variable=foo)

url_forin Flask는 템플릿을 포함하여 응용 프로그램 전체에서 URL을 변경해야하는 오버 헤드를 방지하기 위해 URL을 만드는 데 사용됩니다. 이 없으면 url_for앱의 루트 URL에 변경이있는 경우 링크가있는 모든 페이지에서 변경해야합니다.

통사론: url_for('name of the function of the route','parameters (if required)')

다음과 같이 사용할 수 있습니다.

@app.route('/index')
@app.route('/')
def index():
    return 'you are in the index page'

이제 색인 페이지에 링크가 있으면 다음을 사용할 수 있습니다.

<a href={{ url_for('index') }}>Index</a>

예를 들어 다음과 같이 많은 일을 할 수 있습니다.

@app.route('/questions/<int:question_id>'):    #int has been used as a filter that only integer will be passed in the url otherwise it will give a 404 error
def find_question(question_id):  
    return ('you asked for question{0}'.format(question_id))

위의 경우 다음을 사용할 수 있습니다.

<a href = {{ url_for('find_question' ,question_id=1) }}>Question 1</a>

이와 같이 간단하게 매개 변수를 전달할 수 있습니다!


Flask API 문서를 참조하십시오flask.url_for()

js 또는 css를 템플릿에 연결하는 데 사용되는 다른 샘플 스 니펫은 다음과 같습니다.

<script src="{{ url_for('static', filename='jquery.min.js') }}"></script>

<link rel=stylesheet type=text/css href="{{ url_for('static', filename='style.css') }}">

참고 URL : https://stackoverflow.com/questions/7478366/create-dynamic-urls-in-flask-with-url-for

반응형