Zoeken…


Statische bestanden gebruiken

Webtoepassingen vereisen vaak statische bestanden zoals CSS- of JavaScript-bestanden. Als u statische bestanden in een Flask-toepassing wilt gebruiken, maakt u een map met de naam static in uw pakket of naast uw module. Deze is beschikbaar op /static in de toepassing.

Een voorbeeld van een projectstructuur voor het gebruik van sjablonen is als volgt:

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

app.py is een basisvoorbeeld van Flask met sjabloonweergave.

from flask import Flask, render_template

app = Flask(__name__)

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

Om het statische CSS- en JavaScript-bestand in de sjabloon index.html te gebruiken, moeten we de speciale 'statische' eindpuntnaam gebruiken:

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

Index.html kan dus het volgende bevatten:

<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>

Na het uitvoeren van app.py zien we de webpagina in http: // localhost: 5000 / .

Statische bestanden in productie (geleverd door frontend webserver)

De ingebouwde webserver van Flask kan statische activa bedienen en dit werkt prima voor de ontwikkeling. Voor productie-implementaties die bijvoorbeeld UWSGI of Gunicorn gebruiken om de Flask-toepassing te bedienen, is het uitvoeren van statische bestanden een taak die meestal wordt overgebracht naar de frontend-webserver (Nginx, Apache, enz.). Dit is een kleine / gemakkelijke taak met kleinere apps, vooral als alle statische elementen zich in één map bevinden; voor grotere apps echter, en / of degenen die Flask-plug-ins gebruiken die statische activa bieden, kan het moeilijk worden om de locaties van al die bestanden te onthouden en ze handmatig naar één map te kopiëren / verzamelen. Dit document laat zien hoe u de Flask-Collect-plug- in gebruikt om die taak te vereenvoudigen.

Merk op dat de focus van deze documentatie ligt op het verzamelen van statische activa. Om deze functionaliteit te illustreren, gebruikt dit voorbeeld de Flask-Bootstrap-plug-in, een plug-in die statische activa biedt. Het maakt ook gebruik van de Flask-Script-plug-in, die wordt gebruikt om het maken van opdrachtregelopdrachten te vereenvoudigen. Geen van deze plug-ins zijn cruciaal voor dit document, ze worden hier alleen gebruikt om de functionaliteit te demonstreren. Als u ervoor kiest om Flask-Script niet te gebruiken, wilt u de Flask-Collect-documenten bekijken voor alternatieve manieren om de opdracht collect te roepen .

Merk ook op dat de configuratie van uw frontend webserver om deze statische activa te bedienen buiten het bereik van dit document valt, u wilt enkele voorbeelden bekijken met Nginx en Apache voor meer info. Het volstaat te zeggen dat u URL's die beginnen met "/ static" naar de gecentraliseerde map die Flask-Collect voor u in dit voorbeeld maakt, aliasing.

De app is als volgt gestructureerd:

/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. Maak eerst uw virtuele omgeving en installeer de vereiste pakketten: (uw-virtualenv) $ pip install flask flask-script flask-bootstrap flask-collect

  2. Breng de hierboven beschreven bestandsstructuur tot stand:

    $ touch manage.py; mkdir -p app / {static / {css, js}, templates}; touch app / { init .py, static / {css / styles.css, js / main.js}}

  3. Bepaal de inhoud voor de manage.py , app/__init__.py en app/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. Als deze bestanden aanwezig zijn, kunt u nu het beheerscript gebruiken om de app uit te voeren:
$ ./manage.py runserver # visit http://localhost:5000 to verify that the app works correctly.
  1. Nu, om uw statische activa voor het eerst te verzamelen. Voordat u dit doet, is het vermeldenswaard dat u GEEN static/ map static/ map op het hoogste niveau van uw app moet hebben; dit is waar Flask-Collect alle statische bestanden gaat plaatsen die het gaat verzamelen van uw app en de verschillende plug-ins die u mogelijk gebruikt. Als je wel een static/ map op het hoogste niveau van uw app, moet u het verwijderen volledig alvorens verder te gaan, als te beginnen met een schone lei is een cruciaal onderdeel van het getuigen / begrijpen wat Kolf-Collect doet. Merk op dat deze instructie niet van toepassing is op het dagelijkse gebruik, het is gewoon om het feit te illustreren dat Flask-Collect deze map voor u gaat maken en vervolgens een aantal bestanden daarin plaatst.

Dat gezegd hebbende, kunt u de volgende opdracht uitvoeren om uw statische activa te verzamelen:

$ ./manage.py collect

Nadat u dit hebt gedaan, zou u moeten zien dat Flask-Collect deze static/ map static/ map op het hoogste niveau heeft gemaakt en deze de volgende bestanden bevat:

$ 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

En dat is het: gebruik de opdracht collect wanneer u de CSS of JavaScript van uw app bewerkt of wanneer u een Flask-plug-in hebt bijgewerkt die statische elementen biedt (zoals Flask-Bootstrap in dit voorbeeld).



Modified text is an extract of the original Stack Overflow Documentation
Licentie onder CC BY-SA 3.0
Niet aangesloten bij Stack Overflow