This is the sixth day of my participation in Gwen Challenge.
This tutorial will guide you through creating a simple, yet fully functional React-Flask project.
Front rely on
Please follow the instructions to install the three packages before continuing with the tutorial.
- Node.js: JavaScript runtime that will be used to run front-end projects.
- Yarn: package manager of node.js.
- Python: Run the Flask backend.
Create the React project
We use the Create React App generator to Create a simple project.
$ npx create-react-app react-flask-app
$ cd react-flask-app
Copy the code
Create the Flask API back end
We want to combine the front end and back end into one project, so go to the project directory and add an API directory where the Flask project will be implemented.
$ cd react-flask-app
$ mkdir api
$ cd api
Copy the code
In order not to depend on and affect the global package, we create a virtual environment called _venv _ and run Python in it.
$ python3 -m venv venv
$ source venv/bin/activate
(venv) $ _
Copy the code
For this simple example, I only need two Python packages, Flask and Python-Dotenv.
(venv) $ pip install flask python-dotenv
Copy the code
In the spirit of keeping things simple, we’ll create a small, single file and single endpoint application. In the API directory, create a single file app.py:
# api/app.py
import time
from flask import Flask
app = Flask(__name__)
@app.route('/time')
def get_current_time() :
return {'time': time.time()}
Copy the code
The API responds to the corresponding URL as JSON, and when accessing /time, it may return the following.
{"time": 1624328277.5134633}Copy the code
It turns out that we don’t see function calls from Flask because in recent versions of Flask, the view function returns a dictionary, which is automatically JSON by Flask.
Flask imports the application from the location indicated by the environment variable. If python-dotenv is installed, running flask sets up environment variables according to the configuration in.env and.flaskenv. This avoids manually setting FLASK_APP and other similar service deployments using environment variables after each terminal is opened. Here we create a.flaskenv file and write the environment variables.
# api/.flaskenv
FLASK_APP=app.py
FLASK_ENV=development
Copy the code
You can now start the Flask application.
(venv) $ flask run
* Serving Flask app 'app.py'(lazy loading) * Environment: development * Debug mode: http://127.0.0.1:5000/ (Press CTRL+C to quit) * Restarterstat
* Debugger is active!
* Debugger PIN: 541-013-389
Copy the code
Visit http://127.0.0.1:5000/time can see our API has been effective. Now that the Flask part of the project is complete, let’s leave the _api _ subdirectory and go back to the root directory.
(venv) $ cd.Copy the code
React Configuration Change
Some changes need to be made in the package.json file to improve the integration between React and Flask.
Set the agent
The first change is to set up agent redirection from React to Flask. The React project runs a Web server on port 3000, while Flask runs its own server on port 5000. However, in most deployments, front-end files and API endpoints come from the same domain and port to avoid cross-domain issues and make everything work seamlessly. The React project can be configured to redirect any requests it receives on its port 3000 to other servers. To do this, we modify the package.json file to add the following line.
// package.json{... Other content..."proxy": "http://localhost:5000"
}
Copy the code
Sets the front and back end start commands
To make it easier to manage flask startup with YARN, add the following line to scripts.
// package.json{... Other content..."scripts": {
"start": "react-scripts start"."start-api": "cd api && venv/bin/flask run --no-debugger". Other content... }}Copy the code
Running joint projects
Now let’s run the application. You need to use two terminal Windows, one for the front-end server and one for the back-end server. On the first terminal, start the front end:
$ yarn start
Copy the code
This will take a few seconds, and then the browser window will open to load the React sample application from http://localhost:3000_. Switch to the second terminal and start the Flask backend at http://localhost:5000 _ :
$ yarn start-api
Copy the code
Now both the front end and the back end are running, and the front end will redirect any requests it doesn’t recognize to the back end. Both monitor their source code files and restart after changes.
Call the Flask API from React
Now we have the API defined by the Flask side displayed in the React project, changing the SRC /app.js file.
// src/app.js
import React, { useState, useEffect } from 'react';
import logo from './logo.svg';
import './App.css';
function App() {
const [currentTime, setCurrentTime] = useState(0);
useEffect(async() = > {const response = await fetch('/time');
if(! response.ok) {throw new Error(response.status);
}
const res = response.json();
res.then(data= >setCurrentTime(data.time)); } []);return (
<div className="App">
<header className="App-header">{/ *... Other content... * /}<p>Current Time: {currentTime}</p>
</header>
</div>
);
}
export default App;
Copy the code
Now open your browser and you will see that the current Unix time is displayed successfully.
conclusion
Now we know how to create a project that combines React and Flask.