Home Python Python Flask and React

Python Flask and React

Modern online applications are frequently created using a server-side language that serves data via an API and a front-end JavaScript framework that presents the data to the end-user easy-to-use. Python is a dynamic programming language that is widely used by businesses and professionals. The language’s core ideals indicate that software should be readable and straightforward, allowing developers to be more productive and happier.

We are going to develop a basic web application using the small but powerful JavaScript UI framework ReactJS. In the back-end, we will use Python 3 and the Flask framework.

Flask will also be used to help you quickly create a REST API. On the other hand, React is a declarative, fast, and flexible JavaScript toolkit for building user interfaces developed at Facebook. It enables rich, interactive, and stateful user interfaces from small, isolated code fragments known as components.

It establishes a build system, a code transpiler to translate current syntax to code readable by all browsers. A base directory structure used to be a complicated multi-step process when starting a new React project. Creating a React App now includes all of the JavaScript packages you’ll need to operate a React project, such as code transpilation, basic linting, testing, and build systems.

It also comes with a server with hot reloading, which refreshes your page as you change the code. Finally, it will establish a framework for your directories and components, allowing you to hop right in and begin working in minutes.

Python Flask and React

Put another way. You won’t need to bother setting up a build system like Webpack. You don’t need to use Babel to make your code cross-browser compatible. You won’t have to worry about most of the modern front-end development’s sophisticated systems. In a couple of minutes of preparation, you can begin developing React code.

Prerequisites

Before beginning the actual development, we will first install the requirements. These include:

1) Python

Ensure that Python 3 is installed. Then you can verify the version of Python you have installed by running the following command:

tuts@codeunderscored:~ python –version

Do a fresh installation if Python 3 does not already exist. On Debian Linux, e.g., Ubuntu, you can follow the following procedure.

Step 1: Updating and refreshing repository Lists

To get started, open a terminal window by pressing Ctrl +Alt + T and type the following:

tuts@codeunderscored:~ sudo apt update

Step 2: Installing Supporting Software

By allowing you to add PPA (Personal Package Archive) repositories to your package management, the software-properties-common package gives you more control over your package manager. Install the required software using the following command:

tuts@codeunderscored:~ sudo apt install software-properties-common

Step 3: Install the Deadsnakes PPA

Deadsnakes is a PPA that contains newer Ubuntu releases than the default repositories. Enter the following to add the PPA:

tuts@codeunderscored:~ sudo add-apt-repository ppa:deadsnakes/ppa

To continue, the system will prompt you to press enter. Allow it to finish after you’ve done so. Refresh the list of packages by running the following command.

tuts@codeunderscored:~ sudo apt update

Step 4: Download and install Python 3

The installation of Python 3.8 can now be started using the command:

tuts@codeunderscored:~ sudo apt install python3.8

Allow the operation to finish and check that the Python version was successfully installed:

tuts@codeunderscored:~ python –version

If you are using the Windows operating system, go to the official page for Python and download the latest distribution of Python supported by your operating system. Then run the executable file following the instructions given in the installation wizard.

2) virtualenv

Virtualenv is responsible for creating a virtual environment for running our Python-Flask application. Using a virtual environment can control our application’s kind of Python version without interfering with other applications. Run the following command.

tuts@codeunderscored:~ sudo apt-get install virtualenv
installing virtualenv
installing virtualenv

3) pip

Pip is a package management system that makes installing and managing Python-based software packages like those found in the Python Package Index (PyPI). Pip isn’t installed by default in Ubuntu 18.04, but it’s a simple setup process. This demo teaches you how to use the apt package manager to install Python Pip on Ubuntu. We’ll also go through the fundamentals of using pip to install and manage Python packages.

tuts@codeunderscored:~ sudo apt install python3-pip
pytho3-pip installation
pytho3-pip installation

To verify a successful installation of pip, run the following command.

tuts@codeunderscored:~ pip3 –version
pip3 --version
pip3 –version

4) npm

Node.js is a cross-platform open-source JavaScript run-time environment that allows JavaScript code to be executed on the server. It implies you can run JavaScript code as a standalone application on your PC, independent of any web browser. Node.js is primarily used to create server-side back-end applications, but it is also widely utilized as a full-stack and front-end solution.

The world’s largest software registry and the default package manager for Node.js is Npm.

Run the following curl command as a user with sudo access to enable the NodeSource repository:

tuts@codeunderscored:~ sudo curl -sL https://deb.nodesource.com/setup_12.x | sudo -E bash -

The program will install all necessary packages, create an apt sources repository file, and refresh the apt-cache after adding the NodeSource signing key to your system.

If you prefer to install a varied version, such as 14.x, replace setup_12.x with setup_14.x. Then, install Node.js and npm after the NodeSource repository is enabled by typing:

tuts@codeunderscored:~ sudo apt install nodejs
install nodejs
install nodejs

Both the node and npm binaries are included in the nodejs package. Print the versions of Node.js and npm to ensure that they were successfully installed by running the following commands:

tuts@codeunderscored:~ node –version
tuts@codeunderscored:~ npm --version
node –version
node –version
npm --version
npm –version

Back-end with Flask

REST is an abbreviation for Representational State Transfer. Rest adheres to a set of rules designed to make system communication easier. This article lists all of the necessary parts for a production-ready Python rest API with an example project. The REST API responds with resources, JSON, an HTML document, or something else entirely.

It is vital to install the necessary Python packages ahead of time, depending on your needs. First, we will setup up a virtual environment for our application before installing the required libraries. Using a virtual environment is highly recommended because each virtual environment has its Python binary. It must match the binary version used to generate it and have its own Python packages installed in its site folders. To make a new python virtual environment called flaskvenv (you can call it whatever you want —replace the flaskvenv in the command below with your venv name), run the following command.

tuts@codeunderscored:~ virtualenv flaskenv
creating a virtualenv called flaskenv
creating a virtualenv called flaskenv

Then we can proceed to activate the virtual environment by running the following command.

tuts@codeunderscored:~ source flaskenv/bin/activate
activate virtual environment
activate virtual environment

We will then add the requirements for this application in a file we are calling requirements.txt as follows.

#requirements.txt

Flask
flask-restful
flask_cors
api

To install requirements on our virtual environment, we will run the following commands.

tuts@codeunderscored:~ pip install -r requirements.txt
installing dependencies from requirements.txt
installing dependencies from requirements.txt

We’ll begin by setting up the back-end flask first. There are various ways to structure your project. For instance, the Procfile must be exposed in the root directory if you intend to deploy on Heroku afterward. In our case, we will make a file called app.py in your root directory. We will also create an additional file called CodeunderscoredApiHandler.py in the root directory.

Add the following code to app.py

# app.py
from flask import Flask, send_from_directory
from flask_restful import Api, Resource, reqparse
from flask_cors import CORS
from CodeunderscoredApiHandler import HelloCodeunderscored

app = Flask(__name__, static_url_path='', static_folder='frontend/build')
CORS(app) 

api = Api(app)

@app.route("/", defaults={'path':''})
def serve(path):
    return send_from_directory(app.static_folder,'index.html')

api.add_resource(HelloCodeunderscored, '/api/codeunderscored')

Let’s keep things simple and make a CodeunderscoredApiHandler API that allows you to retrieve a greeting message with a Get request. Our main goal is to respond from our Flask REST APIs with Python on a react front-end application.

Also, add the following code to CodeunderscoredApiHandler.py

# CodeunderscoredApiHandler.py

from flask_restful import Api, Resource, reqparse

class HelloCodeunderscored(Resource):
  def get(self):
    return {
      'status': 'SUCCESS',
      'message': "Welcome to Codeunderscored-React from Flask"
      }

Finally, we have to run the Flask application by running the following command.

tuts@codeunderscored:~ flask run

When it is successful, you will get the following output indicating that the flask application is running OK.

running flask application
running flask application

To verify that we can use GET to fetch the data, we will append /api/codeunderscored to the parent HTTP shown above on the browser. If it is successful, we will get the following output.

Welcome to Codeunderscored-React from Flask
Welcome to Codeunderscored-React from Flask

The goal of this article is to display this message using a front-end application. In this case, we are using React. The subsequent section will walk us through creating a React application and finally display the message, “Welcome to Codeunderscored-React from Flask,” on the React application.

Front-end (React)

What is React?

React isn’t a framework; it’s a library. It takes your tech stack literally, unlike client-side MVC frameworks like Backbone, Ember, and AngularJS, so you can easily incorporate it into a new or legacy codebase. It’s frequently used to manage & select portions of an application’s user interface rather than the complete user interface.

The user interface (the ‘V’ in MVC) is built by a hierarchy of modular view Components that combine static markup with dynamic JavaScript. If you’re familiar with Angular, you’ll recognize these Components as Directives. Components employ JSX, which is an XML-like syntax that compiles to vanilla JavaScript.

Because Components are defined hierarchically, there is no need to re-render the whole DOM. Instead, it employs a Virtual DOM that only re-renders individual Components when the state changes, and it does so at breakneck speed!

Next, we’ll make a frontend folder in the project directory flask-react for our react application. Thus, our project is dubbed “frontend.”

There are various approaches to combining React with Flask in a project. However, because the project structure is significantly more complex than the back-end, we prefer to start with the back-end before covering the front-end. For this example, we created a simple React project using the create-react-app generator as follows.

tuts@codeunderscored:~ npx create-react-app . 

Or

tuts@codeunderscored:~ npx create-react-app frontend

The difference between the two is that the first will create the React app in the current directory. In contrast, a directory called frontend will be created in the current directory to house the React application in the second option.

Node.js includes the npx command. It’s a simple project runner that, if the requested command isn’t already accessible and in the system’s PATH, downloads it. The command to run is the first argument. The name of the project to create is the second input. When this command is finished, you’ll be left with a frontend directory containing a completely functional simple react project.

Because you’ll be working on this project for the foreseeable future, change your current directory to frontend. The top-level structure of the directory should look something like this when you list it:

tuts@codeunderscored:~ ls -a
top level structure of a React app
top-level structure of a React app

React Code to fetch data from Flask Application

Add the following code to app.js, which is under src/used to fetch data from the Flask-backend application.

import logo from './logo.svg';
import './App.css';
import React, { useEffect, useState } from 'react';
import axios from 'axios'

function App() {
  const [getMessage, setGetMessage] = useState({})

  useEffect(()=>{
    axios.get('http://127.0.0.1:5000/api/codeunderscored').then(response => {
      console.log("SUCCESS", response)
      setGetMessage(response)
    }).catch(error => {
      console.log(error)
    })
  }, [])
  return (
    <div className="App">
      <header className="App-header">
        <img src={logo} className="App-logo" alt="logo" />
        <p>React + Flask Tutorial</p>
        <div>{getMessage.status === 200 ? 
          <h3>{getMessage.data.message}</h3>
          :
          <h3>LOADING</h3>}</div>
      </header>
    </div>
  );
}

export default App;

In this code, we use a GET method to fetch data from the Flask route /api/codeunderscored and display it on the front-end application, as shown below

<h3>{getMessage.data.message}</h3>

when the request is successful.

Structure of react-flask-app

node_modules/

All of the external JavaScript libraries utilized by the application are located in node_modules/. Therefore, it’s unlikely that you’ll ever need to use it.

public/
Some basic HTML, JSON, and image files can be found in the public/ directory. It is where your project begins. Later, you’ll have the chance to delve deeper into them.

src/
The React JavaScript code for your project is located in the src/ directory. As shown above, that directory will house the majority of your work, like our core code to fetch data from the back-end application.

.gitignore

The node_modules directory, for example, is listed in the .gitignore file as a default directory and file that git—your source control—will ignore. Larger folders or log files that aren’t needed in source control are frequently overlooked. It will also have specific directories that you will create using React scripts.

README.md

README.md is a markdown file that offers a wealth of information about Create React App, including a command summary and links to advanced settings. For the time being, it’s advisable to leave the README.md file alone. Then, you can make the necessary changes to the existing default content to suit your project, preferably with more extensive information about your project as your project proceeds.

package-lock.json

Your package manager uses the last two files. You installed the additional dependencies as well as the base project when you ran the initial npx command. You created a package-lock.json file when you installed the dependencies. npm uses this file to ensure that the packages are the same version. Thus, you can be assured that your project’s dependencies are similar if someone else downloads it. You will rarely change this file directly because it is made automatically.

package.json

Package.json is the final file. This section contains information about your project’s title, version number, and dependencies. There are additional scripts included that you can use to run your project.

In your favorite text editor, open the package.json file:

tuts@codeunderscored:~ vim package.json
contents of package.json
contents of package.json

You’ll see a JSON object with all the metadata when you open the file. There are four different scripts in the scripts object: start, build, test, and eject.

These scripts are ranked from most important to least important. The first script creates a local development environment, which you’ll see in the next step. After that, your project will be built using the second script.

Test Script

The test script is one of those unique scripts that doesn’t need the run keyword but still works if you do. This script will launch the Jest test runner. The test runner searches your project for files ending in .spec.js or .test.js, then executes those files.

Type the following command to run the test script:

tuts@codeunderscored:~ npm test

The output of the test suite will appear in your terminal once you run this script, and the terminal prompt will disappear. It will resemble the following:

test script image
test script image

Several things are of great concern and worth monitoring. First, as previously stated, it recognizes any files having test extensions, such as .test.js and .spec.js. There is only one test suite in this case—only one.test.js file—and that test suite comprises only one test. Second, jest can discover tests in the hierarchy of your code. Thus, you can nest tests in a directory, and Jest will find them.

Second, Jest doesn’t just run your tests once and then go. It instead continues to execute in the terminal. It will restart the tests if you make any modifications to the source code.

You can also use one of the keyboard settings to limit which tests you run. For example, if you type o, the tests will only be run on changed files. As your test suites develop, this can save you a lot of time.

Finally, press the q key to exit the test runner. To reclaim your command prompt, do this right now.

Eject Script

The eject Script is a script used to remove anything from npm – eject is the final script. This script moves your project’s dependencies and configuration files into it, giving you complete control over your code and removing it from the Create React App integrated toolchain. You won’t execute this right now because you won’t be able to undo what you’ve done, and you’ll lose any future Create React App updates if you do.

The benefit of Create React App is that it eliminates the need for a substantial number of settings. Modern JavaScript applications necessitate many technologies, ranging from build systems like Webpack to compilation tools like Babel. Create React App takes care of all the configuration for you, so ejecting means you’ll have to deal with everything independently.

The disadvantage of Create React App is that you will be unable to modify the project entirely. It isn’t a problem for most projects, but you’ll need to eject the code if you ever want complete control over the build process. However, as previously said, you will not update to new versions of Create React App once you eject the code, and you will have to make any enhancements on your own manually.

Start Script

Another npm script is used to begin your project. This script, like the npm test, does not require the run command. After the script is run, a local server is launched. Successively, execute the project code, start a watcher for code changes, and open the project in a web browser.

tuts@codeunderscored:~ npm start

Before the server starts up, you’ll see some placeholder text, which will look like this:

npm start image
npm start image

If you run the script locally, the project will open in a browser window, and the attention will be shifted from the terminal to the browser. Successively, you will be able to see the following page when you open port 3000 on the browser as follows.

React fetching data from Flask-Rest Api
React fetching data from Flask-Rest API

If it doesn’t work, go to http://localhost:3000/ to observe how the site works. It’s OK if you already have another server listening on port 3000. Create React App will find the next available port and use it to run the server. If the project is operating on port 3000, this new one will begin on port 3001.

Create React App will find the next available port if 3000 is not available
Create React App will find the next available port if 3000 is not available

Even if you’re using a distant server, you’ll be able to see your site without any further configuration. http://your_server_ip:3000 will be the address. On a remote server, if you have a firewall configured, then open the concerned port.

Changes to make in React Configuration

The package.json file with the project’s configuration was left by the React project generated by the create-react-app function. This file requires a couple of adjustments to better the integration between the React and Flask sides.

Set up “proxy” redirection from React to Flask as the initial change. The React project will operate a web server on port 3000, while Flask will run its server on port 5000, as you’ll see in a moment. However, in typical deployments, the front-end files and API endpoints are all served from the same domain and port, ensuring that everything runs smoothly and without cross-origin problems.

Any queries that the React project receives on port 3000 that it does not understand are forwarded to another server. Add a proxy key to the bottom package.json to configure this.

 "scripts": {
    "start": "PORT=5000 react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },

When you’re done, don’t forget to add a comma at the end of the previous line because the file wouldn’t be a valid JSON file without it.

Yarn is used as a command manager in the React application. The yarn start command, for example, is used to start the front-end server. A yarn test and a few other controls are also included.

The commands for managing the Flask app can also be connected with yarn. However, this is entirely optional. Somewhere in the package.json’s midsection – a scripts key can be found. You can include any custom commands you want:

 "scripts": {
    "start": "react-scripts start",
    "start-api": "cd backend && venv/bin/flask run --no-debugger",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },  

We’ve added a new line named start-api to this list, which will be used to run the Flask server if you wish to run the back-end from the front-end using yarn. However, that is for your information if you want to go ahead and attempt that approach. In this demo, we will stick to using npm, and we will serve our frontend separately from the backend. The command that has to be run is the value of this key, which in this example means shifting to the back-end subdirectory and then running the flask run command.

It’s worth noting that we used the virtual environment path for the flask command to avoid activating the virtual environment. The benefit of running the command this way is that all imports will function in the context of the Flask process just like they would in a virtual environment that has been activated.

npx comes pre-installed with npm from version 5.2.0. As a result, it’s pretty much standard now. npx is a command-line utility that makes it simple to install and manage dependencies from the npm registry. In addition, it’s now effortless to launch any Node.js -based executable you’d typically install using npm. So, if you intend to run this using yarn, then from the word go, you will use yarn to create the front-end application instead of using npx as follows.

yarn create-react-app my-app

You should also note the —no-debugger option we have introduced to the command. Because this Flask back-end is solely an API server, we’ll never be serving whole pages, therefore using the browser-based debugger is pointless, as it will muck up, the JSON replies the API sends. In the terminal, you’ll see stack traces of your problems.

Conclusion

That’s all about creating a front-end application using React and a back-end application using Flask. As we mentioned before, this isn’t the only method to integrate these two frameworks. The other alternative highlighted in this article is creating a mix of React and Flask in a project and running the Flask application from the React side without activating the environment. However, the catch is doing so using yarn. But as you may already know, we used npx in this article. That limited us to run the two applications separately. You are free to test different approaches and figure out what works best for you.

Do you have a different approach? What about we see how it compares to ours in the comments section below!

You may also like

Leave a Comment

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More