React中Axios刷新页面时无法更新Django后端数据求助
问题:Django后端数据更新后,React页面刷新无法获取新数据,仅重启服务器生效
页面刷新时Axios仅获取首次数据,后端数据更新后必须重启服务器才能拿到新值,已尝试多种Stack Overflow方案但无效。
相关代码
React组件代码
import axios from "axios"; import React, { useState, useEffect } from "react"; import StatBox from "../components/StatBox"; function Bucketsize() { const [data, setData] = useState({size: '', unit: ''}); const fetchDevices = async () => { try { const res = await axios.post("http://127.0.0.1:8000/bucketsize/", {}); const size = res.data.size; const unit = res.data.unit; setData({ size, unit }); } catch(err) { console.error(err); } }; useEffect(() => { fetchDevices(); }, []); return ( <StatBox data={data.size} size={data.unit} heading="Bucket Size" /> ); } export default Bucketsize;
Django视图代码(views.py)
class Bucketsize(APIView): from django.views.decorators.csrf import csrf_exempt from rest_framework import status import json @staticmethod @csrf_exempt def post(request): from .awsdata.generalstats.bucketsize import bucket_size size, unit = bucket_size() return Response({"size": size, "unit": unit})
AWS数据获取代码
import boto3 # from .credentials.credential import bucketname def get_bucket_size(bucket_name): s3 = boto3.client('s3') paginator = s3.get_paginator('list_objects_v2') size = 0 for page in paginator.paginate(Bucket=bucket_name): for obj in page.get('Contents', []): size += obj['Size'] return size bucket_name = 'bucket_name' size = get_bucket_size(bucket_name) # Determine the appropriate unit based on the size units = ['bytes', 'KB', 'MB', 'GB', 'TB'] unit_index = 0 while size >= 1024 and unit_index < len(units) - 1: size /= 1024 unit_index += 1 # Format the size with two decimal places bucketsize = '{:.2f}'.format(size) def bucket_size(): unit = units[unit_index] return bucketsize, unit # a,b = bucket_size() # print(a,b)
注:后端Python脚本从AWS Timestream获取数据,每次执行需5-10秒。曾尝试使用异步函数获取数据,但问题依旧。
问题根源
Python模块级变量会在服务器启动时仅执行一次,你的AWS数据代码中,size = get_bucket_size(bucket_name)、unit_index、bucketsize都是模块级变量,服务器启动后就固定了值,后续调用bucket_size()只是返回缓存的旧数据,不会重新请求AWS获取新值。
解决方案
1. 重构AWS数据获取函数
把所有计算逻辑移到bucket_size()内部,确保每次调用都重新请求并计算:
import boto3 def get_bucket_size(bucket_name): s3 = boto3.client('s3') paginator = s3.get_paginator('list_objects_v2') size = 0 for page in paginator.paginate(Bucket=bucket_name): for obj in page.get('Contents', []): size += obj['Size'] return size def bucket_size(): bucket_name = 'bucket_name' size = get_bucket_size(bucket_name) # 重新计算单位和格式化 units = ['bytes', 'KB', 'MB', 'GB', 'TB'] unit_index = 0 while size >= 1024 and unit_index < len(units) - 1: size /= 1024 unit_index += 1 bucketsize = '{:.2f}'.format(size) unit = units[unit_index] return bucketsize, unit
2. 优化React请求避免浏览器缓存
给Axios请求添加时间戳参数,防止浏览器缓存旧响应:
const fetchDevices = async () => { try { // 加时间戳参数避免缓存 const res = await axios.post("http://127.0.0.1:8000/bucketsize/", {}, { params: { t: Date.now() } }); const size = res.data.size; const unit = res.data.unit; setData({ size, unit }); } catch(err) { console.error(err); } };
3. 规范Django视图代码
将导入移到文件顶部,避免每次请求重复导入模块:
from django.views.decorators.csrf import csrf_exempt from rest_framework import status from rest_framework.views import APIView from rest_framework.response import Response from .awsdata.generalstats.bucketsize import bucket_size class Bucketsize(APIView): @staticmethod @csrf_exempt def post(request): size, unit = bucket_size() return Response({"size": size, "unit": unit})
内容的提问来源于stack exchange,提问作者Suprava
相关产品推荐
相关产品推荐

