如何使用 Python 缓存带有静态资产的 React 页面?

How to cache a react page with static assets using Python?

我创建了一个 Flask 应用程序,它向 https://create-react-app-example.vercel.app 发出 GET 请求并缓存反应页面。 然后从缓存中提供 HTML 页面。

烧瓶应用程序:

from flask import Flask
import requests_cache

app = Flask(__name__)
session = requests_cache.CachedSession('react_page')

@app.route("/")
def serve_react_page():    
    return session.get('https://create-react-app-example.vercel.app').text

if __name__ == '__main__':
  app.run(host='0.0.0.0', port=5000)

Flask 应用依赖项:

Flask==1.1.2
requests-cache==0.8.1

我无法缓存静态文件夹中的内容。

dineshsonachalam@macbook % python3 proxy.py
 * Serving Flask app "proxy" (lazy loading)
 * Environment: production
   WARNING: This is a development server. Do not use it in a production deployment.
   Use a production WSGI server instead.
 * Debug mode: off
 * Running on http://0.0.0.0:5000/ (Press CTRL+C to quit)
127.0.0.1 - - [28/Oct/2021 23:09:40] "GET / HTTP/1.1" 200 -
127.0.0.1 - - [28/Oct/2021 23:09:40] "GET /static/css/main.5f361e03.chunk.css HTTP/1.1" 404 -
127.0.0.1 - - [28/Oct/2021 23:09:40] "GET /static/js/2.087e98bc.chunk.js HTTP/1.1" 404 -
127.0.0.1 - - [28/Oct/2021 23:09:40] "GET /static/js/main.26bec6bc.chunk.js HTTP/1.1" 404 -
127.0.0.1 - - [28/Oct/2021 23:09:40] "GET /static/js/2.087e98bc.chunk.js HTTP/1.1" 404 -
127.0.0.1 - - [28/Oct/2021 23:09:40] "GET /static/js/main.26bec6bc.chunk.js HTTP/1.1" 404 -
127.0.0.1 - - [28/Oct/2021 23:09:40] "GET /manifest.json HTTP/1.1" 404 -

React 构建将包含用于存储 CSS、js 和图像的静态文件夹。

dineshsonachalam@macbook ui % tree build 
build
├── asset-manifest.json
├── favicon.ico
├── index.html
├── logo192.png
├── logo512.png
├── manifest.json
├── robots.txt
└── static
    ├── css
    │   ├── main.a617e044.chunk.css
    │   └── main.a617e044.chunk.css.map
    └── js
        ├── 2.d4015c87.chunk.js
        ├── 2.d4015c87.chunk.js.LICENSE.txt
        ├── 2.d4015c87.chunk.js.map
        ├── 3.b4494d53.chunk.js
        ├── 3.b4494d53.chunk.js.map
        ├── main.3dbeb9be.chunk.js
        ├── main.3dbeb9be.chunk.js.map
        ├── runtime-main.5d34aaab.js
        └── runtime-main.5d34aaab.js.map

3 directories, 18 files

有没有办法缓存静态文件夹中的内容。

serve_react_page 这里返回用户导航到该页面时会看到的内容。其中包括 /static.

中文件的链接

该页面有指向静态资产的链接,当它寻找它们时,它会向 您的 服务器询问实际的内容,例如 https://create-react-app-example.vercel.app/static/css/main.5f361e03.chunk.css.

但是浏览器想在 http://0.0.0.0:5000/static/css/main.5f361e03.chunk.css 找到它,这当然不存在。

您可以尝试在您的 Flask 应用程序中设置一个路由,任何对 /static 的请求都会从 https://create-react-app-example.vercel.app 下载文件并将其缓存到客户端。