Python Flask从root静态文件夹而不是blueprint的静态文件夹提供静态文件

Avi*_*Das 3 python flask

我有一个蓝图定义为:

auth_login = Blueprint('auth_login', __name__, template_folder='templates', static_folder='static', static_url_path='/static')
Run Code Online (Sandbox Code Playgroud)

我将其注册为:

app.register_blueprint(auth_login, url_prefix='/user')
Run Code Online (Sandbox Code Playgroud)

我有一条路线:

@auth_login.route('/<username>/')
def profile(username):
return render_template('profile/user.html',
username = username)
Run Code Online (Sandbox Code Playgroud)

使用此设置,/ user/endpoint永远不会像我一样设置加载静态文件,

"GET /user//static/css/lib/bootstrap.min.css HTTP/1.1"404 - "GET /user//static/css/lib/font-awesome/css/font-awesome.min.css HTTP/1.1"404 -

我真正想要的是查看根应用程序的静态文件夹而不是蓝图,所以我希望它请求

"GET /static/css/lib/bootstrap.min.css HTTP/1.1"200 -

是否可以通过static_folder或static_url_path配置它,以便路由将在根目录中查找静态文件,而不是相对于蓝图的安装位置?

Sea*_*ira 5

默认情况下,Flask会设置/staticURL以提供文件{application_root}/static- 您将使用蓝图代码覆盖该默认值.(URL仍然/static是文件夹{application_root}/path/to/blueprint/static,根据事物的声音,它不是你想要的).

只需删除初始化的static_folderstatic_url参数,BlueprintURL就可以正常工作(假设您的{application_root}/static文件夹中有适当的CSS .)

  • @AviDas - 确保你至少使用静态引用的路径绝对URL:`<link href ="static/css/some.css>`是路径相对的,而`<link href ="/ static/css /some.css>`是path-absolute(注意前导`/`).更好的是,使用`{{url_for('static',filename ='/ your/file.name')}}`所以如果你将应用程序安装在不是URL根目录的地方,一切都会正常工作*. (2认同)