redux 第一次学习Python Flask,我在连接React前端和Flask API时遇到了麻烦

xytpbqjk  于 11个月前  发布在  Python
关注(0)|答案(1)|浏览(165)

我目前第一次学习flask,用它做了一个简单的API。我用React JS写了我的前端,我为我的投资组合网站做了一个简单的访问者计数器。
我现在得到的错误是这样的:

“类型错误:total_visitors()接受0个位置参数,但给出了2个视图函数未返回有效的响应。返回类型必须是字符串、dict、列表、具有头或状态的元组、响应示例或WSGI可调用,但它是一个函数。"

下面是我的React“home”组件,它有一个问题:

import { useState, useEffect } from "react";
import { BsGithub } from "react-icons/bs";
import { BsLinkedin } from "react-icons/bs";
import { Link } from "react-scroll";
import { FaMedium } from "react-icons/fa6";
import Clock from "./clock";
import { useSelector, useDispatch } from "react-redux";
import MyPic from "../images/mypic.jpg";
import { fetchVisitors, incrementVisitor } from "../features/counter/counterSlice";

export default function Home() {
  // const visitorCount = useSelector((state) => state.counter.value);
  const dispatch = useDispatch();
  

  useEffect(() => {
  
    dispatch(incrementVisitor()).then((action)=>{
      dispatch(fetchVisitors(action.payload))
    })
    
  }, []);

  return (
    <div className="home-component" name="home">
      <div className="hero min-h-screen bg-base-600">
        <div className="hero-content text-center">
          <div className="max-w-md">
            <h1 className="text-5xl font-bold m-5">Hello there!</h1>
            <img
              src={MyPic}
              alt="me"
              className="w-20 rounded-full m-auto"
            ></img>

            <p className="py-6 text-lg">My name is Yoonsung Kim.</p>

            <div className="link-container">
              <nav className="flex">
                <a
                  href="https://github.com/jeffkim1118"
                  target="_blank"
                  rel="noreferrer"
                  className="m-auto hover:animate-bounce"
                >
                  <BsGithub className="text-4xl m-auto" />
                  Github
                </a>

                <a
                  href="https://www.linkedin.com/in/yoonsung-kim-639b30178/"
                  target="_blank"
                  rel="noreferrer"
                  className="m-auto hover:animate-bounce"
                >
                  <BsLinkedin className="text-4xl m-auto" />
                  Linkedin
                </a>

                <a
                  href="https://medium.com/@1019yskim"
                  target="_blank"
                  rel="noreferrer"
                  className="m-auto hover:animate-bounce"
                >
                  <FaMedium className="text-4xl m-auto" />
                  Medium
                </a>
              </nav>
            </div>

            <div className="stats shadow m-3">
              <div className="stat">
                <Clock />
                <div className="stat-title">Total Page Views</div>
                <div className="stat-value" data-testid="hitcounter">
                  1000
                </div>
              </div>
            </div>
            <br />

            <Link
              className="btn btn-primary"
              to="about"
              smooth={true}
              duration={600}
            >
              Get Started
            </Link>
          </div>
        </div>
      </div>
    </div>
  );
}

字符串
我使用react-redux进行状态管理,我想在redux中发出所有API请求。下面是我的counterSlice.js文件:

import { createSlice, createAsyncThunk } from '@reduxjs/toolkit';

export const fetchVisitors = createAsyncThunk('fetchVisitors', async(values, thunkAPI) => {
    await fetch('http://localhost:5000/visitor')
    .then((res) => {res.json()})
    .then((data) => {return data})
    .catch((error) => {
        return thunkAPI.rejectWithValue(error.value);
    });
    
});

export const incrementVisitor = createAsyncThunk('incrementVisitor', async(values, thunkAPI) => {
    await fetch('http://localhost:5000/visitor', {
        method:"POST",
        headers: {'Content-Type': 'application/json'},
        body:JSON.stringify({value:values})
    })
    .then((res) => res.json())
    .then((data) => {return data})
    .catch((error) => {
        return thunkAPI.rejectWithValue(error.message);
    })
})

const counterSlice = createSlice({
    name: 'visitor-counter',
    initialState: {
        value: 0,
    },
    
    reducers:{
        increment:(state, action) => {
            state.value = action.payload;
        },
        getVisitors: (state,action) => {
            state.value = action.payload
        }
    },
    extraReducers: (builder) => {
        builder
        .addCase(fetchVisitors.fulfilled,(state,action) => {
            state.value = action.payload;
        })
        .addCase(incrementVisitor.fulfilled, (state,action) => {
            state.value = action.payload + 1;
        })
    }
    
})
export const { increment, getVisitors } = counterSlice.actions;
export default counterSlice.reducer


这是我的 flask api.py:

import time
from flask import Flask, jsonify, request
from flask_cors import CORS, cross_origin

app = Flask(__name__)
cors = CORS(app)
app.config['CORS_HEADERS'] = 'Content-Type'

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

total_visitors = {
    'counter':0
}

@app.route('/')
def hello_world():
    return "<p>Hello, world</p>"

@app.route('/time')
def get_current_time():
    return {'time': time.time()}

@app.route('/visitor', methods=['GET', 'POST'])
@cross_origin()
def total_visitors():
    global total_visitors
    if request.method == "POST":
        total_visitors.counter+=1
        return total_visitors
    elif request.method == 'GET':
        return total_visitors


我想确保我得到了总访问者的数量,并使用来自我的redux的get和post请求来增加总访问者的数量,以在我的React前端中显示它。我可能在代码中犯了很多错误,所以,请帮助。

tf7tbtn2

tf7tbtn21#

你的错误说:
返回类型必须是字符串、dict、列表、带有头或状态的元组、响应示例或WSGI可调用,但它是一个函数。
你已经声明了一个与你的方法名同名的变量,当你输入return total_visitors时,返回的是函数而不是变量。把你的变量名改为别的。

相关问题