Flask

[Flask] url_for, render_template를 이용해 이미지 출력하기

땅콩새싹 2020. 9. 24. 18:05
반응형

url_for, render_template를 이용해 이미지 출력하기

 


 

기본 경로 입니다.

 

1
2
3
4
5
6
7
8
9
10
from flask import Flask, url_for
from flask import render_template
app = Flask(__name__)
 
@app.route('/showImg')
def showImg():
    return render_template('showImg.html')
 
if __name__ == '__main__' :
    app.run(host = '0.0.0.0', port = 80, debug = True)

<app.py>

기본이 되는 app.py입니다.

우선 'showImg()'함수부터 실행해 보겠습니다. 'showImg()'함수를 실행하게 되면

templates폴더 안에 있는 'showImg.html'을 실행하게 됩니다.

 

1
2
3
4
5
<html>
   <body>
      <img src="{{url_for('static', filename = '/img/hi.png')}}">
   </body>
</html>

<showImg.html>

실행되는 showImg.html입니다.

위에 올린 파일들 경로를 참고해서 보면 static이라는 폴더 안에

img라는 폴더가 있고 img폴더 안에 hi.png라는 그림파일이 있습니다.

url_for에 경로를 입력시켜 그림파일을 불러오고 'showImg()' 함수로 return 했습니다.

 

'showImg()'함수 리턴 화면

 

반응형