You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python简易HTTP服务器:如何避免两端返回304状态码?

解决本地Python HTTP服务器JSON缓存(304响应)问题

针对你遇到的浏览器因304缓存停止请求JSON的问题,以下是两种可行的具体实现方案:

方案一:修改Python服务器,强制返回200响应并禁用缓存

默认的Python http.server会根据文件修改时间返回304(未修改),我们可以自定义请求处理器,强制返回200并添加禁止缓存的响应头,让浏览器每次都重新请求文件。

  1. 在你的项目目录下创建custom_server.py文件,内容如下:
from http.server import HTTPServer, SimpleHTTPRequestHandler

class NoCacheHandler(SimpleHTTPRequestHandler):
    def send_response_only(self, code, message=None):
        # 强制替换304为200响应
        super().send_response_only(200, message)
    
    def end_headers(self):
        # 发送禁止缓存的响应头,彻底避免浏览器缓存
        self.send_header('Cache-Control', 'no-cache, no-store, must-revalidate')
        self.send_header('Pragma', 'no-cache')
        self.send_header('Expires', '0')
        super().end_headers()

if __name__ == '__main__':
    server_address = ('', 8000)
    httpd = HTTPServer(server_address, NoCacheHandler)
    print('服务器运行在 http://localhost:8000')
    httpd.serve_forever()
  1. 在命令行进入项目目录,运行python custom_server.py启动服务器,之后浏览器每次请求JSON都会收到200响应,不会再触发缓存。

方案二:让JSON文件持续更新,避免304响应

通过每秒修改JSON文件的内容(比如添加时间戳),让服务器检测到文件变化,从而返回200响应。

  1. 创建update_json.py脚本(假设你的JSON文件名为data.json):
import json
import time

while True:
    try:
        # 读取并更新JSON内容
        with open('data.json', 'r+') as f:
            data = json.load(f)
            data['timestamp'] = int(time.time())  # 添加时间戳字段
            f.seek(0)
            json.dump(data, f, indent=2)
            f.truncate()
    except FileNotFoundError:
        # 文件不存在时创建初始内容
        with open('data.json', 'w') as f:
            json.dump({'timestamp': int(time.time())}, f, indent=2)
    time.sleep(1)  # 每秒更新一次
  1. 同时启动两个进程:
    • 第一个进程运行python update_json.py,持续更新JSON文件
    • 第二个进程运行默认的Python服务器:python -m http.server 8000

这样每次浏览器请求时,服务器会检测到文件已修改,返回200和最新的JSON内容。

内容的提问来源于stack exchange,提问作者Zyst

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.27 15:08:10