I am a beginner to Python's Flask. I have a react native app. Amidst executing the main function, I want to get a user input. I also want to update the value of a status
state hook dynamically amidst the function execution.
Here is what I have did.
Client device
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);
}, []);
Server (running 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 ""
When stuff.main()
runs, I want to get a user input and use that for further processing. How can I do that?
As for the status, the app first starts off the main function by making a request to the server. This triggers the execution of the main()
in server. Then, the app makes requests for refreshing the status every 2 seconds. These code snippets do work. But I expect a medium-high crowd of users and this will slow it down. Speed is a very important aspect of this app due to what it is doing mainly. Also, in this method, I can't get the user input, which is the essential part of this question.