在Flask中处理嵌套目录通常涉及到路由的设计和静态文件的组织。以下是一些基础概念和相关信息:
@app.route()
来定义路由。/static
目录来存放这些文件。/app/routes.py
, /app/templates/index.html
, /app/static/css/style.css
/app/modules/user/routes.py
, /app/modules/user/templates/profile.html
, /app/modules/user/static/css/user.css
# app.py
from flask import Flask, render_template
app = Flask(__name__)
@app.route('/')
def index():
return render_template('index.html')
if __name__ == '__main__':
app.run(debug=True)
<!-- app/templates/index.html -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Home</title>
<link rel="stylesheet" href="{{ url_for('static', filename='css/style.css') }}">
</head>
<body>
<h1>Welcome to the Home Page</h1>
</body>
</html>
/* app/static/css/style.css */
body {
background-color: #f0f0f0;
}
# app/modules/user/routes.py
from flask import Blueprint, render_template
user_bp = Blueprint('user', __name__, template_folder='templates', static_folder='static')
@user_bp.route('/profile')
def profile():
return render_template('profile.html')
# app.py
from flask import Flask
from app.modules.user.routes import user_bp
app = Flask(__name__)
app.register_blueprint(user_bp, url_prefix='/user')
if __name__ == '__main__':
app.run(debug=True)
<!-- app/modules/user/templates/profile.html -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Profile</title>
<link rel="stylesheet" href="{{ url_for('user.static', filename='css/user.css') }}">
</head>
<body>
<h1>User Profile</h1>
</body>
</html>
/* app/modules/user/static/css/user.css */
.profile-container {
background-color: #e0e0e0;
}
url_for()
正确引用静态文件。<link rel="stylesheet" href="{{ url_for('static', filename='css/style.css') }}">
app.register_blueprint(user_bp, url_prefix='/user')
通过以上方法,可以有效地处理Flask中的嵌套目录,提高应用的可维护性和扩展性。
领取专属 10元无门槛券
手把手带您无忧上云