티스토리 뷰

IT/Flask

[Flask] 정적 파일 (Static file)

Dragonz 2019. 4. 18. 12:52
반응형

 

Jinja2 에서는 render_template() 함수를 이용하여 html 파일을 렌더링 할 수 있다. 패키지 경로 또는 모듈이 위치한 경로에 templates 디렉토리를 만들고 그곳에 html 파일을 생성하기만 하면 된다. 정적 파일 (Static file) 도 이와 유사한 방식으로 사용할 수 있다. 패키지 경로 또는 모듈이 위치한 경로에 static 디렉토리를 만들고, 그곳에 css 나 자바스크립트와 같은 static file 을  위치시키면 된다.

 

파일명 : 7_static_files.py

from flask import Flask, render_template
app = Flask(__name__)

@app.route("/")
def index():
    # 7_static_files.html 을 렌더링한다.
    return render_template("7_static_files.html")

if __name__ == '__main__':
    app.run(debug = True)

 

파일명 : 7_ static_files.html

<html>
    <head>
        <script type = "text/javascript"
            src = "{{ url_for('static', filename = 'hello.js') }}" ></script>
    </head>
    <body>
        <input type = "button" onclick = "sayHello()" value = "Say Hello" />
    </body>
</html>

 

파일명 : hello.js

 function sayHello() {
     alert("Hello world")
 }

 

각각의 파일은 아래와 같은 경로에 위치하게 된다.

Project
   - Flask
      - 7_static_files.py
      - templates
         - 7_static_files.html
      - static
         - hello.js

 

웹브라우저를 이용하여 "http://127.0.0.1:5000" 으로 이동하면 7_static_files.html 파일의 내용이 렌더링된다.  html 파일의 내용은 간단하다. Say Hello 라는 이름의 버튼이 하나 있고, 버튼을 클릭하면 sayHello() 함수를 호출한다. 이 함수는 자바스크립트 파일에 구현되어 있으며 js 파일은 static 디렉토리에 위치해있다.

 

 

버튼을 클릭하면 sayHello() 함수가 호출되고, alert 팝업창이 뜬다.

 

 

 

반응형
댓글
공지사항