我确信还有其他方法可以实现这一点,但一种方法是使用蓝图结构并在蓝图文件夹中包含该特定蓝图的所有静态文件。
app
|- collections
| - blueprint_one
| - configs
| - static
| - css
| - js
| js_file_one.js
| - templates
| - blueprint_one
| html_file_one.html
| blue_print_one_view_file_one.py
| __init__.py
| - blueprint_two
| - blueprint_three
|- static
| - js
| - css
|- templates
__init__.py
上面的文件夹结构不仅可以让您分离出静态文件,还可以分离出 Flask 视图文件。
以下是激活/导入文件的示例:
1) 应用程序/init.py
app = Flask(__name__, static_folder='static')
app.config.from_pyfile('app_config.py')
# Do all your db set up and etcs..
# Import blueprints below set ups to prevent circular import
app.collections.blueprint_one import blueprint_one
app.collections.blueprint_two import blueprint_two
# Now register blueprints that you've imported
app.register_blueprint(blueprint_one, url_prefix='/blueprint_one')
app.register_blueprint(blueprint_two, url_prefix='/blueprint_two')
2) blueprint_one/init.py
# Create a blueprint
from flask import Blueprint
blueprint_one = Blueprint('blueprint_one_name', __name__, template_folder='templates', static_folder='static')
# Import required views to use
from . import blue_print_one_view_file_one.py
3) blueprint_one/blue_print_one_view_file_one.py
# Import blueprint
from app.collections.blueprint_one import blueprint_one
# Any view functions using above blueprint
@blueprint_one.route('/login/, methods=['GET'])
def login():
return render_template('blueprint_one/html_file_one.html')
4) blueprint_one/templates/blueprint_one/html_file_one.html
// Note: instead of .static, you can use blueprint_one.static.
<script type="text/javascript" src="{{ url_for('.static', filename = 'js/js_file_one.js') }}"></script>
5) app/static 和 app/templates 仍然可以像您当前使用的一样使用。
这个方案并没有解决js和html放在同一个文件夹的问题,但至少你可以将每个特性分成像蓝图这样的组件,让项目结构更加模块化。