gpt4 book ai didi

python - 使用来自不同目录的 Flask 提供单个 index.html

转载 作者:太空宇宙 更新时间:2023-11-04 04:25:46 26 4
gpt4 key购买 nike

我目前的文件夹结构如下:

/
--client
----dist
------index.html
------index.js
--server
----server.py

dist/ 中的 index.js 服务于 React 应用程序。我的 server.py 看起来像这样:

import os
from flask import Flask, send_from_directory
app = Flask(__name__)

@app.route('/')
def hello_world():
return send_from_directory('../client/dist/', 'index.html')

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

不幸的是,这没有用,我得到了一个Failed to load resource。我查看了关于 SO 及其他关于此的几篇文章。它们中的大多数都非常陈旧(也许已经过时),并且它们通常都具有不同的文件夹结构,其中 index.html 文件是从 static 文件夹中提供的 server/ 或类似的东西。

我真的只是想做我认为应该是一件容易的事:当 localhost:5000 被访问时,Flask 服务于 ../client/dist/index.html 从那里 React 接管并做它的事情。

如果有人能为我提供实现目标的最小/干净方法,我将不胜感激。

最佳答案

事实证明我有点错了。我以为这个问题不是转贴,但经过更多搜索后,我发现了另一个与我非常相似的 StackOverflow 问题:

Serving static html file from another directory from flask restful endpoint

将那里和其他地方的几个答案放在一起,我有一个最小的工作解决方案:

from flask import Flask, send_from_directory
app = Flask(__name__, static_folder='../client/dist')

@app.route('/')
def hello_world():
return send_from_directory(app.static_folder, 'index.html')

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

当我现在访问 localhost:5000 时,我得到了 index.html 的内容。

关于python - 使用来自不同目录的 Flask 提供单个 index.html,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53535970/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com