Python 在Flask中使用根路径参数

Python 在Flask中使用根路径参数,python,flask,Python,Flask,我试着遵循一个教程,该教程旨在演示如何更改静态和模板文件夹在根目录中的位置。然而,我无法让这个例子起作用。应用程序运行正常,但在查找样式表“GET/static/style.css HTTP/1.1”404时返回404。因此,它似乎可以找到模板,但找不到样式表 下面是我的hello world示例。 我应该使用根路径还是实例路径、模板文件夹和静态文件夹 api_files static style.css templates index.html api.py api.

我试着遵循一个教程,该教程旨在演示如何更改静态和模板文件夹在根目录中的位置。然而,我无法让这个例子起作用。应用程序运行正常,但在查找样式表“GET/static/style.css HTTP/1.1”404时返回404。因此,它似乎可以找到模板,但找不到样式表

下面是我的hello world示例。 我应该使用根路径还是实例路径、模板文件夹和静态文件夹

api_files
  static
    style.css
  templates
    index.html
api.py
api.py 从flask导入flask,为

# here we can set a different root path
app = Flask(__name__, root_path='api_files/')

@app.route('/')
def index():
    """Render home page."""
    return render_template('index.html')  # we can render templates as usual

if __name__ == '__main__':
    app.run(debug=True)
index.html

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8"/>
    <link rel= "stylesheet" type= "text/css" href= {{ url_for('static', filename='style.css') }}>
</head>
<body>
  hello world
</body>
</html>

我正是在遵循这本教程的过程中遇到了同样的问题。是正确的--您已将绝对路径传递给
根路径
。如果不这样做,
模板
将起作用,但
静态内容肯定不会起作用

我的文件如下所示:

# │   hello.py
# │
# └───web-content
#     ├───static
#     │       style.css
#     │
#     └───templates
#             welcome.html
hello.py
现在看起来像:

import os
from flask import Flask, render_template

# important - pass an absolute path to root_path
app = Flask(__name__, root_path=os.path.join(os.getcwd(), 'web-content'))

@app.route('/page/<string:page_name>')
def render_static(page_name):
    return render_template(f'{page_name}.html')

if __name__ == "__main__":
    app.run()
导入操作系统
从烧瓶导入烧瓶,渲染\u模板
#重要信息-将绝对路径传递给根路径
app=Flask(\uuuuu name\uuuuuu,root\u path=os.path.join(os.getcwd(),'webcontent'))
@app.route(“/page/”)
def render_static(页面名称):
返回render_模板(f'{page_name}.html')
如果名称=“\uuuuu main\uuuuuuuu”:
app.run()

您是否收到某种错误消息?是的,当它查找样式表时,我收到了404。我已将问题更新为包含此内容。请改为尝试这一行?:static\u url\u path='api\u files/static')@gittert添加该行会生成以下错误:ValueError:url必须以斜杠开头。如果我添加了一个前导斜杠static\u url\u path='/api\u files/static',那么应用程序运行时样式表仍然是404。关于它应该如何工作的解释可以在这里找到:这个答案值得更多关注,感谢您清楚地解决了我的问题。
import os
from flask import Flask, render_template

# important - pass an absolute path to root_path
app = Flask(__name__, root_path=os.path.join(os.getcwd(), 'web-content'))

@app.route('/page/<string:page_name>')
def render_static(page_name):
    return render_template(f'{page_name}.html')

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