본문 바로가기
파이썬

파이썬 플라스크에서 동적 URL을 생성하는 방법은 무엇입니까?

by º기록 2020. 11. 10.
반응형

다음과 같이 URL을 구성하려는 데이터베이스에 여러 레코드가 있습니다.

mysite.com/post/todays-post-will-be-about

todays-post-will-be-about 은 데이터베이스에서 가져옵니다.

플라스크에서 이걸 뺄 수있는 방법이 있나요?

 

해결 방법

 

views.py 함수에 변수 이름을 넣을 수 있습니다. 예를 들면 :

# you can also use a particular data type such as int,str
# @app.route('post/<int:id>', methods=['GET', 'POST'])
@app.route('post/<variable>', methods=['GET'])
def daily_post(variable):
    #do your code here
    return render_template("template.html",para1=meter1, para2=meter2)

사이트에 표시 할 데이터베이스 정보를 얻으려면 매개 변수를 템플릿에 전달해야합니다. 따라서 템플릿에서 다음과 같은 매개 변수를 참조합니다.

<td>Post Author: {{ para1.author }}</td>
<td>Post Body: {{ para1.body }}</td>
<td>Date Posted: [{{ para2 }}] times</td>

그런 다음 mysite.com/post/anything_here를 방문하면 'anything_here'가 함수로 이동하여 필요에 따라 평가됩니다. 누군가가 수동으로 게시물을 입력하려고하는 경우에 대비하여 404 페이지 처리를 설정하는 것이 좋습니다.

@app.errorhandler(404)
def not_found_error(error):
    return render_template('404.html', pic=pic), 404

 

참조 페이지 https://stackoverflow.com/questions/35107885

 

 

반응형

댓글