python/Flask

Flask image render

blackbearwow 2022. 4. 28. 23:52

Flask로 이미지를 렌더시키려 한 시도가 한두번이 아니다...(멘탈이 한두번 나간적이 아니다)

그때마다 모두 실패...

하지만 오늘 드디어 방법을 알아내고 성공했으니 블로그에 글을 적는다.

 

구글에 flask image render를 치면 html에 url_for를 이용하여 지정하는 것 밖에 안나온다.

하지만 내가 원하는 것은 <img>태그나 직접 주소에 이미지 주소를 쳐도, javascript var img=new Image(); img.src='car.jpg'; 를 하여도 로드되는 이미지를 원하는 것이다.

 

해당방법은 구글링을 하다가 stackoverflow에서 찾게되었다. 사실 저번에도 구글링 해서 stackoverflow에 해당 글을 읽었을 수 도 있지만 영어를 이해하지 못해서 실패했던 건가? 흠....

 

해당 방법은 다음과 같다

return send_from_directory("templates/image/bazzi", "inWaterBalloon1.png")

send_from_directory함수를 이용하면 되는것이다.

함수의 공식 문서: https://flask.palletsprojects.com/en/2.1.x/api/?highlight=send_from_directory#flask.send_from_directory 

 

API — Flask Documentation (2.1.x)

rv (Union[Response, str, bytes, Dict[str, Any], Iterator[str], Iterator[bytes], Tuple[Union[Response, str, bytes, Dict[str, Any], Iterator[str], Iterator[bytes]], Union[Headers, Dict[str, Union[str, List[str], Tuple[str, ...]]], List[Tuple[str, Union[str,

flask.palletsprojects.com

함수를 찾게된 stack overflow의 글: https://stackoverflow.com/questions/20646822/how-to-serve-static-files-in-flask

 

How to serve static files in Flask

So this is embarrassing. I've got an application that I threw together in Flask and for now it is just serving up a single static HTML page with some links to CSS and JS. And I can't find where in ...

stackoverflow.com