我将如何使用 Flask 提供这个 html 文件(不是模板)
How would I serve this html file with Flask (nota a template)
我正在使用 apidoc 生成文档网站。在 运行 上,它会创建一个名为 doc 的文件夹,其中包含一个 index.html 文件以及随附的 css 和 js.
我希望能够使用 Flask 服务器为该文件夹提供服务,但不知道该怎么做。
我的文件夹结构是这样的
-root
--- doc/ #contains all of the static stuff
--- server.py
我已经试过了,但无法正常工作:
app = Flask(__name__, static_url_path="/doc")
@app.route('/')
def root():
return app.send_from_directory('index.html')
其中一个问题是 apidoc 生成的 index.html 中引用的所有静态文件都与该页面相关,因此 /js/etc。不起作用,因为它实际上是 /doc/js...
如果有人能帮助我解决这里的语法问题,那就太好了。谢谢
我在代码中发现了三个问题。
a) 您不需要使用 static_url_path
,因为 send_from_directory
独立于它
b) 当我尝试 运行 上面的代码,然后转到 /
,我得到一个 AttributeError: 'Flask' object has no attribute 'send_from_directory'
- 这意味着转换为 app.send_from_directory
是错误的 - 你需要从 flask 导入这个函数,即 from flask import send_from_directory
c) 然后当我尝试 运行 你的代码时,我得到一个 TypeError: send_from_directory() missing 1 required positional argument: 'filename'
,这意味着 send_from_directory
需要另一个参数;它需要一个目录和一个文件
把这些放在一起你会得到这样的东西:
from flask import Flask
from flask import send_from_directory
app = Flask(__name__)
@app.route("/")
def index():
return send_from_directory("doc", "index.html")
作为外卖(对我自己):
阅读文档有很大帮助 (https://flask.palletsprojects.com/en/1.1.x/api/)
仔细查看 - 起初很可怕 - 错误消息可以很好地提示该怎么做
我正在使用 apidoc 生成文档网站。在 运行 上,它会创建一个名为 doc 的文件夹,其中包含一个 index.html 文件以及随附的 css 和 js.
我希望能够使用 Flask 服务器为该文件夹提供服务,但不知道该怎么做。
我的文件夹结构是这样的
-root
--- doc/ #contains all of the static stuff
--- server.py
我已经试过了,但无法正常工作:
app = Flask(__name__, static_url_path="/doc")
@app.route('/')
def root():
return app.send_from_directory('index.html')
其中一个问题是 apidoc 生成的 index.html 中引用的所有静态文件都与该页面相关,因此 /js/etc。不起作用,因为它实际上是 /doc/js...
如果有人能帮助我解决这里的语法问题,那就太好了。谢谢
我在代码中发现了三个问题。
a) 您不需要使用 static_url_path
,因为 send_from_directory
独立于它
b) 当我尝试 运行 上面的代码,然后转到 /
,我得到一个 AttributeError: 'Flask' object has no attribute 'send_from_directory'
- 这意味着转换为 app.send_from_directory
是错误的 - 你需要从 flask 导入这个函数,即 from flask import send_from_directory
c) 然后当我尝试 运行 你的代码时,我得到一个 TypeError: send_from_directory() missing 1 required positional argument: 'filename'
,这意味着 send_from_directory
需要另一个参数;它需要一个目录和一个文件
把这些放在一起你会得到这样的东西:
from flask import Flask
from flask import send_from_directory
app = Flask(__name__)
@app.route("/")
def index():
return send_from_directory("doc", "index.html")
作为外卖(对我自己):
阅读文档有很大帮助 (https://flask.palletsprojects.com/en/1.1.x/api/)
仔细查看 - 起初很可怕 - 错误消息可以很好地提示该怎么做