deploying a React app that uses a Flask backend
I am trying to deploy a React
app that uses a flask
backend.
I've never done this, so I would like to clarify some stuff.
Do we first have to deploy the flask
backend somewhere and make the React
frontend call that API instead of localhost
?
If so, do we have to separately deploy the frontend after doing this?
What is the brief flow of this process?
Thanks
1 answer
-
answered 2018-09-17 06:19
Kristoffer Lund
I think this goes towards preferences and common practices, but if it was up to me I would deploy the backend first and make sure the fronted works before I deploy that too. It is not very uncommon to have a separate frontend and backend team, which results in separate deploys, but this is usually coordinated so that you can do simultaneous deploy if there are breaking changes.
See also questions close to this topic
-
Storing 3rd Party OAuth Credentials (React)
I'm attempting to implement Google OAuth with the package react-google-login, but I found I had some questions after reading the docs:
ReactDOM.render( <GoogleLogin clientId="658977310896-knrl3gka66fldh83dao2rhgbblmd4un9.apps.googleusercontent.com" buttonText="Login" onSuccess={responseGoogle} onFailure={responseGoogle} />, document.getElementById('googleButton') );
In this example, provided in the usage instructions, the developer's clientId is hardcoded into the component. I'm fairly certain this should never happen, so I wanted to get some clarification as to what the best practice for storing 3rd party authentication credentials actually is.
(Not sure if this is relevant, but I wanted to add that I'll be using a rails backend. I believe I've seen an implementation in the past wherein a request is first made to the backend, where the actual oauth request is then dispatched using credentials that have been stored as environment variables in the server so that they never pass through the browser? If that makes sense?)
Any advice or clarification on this subject would be much appreciated. Thanks in advance!
-
How to connect over wifi for multiplayer Connect Four game in React?
I'm learning webdev and React by writing a simple 'Connect Four' game (https://github.com/DavidDeprost/connect4_react). It's not yet finished, but it already works fine (fully responsive with customizable gridsize, checkers and timer)! I've noticed that Create-React-App by default makes the app available on my home network, which is amazing. What I'd like to try next though is network it, so that I can access the same instance from different computers in the network, in order to play against each other (now you can only play with 2 persons on the same computer).
But I honestly have no clue on how to proceed with this, or even what to research ... Would it require node.js to just play over wifi? Something else? Is it actually simpler if I just want multiplayer over wifi, compared to fully online (with a backend), or does a (peer-to-peer?) app require pretty much the same? Would this require massive changes, or be a rather straightforward addition?
Sorry for the ton of questions, but it is mostly just to illustrate what I'm struggling with, never having done anything networked before. I'd be more than happy if someone could provide some pointers or feedback on how to proceed (or even the topic name to research on google/blogs/...). (Any general feedback, tips, or even PR's on the app itself are also very much welcome)
-
How can I retrieve search results with only one click of the search button instead of two?
I am working on a Node.js + ElasticSearch + React.js project and I have managed to get the search to work! However, I have to click the search button twice before I get back results in my console. Eventually, I would like to output the results via components to the user. any input would be great!
Here is React.js:
import React, { Component } from 'react'; import axios from 'axios'; class App extends Component { state = { result: [], name: 'Roger', userInput: null, } handleSubmit = event=> { event.preventDefault(); var input = document.getElementById("userText").value; this.setState({ userInput: input }); axios.get('http://localhost:4000/search?query=' + this.state.userInput) .then(res => { var result = res.data; this.setState({ result: result }); console.log(this.state.result); console.log(this.state.userInput); }) } render() { return ( <div className="App"> <h2>hello from react</h2> <form action="/search"> <input type="text" placeholder="Search..." name="query" id="userText"/> <button type="submit" onClick={this.handleSubmit}><i>Search</i></button> </form> </div> ); } } export default App;
here is Node.js:
const express = require('express'); const bodyParser = require('body-parser'); const morgan = require('morgan'); const JSON = require('circular-json'); const PORT = 4000; var client = require ('./connection.js'); var argv = require('yargs').argv; var getJSON = require('get-json'); const cors = require('cors'); let app = express(); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: true })); app.use(cors({ origin: 'http://localhost:3001', credentials: true })); app.get('/', function(req, res){ res.send("Node is running brother"); }); app.get("/search", function (request, response) { client.search({ index: 'club', type: 'clubinfo', body: { query: { match: { "name": query} }, } },function (error, data, status) { if (error) { return console.log(error); } else { // Send back the response response.send(data); } }); }); app.listen(PORT, () => console.log('wowzers in me trousers, Listening on port ' + PORT));
-
How do increase timeout for NGINX?
I am using Python, Flask, uWSGI and NGINX to host a web server. One of the functions involves generating a file for the user which can take up to a minute or two. On this action I keep getting a 504 timeout from NGINX. I tried to change some config variables in
/etc/nginx/nginx.conf
likekeepalive_timeout
but that didn't work.How do I increase the length of time before the request times out? Thanks for any help
-
How to use socketio.emit inside a bunch of functions of a thread
I am trying to do kind of a State Machine in Flask. When my app starts I launch a background task that begins with a function "state_0()" and sequentially jumps to other functions "state_1()" then "state_2()" and then return to "state_0()".
This s0 -> s1 -> s2 -> s0 -> s1 -> ... is constantly running from the very beginning when the web app starts and what I want to do is to "socketio.emit('refresh', state)" inside those functions so the FrontEnd can be updated accordingly.
To do this, I use a thread with @app.before_first_request that basically runs "state_0()" using application context.
The problem is that the emit only works for state_0() function.
My current code can be simplified as follows:
myapp.py
from flask import Flask, render_template, current_app from flask_socketio import SocketIO, emit import threading import time, json DATA = {'state': '0'} N = 5 # Fake pooling # initialize Flask app = Flask(__name__) socketio = SocketIO(app) def state_0(): # Update DATA global DATA DATA['state'] = '0' socketio.emit('refresh', json.dumps(DATA), broadcast=True) print("State " + DATA['state'] + "!") # Dummy pooling simulation i = 0 while i < N: print("Dummy workload " + DATA['state'] + "...") time.sleep(3) i += 1 state_1() def state_1(): # Update DATA global DATA DATA['state'] = '1' socketio.emit('refresh', json.dumps(DATA), broadcast=True) print("State " + DATA['state'] + "!") # Dummy pooling simulation i = 0 while i < N: print("Dummy workload " + DATA['state'] + "...") time.sleep(3) i += 1 print("Alarm(s) detected!") state_2() def state_2(): # Update DATA global DATA DATA['state'] = '2' socketio.emit('refresh', json.dumps(DATA), broadcast=True) print("State " + DATA['state'] + "!") # Dummy pooling simulation i = 0 while i < N: print("Dummy workload " + DATA['state'] + "...") time.sleep(3) i += 1 state_0() @app.before_first_request def activate_job(): def run_job(): with app.app_context(): state_0() thread = threading.Thread(target=run_job) thread.start() @app.route('/') def index(): return render_template('myindex.html') # Every time Client refresh the web, we broadcast the current DATA @socketio.on('connect') def on_connect(): print("[Server.on_connect]: A new connection!") emit('refresh', json.dumps(DATA), broadcast=True) if __name__ == '__main__': socketio.run(app, debug=True)
myindex.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>State Machine</title> </head> <body> <p>State machine...</p> <form action=""> <input id ="s0" type="radio" name="state0"> State 0<br> <input id ="s1" type="radio" name="state1"> State 1<br> <input id ="s2" type="radio" name="state2"> State 2<br> </form> <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.2.0/socket.io.js"></script> <script type="text/javascript" charset="utf-8"> var socket = io.connect('http://' + document.domain + ':' + location.port); // verify our websocket connection is established socket.on('connect', function () { console.log('Websocket connected!'); }); socket.on('refresh', function (DATA) { var DATA = JSON.parse(DATA); console.log('[refresh] Frontend has updated info! Now we are in state ' + DATA.state); console.log('[refresh] All variables are:'); console.log(DATA); switch (DATA.state) { case '0': document.getElementById('s2').checked = "" document.getElementById('s0').checked = "checked" break; case '1': document.getElementById('s0').checked = "" document.getElementById('s1').checked = "checked" break; case '2': document.getElementById('s1').checked = "" document.getElementById('s2').checked = "checked" break; default: // code block } }); </script> </body> </html>
I have also tried to do this:
@app.before_first_request def activate_job(): def run_job(): with app.app_context(): state_0() # this function emits to frontend! state_1() # but this function does not emit nothing thread = threading.Thread(target=run_job) thread.start()
I have tried to use with app.app_context() here and there but only works with state_0() function.
I hope my question is clear. Note that I want to keep things as simple as possible (this is why I am using global variable to keep state and why I don't use Celery to run background tasks). This is not for production.
Hope somebody may provide help!
Note: To test this example in ubuntu, create a "virtualenv env", and then "pip3 install flask flask-socketio eventlet" and run "python3 myapp.py"
-
Possible ways to display real time sensor data on web page using python
I am trying to make web application which takes temperature and (motor)RPM from sensors coming through my computer which connected serially to a mechanical machine and display it on web page.
I am using Python Flask with AJAX. What I've tried so far now is took jsonify data from back-end and displayed on html page. But I am not getting or seeing any real time data changing on web page without reloading the page. I need to reload the page every time to see data changing.
How can I and what are the possible ways to get this data displayed on web page.
This is my python script for flask app:
from flask import Flask, render_template, request, jsonify import random import time import serial app = Flask(__name__) @app.route('/') def hello_world(): return render_template("index.html") @app.route('/ret_num', methods = ['POST', 'GET']) def ret_num(): s = serial.Serial('COM7') res = s.read() time.sleep(1) return jsonify(res) if __name__ == '__main__': app.run(debug = True)
And HTML code:
<html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <body> <script> $(function(){ $.ajax({ url: '/ret_num', type: 'POST', success: function(response) { console.log(response); $("#num").html(response); }, error: function(error) { console.log(error); } }); }); </script> <h1>Output</h1> <h1 id="num"></h1> </body> </head> </html>