수색…


정적 파일 사용

웹 애플리케이션은 종종 CSS 또는 JavaScript 파일과 같은 정적 파일을 필요로합니다. Flask 응용 프로그램에서 정적 파일을 사용하려면 패키지 또는 모듈 옆에 static 이라는 폴더를 만들고 응용 프로그램에서 /static 에서 사용할 수 있습니다.

템플릿을 사용하는 프로젝트 구조의 예는 다음과 같습니다.

MyApplication/
    /static/
        /style.css
        /script.js
    /templates/
        /index.html
    /app.py

app.py는 템플릿 렌더링이있는 Flask의 기본 예제입니다.

from flask import Flask, render_template

app = Flask(__name__)

@app.route('/')
def index():
    return render_template('index.html')

템플릿 index.html에서 정적 CSS 및 JavaScript 파일을 사용하려면 특별한 '정적'끝점 이름을 사용해야합니다.

{{url_for('static', filename = 'style.css')}}

따라서 index.html에 다음 이 포함될 수 있습니다.

<html>
    <head>
        <title>Static File</title>
        <link href="{{url_for('static', filename = 'style.css')}}" rel="stylesheet">
        <script src="{{url_for('static', filename = 'script.js')}}"></script>
    </head>
    <body>
        <h3>Hello World!</h3>
    </body>
</html>

app.py를 실행하면 http : // localhost : 5000 /에 웹 페이지가 표시됩니다.

프로덕션의 정적 파일 (프론트 엔드 웹 서버에서 제공)

Flask에 내장 된 웹 서버는 정적 자산을 서비스 할 수 있으며, 이는 개발에 적합합니다. 그러나 Flask 응용 프로그램을 제공하기 위해 uWSGI 또는 Gunicorn과 같은 것을 사용하는 프로덕션 배포의 경우 정적 파일을 제공하는 작업은 일반적으로 프론트 엔드 웹 서버 (Nginx, Apache 등)로 오프로드되는 작업입니다. 이것은 특히 모든 정적 자산이 하나의 폴더에있는 경우 작고 간단한 작업입니다. 그래도 큰 응용 프로그램이나 정적 자산을 제공하는 Flask 플러그인을 사용하는 경우에는 모든 파일의 위치를 ​​기억하고 하나의 디렉토리에 수동으로 복사 / 수집하기가 어려울 수 있습니다. 이 문서는 Flask-Collect 플러그인 을 사용하여 작업을 단순화하는 방법을 보여줍니다.

이 문서의 초점은 정적 자산 컬렉션에 있습니다. 이 기능을 설명하기 위해이 예제에서는 정적 애셋을 제공하는 Flask-Bootstrap 플러그인을 사용합니다. 또한 Flask-Script 플러그인을 사용합니다.이 플러그인은 명령 줄 작업을 간단하게 만드는 데 사용됩니다. 이들 플러그인 중 어느 것도이 문서에서 중요하지 않습니다. 기능을 설명하기 위해 여기서 사용하고 있습니다. Flask-Script를 사용하지 않기로 결정한 경우 Flask-Collect 문서 를 검토 하여 collect 명령을 호출하는 다른 방법을 찾아야합니다 .

또한이 정적 자산을 제공하는 프론트 엔드 웹 서버 구성은이 문서의 범위를 벗어나는 것이므로 자세한 내용은 NginxApache 를 사용하여 몇 가지 예제를 확인하십시오. 이 예에서는 Flask-Collect가 생성 할 중앙 디렉토리에 "/ static"으로 시작하는 URL의 별칭을 지정한다고 가정하면 충분합니다.

앱은 다음과 같이 구성되어 있습니다.

/manage.py - The app management script, used to run the app, and to collect static assets
/app/ - this folder contains the files that are specific to our app
    | - __init__.py - Contains the create_app function
    | - static/ - this folder contains the static files for our app.
        | css/styles.css - custom styles for our app (we will leave this file empty)
        | js/main.js - custom js for our app (we will leave this file empty)
    | - templates/index.html - a simple page that extends the Flask-Bootstrap template
  1. 먼저 가상 환경을 만들고 필수 패키지를 설치하십시오. (your-virtualenv) $ pip 설치하기 flask flask-script flask-bootstrap flask-collect

  2. 위에서 설명한 파일 구조를 설정하십시오.

    $ touch manage.py; mkdir -p app / {static / {css, js}, templates}; 앱 / { init. py, static / {css / styles.css, js / main.js}}을 터치합니다.

  3. manage.py , app/__init__.pyapp/templates/index.html 파일의 내용을 설정합니다.

# manage.py
#!/usr/bin/env python
import os
from flask_script import Manager, Server
from flask import current_app
from flask_collect import Collect
from app import create_app

class Config(object):
   # CRITICAL CONFIG VALUE: This tells Flask-Collect where to put our static files!
   # Standard practice is to use a folder named "static" that resides in the top-level of the project directory.
   # You are not bound to this location, however; you may use basically any directory that you wish.
   COLLECT_STATIC_ROOT = os.path.dirname(__file__) + '/static'
   COLLECT_STORAGE = 'flask_collect.storage.file'

app = create_app(Config)

manager = Manager(app)
manager.add_command('runserver', Server(host='127.0.0.1', port=5000))

collect = Collect()
collect.init_app(app)

@manager.command
def collect():
  """Collect static from blueprints. Workaround for issue: https://github.com/klen/Flask-Collect/issues/22"""
  return current_app.extensions['collect'].collect()

if __name__ == "__main__":
   manager.run()

# app/__init__.py
from flask import Flask, render_template
from flask_collect import Collect
from flask_bootstrap import Bootstrap

def create_app(config):
  app = Flask(__name__)
  app.config.from_object(config)

  Bootstrap(app)
  Collect(app)

  @app.route('/')
  def home():
    return render_template('index.html')

  return app

# app/templates/index.html
{% extends "bootstrap/base.html" %}
{% block title %}This is an example page{% endblock %}

{% block navbar %}
<div class="navbar navbar-fixed-top">
  <!-- ... -->
</div>
{% endblock %}

{% block content %}
  <h1>Hello, Bootstrap</h1>
{% endblock %}
  1. 해당 파일을 사용하여 이제 관리 스크립트를 사용하여 앱을 실행할 수 있습니다.
$ ./manage.py runserver # visit http://localhost:5000 to verify that the app works correctly.
  1. 이제 정적 자산을 처음으로 수집하십시오. 이렇게하기 전에 앱의 최상위 레벨에 static/ 폴더가 없어야한다는 점을 다시 한 번 지적 할 필요가 있습니다. Flask-Collect가 앱에서 수집 할 모든 정적 파일과 사용하고있는 다양한 플러그인을 배치 할 곳입니다. 당신이이있는 경우 static/ 앱의 최상위에있는 폴더를, 당신이 깨끗한 상태로 시작으로, 완전히 진행하기 전에 삭제해야 할 것은 플라스크-수집이 무엇을 이해하는 전도의 중요한 부분 /입니다. 이 지시 사항은 일상적인 사용에는 적용되지 않는다는 점에 유의하십시오. Flask-Collect가이 디렉토리를 생성하고 거기에 여러 개의 파일을 배치한다는 사실을 설명하기 만하면됩니다.

그렇게 말하면 다음 명령을 실행하여 정적 자산을 수집 할 수 있습니다.

$ ./manage.py collect

그렇게하면 Flask-Collect가 최상위 static/ 폴더를 생성했으며 다음 파일이 포함되어 있음을 확인해야합니다.

$ find ./static -type f # execute this from the top-level directory of your app, same dir that contains the manage.py script
static/bootstrap/css/bootstrap-theme.css
static/bootstrap/css/bootstrap-theme.css.map
static/bootstrap/css/bootstrap-theme.min.css
static/bootstrap/css/bootstrap.css
static/bootstrap/css/bootstrap.css.map
static/bootstrap/css/bootstrap.min.css
static/bootstrap/fonts/glyphicons-halflings-regular.eot
static/bootstrap/fonts/glyphicons-halflings-regular.svg
static/bootstrap/fonts/glyphicons-halflings-regular.ttf
static/bootstrap/fonts/glyphicons-halflings-regular.woff
static/bootstrap/fonts/glyphicons-halflings-regular.woff2
static/bootstrap/jquery.js
static/bootstrap/jquery.min.js
static/bootstrap/jquery.min.map
static/bootstrap/js/bootstrap.js
static/bootstrap/js/bootstrap.min.js
static/bootstrap/js/npm.js
static/css/styles.css
static/js/main.js

그게 전부입니다 : 앱의 CSS 나 JavaScript를 수정할 때마다 또는 정적 애셋을 제공하는 Flask 플러그인을 업데이트 한 경우 (이 예에서는 Flask-Bootstrap과 같은) collect 명령을 사용하십시오.



Modified text is an extract of the original Stack Overflow Documentation
아래 라이선스 CC BY-SA 3.0
와 제휴하지 않음 Stack Overflow