python - 如何从 Flask 提供 create-react-app 服务?

标签 python flask

如何通过 Flask 提供 create-react-app 的可交付成果?

npm run build之后,这大致是我的文件夹树:

src/
├── service/
│   └── app.py
└── content/
    ├── static
    │   ├── css
    │   │   └── many css files...
    │   ├── js
    │   │   └── many js files...
    │   └── media
    │       └── some images...
    ├── index.html
    ├── service-worker.js
    └── manifest.json

这是服务器的代码:

app = Flask(__name__, template_folder='../content', static_folder='../content')

@app.route('/')
def home():
    return flask.render_template('index.html')

@app.route('/static/<path:path>')
def static_files(path):
    return flask.send_from_directory('../content/static', path)

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

主 html index.html 已成功提供。 content/static/ 下的所有文件也是如此。

但是,content/ 下的文件(index.html 除外)根本没有传送(错误 404,未找到)。

最佳答案

假设您只是想提供一堆静态文件,那么使用像 nginx 这样的网络服务器可能会更有效地完成这一任务。

但是,如果您确实希望使用 Flask,使用现有目录结构执行此操作的最简单方法是:

from flask import Flask, render_template

app = Flask(__name__,
            static_url_path='', 
            static_folder='../content')

@app.route('/')
def index_redir():
    # Reached if the user hits example.com/ instead of example.com/index.html
    return render_template('index.html')

这本质上是在 / 端点静态地提供 contents/ 目录中的所有内容(由于 static_url_path 设置为空字符串)

当然,还有 index_redir 函数,如果用户实际点击 example.com/ 而不是 ,它将呈现 index.html >example.com/index.html.

这也避免了在代码中定义 static_files 函数,因为 Flask 具有开箱即用的静态文件服务功能。

同样,这个东西可能更适合生产环境中的 nginx

关于python - 如何从 Flask 提供 create-react-app 服务?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59756456/

相关文章:

python - 我想将 pandas DataFrame 中的两列相乘并将结果添加到新列中

python - 从 angularjs 加载 REST 资源时等待时间非常长

python - Flask 登录@login_required 不工作

python - 创建简单的 flask 错误应用程序来记录异常

python - 使用 uWSGI 部署时如何使用 getpass 向 Flask 应用程序提供输入?

python - 迭代两个列表并返回索引

python - 上传文件时显示微调器 Django 和 Ajax

python-2.7: 在类的 setter 方法中忽略了 doctests

python - 如何在pytest中每次测试后完全拆卸Flask App?

python - 传入 session 时 Tensorflow Multiprocessing pickle rlock 错误