0

我是 Python Flask 的初学者。我有一个反应原生应用程序。在执行主要功能时,我想获得用户输入。我还想status在函数执行过程中动态更新状态钩子的值。

这是我所做的。

客户端设备

React.useEffect(()=>{
    //all variables and hooks have been declared in original code
    //skipping all declarations to reduce size
    fetch('http://localhost:5000/start', {
            method: 'POST',
            headers: {
                Accept: 'application/json',
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({
                session: sessionID,
                url: url,
                user: username,
                password: password,
                stuff1: stuff1,
                stuff2: stuff2
            })
      });
      return unsubscribe;
    }, [navigation]);
});
//refresh the status every 2 seconds
React.useEffect(() => {
    const interval = setInterval(() => {
        fetch('http://localhost:5000/status',{
            method: 'POST',
            headers: {
                Accept: 'application/json',
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({
                session: sessionID
            })
    }).then(res => res.json()).then((data)=>{
        setStatus(data.status);
        console.log(data.status);
        if(data.status==='Failed'){
            setStatus("Sorry, this task has failed");
            setTimeout(()=>{navigation.goBack()}, 3000)
        } 
    }).catch(()=>{
        setStatus("Either our server or this device went offline");
        //just giving user 5 secs to read the status
        setTimeout(()=>{
            setStatus("Try again...")
            navigation.goBack('Task_Elaborate');
            return;
        }, 5000)
    });
    }, 2000);
    return () => clearInterval(interval);
}, []);

服务器(运行 Flask)

#function to refresh status in client device
@app.route('/status', methods=['GET','POST'])
@cross_origin(origin='*',headers=['Content-Type','Authorization'])
def refresh_status():
  data = request.get_json()
  session['currentuser'] = data['session']
  if(stuff.status=='Failed'):
    session.pop(data['session'], None)
  return jsonify({'status':stuff.status})

#function to run for triggering main()
@app.route('/start', methods=['GET', 'POST'])
@cross_origin(origin='*',headers=['Content-Type','Authorization'])
def start_main():
  data = request.get_json()
  url = data['url']
  username = data['user']
  password = data['password']
  stuff1 = data['stuff1']
  stuff2 = data['stuff2']
  session['currentuser'] = data['session']
  stuff.main(url, username, password, stuff1, stuff2)
  return ""

运行时stuff.main(),我想获得用户输入并将其用于进一步处理。我怎样才能做到这一点?

至于状态,应用程序首先通过向服务器发出请求来启动主功能。这会触发main()in 服务器的执行。然后,应用程序每 2 秒请求一次刷新状态。这些代码片段确实有效。但我预计会有中等数量的用户,这会减慢速度。速度是这个应用程序的一个非常重要的方面,因为它主要是做什么的。另外,在这种方法中,我无法获得用户输入,这是这个问题的重要部分。

4

0 回答 0