Python-flask+react Architecture

Keywords: React JSON npm Python

flask+react

1. Setting up the Background

Install flask

pip3 install flask

Install virtualenv

Viralenv is a script for creating a virtual environment. Different projects can use their own set of environments to avoid conflicts between projects or with the local environment.
Use
pip3 install virtualenv
Then create a virtual environment
cd /var/www/WebSite
Viralenv venv # Create a virtual environment
source venv/bin/activate # Running Virtual Environment
At this point, the command prompt changes, with a prefix (venv) indicating that the current environment is a Python environment called venv.
Then install all kinds of packages normally. In venv environment, the packages installed with pip are installed in venv environment, and the system Python environment is not affected.
You can exit the current environment using the deactivate command.
In venv environment, you can use PIP3 freeze > requirements. txt to export python third-party libraries used in current venv environment.
In the process of deploying to the server, running PIP3 install-r requirements.txt on the server side can directly install the libraries required by the project.

Create background files

Create a python file hello.py as the entry file for the project

from backend import creat_app

app = creat_app()

if __name__ == "__main__":
    app.run(host='0.0.0.0', port=8080)

Then create a directory called backend as the project background.
Create a _init_.py in backend

from flask import Flask,render_template,g,session
def creat_app():
    app = Flask(__name__,template_folder="templates",static_folder="static",static_url_path="/backend/static")
    #Registration blueprint
    from . import main
    app.register_blueprint(main.main)
    app.config['SECRET_KEY'] = '...Self-generated secret key'
    app.debug = True
    db.init_app(app)
    return app

Then create templates and static directories to store rendering templates and other static files.
Create a main module
Write in its _init_.py

from flask import render_template
from flask import Blueprint
from flask import url_for

main = Blueprint('main', __name__, template_folder='templates', static_folder='static', static_url_path="/static")

@main.route('/', defaults={'path': ''})
@main.route('/<path:path>')
def index(path):
  return render_template('index.html')

At this point, the project directory is as follows

WebSite
├──hello.py
└──backend
    ├── __init__.py
    ├── main
    │   └── __init__.py
    ├── static
    └── templates

2. Building the Front Desk

1.init

When creating a React project. Create using the creat react app library provided by Facebook. This library encapsulates the basic library for packaging and development.

npm install -g create-react-app

create-react-app frontend

The directory structure after creation is as follows

frontend
├── README.md
├── node_modules
├── package.json
├── .gitignore
├── public
│   ├── favicon.ico
│   ├── index.html
│   └── manifest.json
└── src
    ├── App.css
    ├── App.js
    ├── App.test.js
    ├── index.css
    ├── index.js
    ├── logo.svg
    └── registerServiceWorker.js

Contents in package.json

{
  "name": "app",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "react": "^16.4.0",
    "react-dom": "^16.4.0",
    "react-scripts": "1.1.4"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test --env=jsdom",
    "eject": "react-scripts eject"
  }
}

It was found that there was no package tool like webpack in package.json.

In fact, webpack has been installed in node_modules, and all the packaging work is now done through scripts build. The webpack configuration file is in the react-scripts Library in node_modules. We have finished the package for us.
Many of the application libraries in package.json have been encapsulated in react-scripts libraries. If you want to view it, you can run NPM run project to restore it to package. json. But notice that the punch is irreversible. Normal conditions to help us encapsulate the program is enough for us to package debugging and normal development.

Scripts in scrips can be run through instructions in npm run +scripts.
npm run start runs a local server for debugging code.

Running the Front-end Program in Flask Background

1.build directory

npm run build creates a build directory in the front directory. Then the resources used by the react program and the packaged and compressed js and css files are put into it.

build
├── asset-manifest.json
├── favicon.ico
├── index.html
├── manifest.json
├── service-worker.js
└── static
    ├── css
    │   ├── main.c17080f1.css
    │   └── main.c17080f1.css.map
    ├── js
    │   ├── main.61911c33.js
    │   └── main.61911c33.js.map
    └── media
        └── logo.5d5d9eef.svg

In browsers, if the file name does not change, it may result in the use of local cached files instead of updating the file. The build script of react-script helps us solve this problem.
There is a string of hash values behind the files in the static directory. This value is taken as the file name by md5 of the file. This is done as long as the file changes. Hash values also change. This ensures that the document is updated. The name of the build file will also change.

2. Configure to the server

Although the build file has been generated. But the generated path is in the front directory. To run Flask in the background, you need to move the build entry file index.html to the template directory of backend. Other js, css, pictures, etc. are moved to the static directory in the backend to facilitate external access.
So we need to add some commands or scripts before and after npm run build, and move the file to the directory under backend.
After moving, the project structure is roughly as follows

WebSite
├──hello.py
├──frontend
│   └── ...
└──backend
    ├── __init__.py
    ├── main
    │   └── __init__.py
    ├── static
    │   └── build
    │       ├── asset-manifest.json
    │       ├── favicon.ico
    │       ├── manifest.json
    │       ├── service-worker.js
    │       └── static
    │           ├── css
    │           │   ├── main.c17080f1.css
    │           │   └── main.c17080f1.css.map
    │           ├── js
    │           │   ├── main.040641a3.js
    │           │   └── main.040641a3.js.map
    │           └── media
    │               ├── 1.0ebbf763.jpg
    │               └── logo.5d5d9eef.svg
    └── templates
        └── index.html

Edit package.json and add hooks to script

"prebuild": "rm -rf .../backend/templates/index.html && rm -rf .../backend/static/build",
"postbuild": "mv build/index.html .../backend/templates/ && mv build .../backend/static/",

Write it under widnows

"prebuild": "del ...\backend\templates\index.html & rd /s/q ...\backend\static\build",
"postbuild": "move build\index.html ...\backend\templates\ & move build ...\backend\static\",

The purpose is to execute some shell commands before and after build.

So. After we run npm run build. The generated files are already in the backend.

But running python hello.py at this point will find out. The open page is blank. Looking at index.html under templates, you will find that the link address of the referenced file is incorrect

app = Flask(__name__,template_folder="templates",static_folder="static",static_url_path="/backend/static")

The path to our staic file should be / backend/static /... the js path above should be
/ This file is accessible only when backend/static/build/static/js/main.040641a3.js.
We can specify the homepage parameter in package.json to specify the home page path of the generated file.
Add in package.json

"homepage": "/backend/static/build"

The package.json at this point is as follows

{
  "name": "frontend",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "react": "^16.4.0",
    "react-dom": "^16.4.0",
    "react-scripts": "1.1.4",
  },
  "scripts": {
    "start": "react-scripts start",
    "prebuild":"rm -rf ../backend/templates/index.html && rm -rf ../backend/static/build",
    "build": "react-scripts build",
    "postbuild": "mv build/index.html ../backend/templates/ &&  mv build ../backend/static/", 
    "test": "react-scripts test --env=jsdom",
    "eject": "react-scripts eject"
  },
  "homepage": "/backend/static/build"
}

Then rebuild npm run build. Then run the python hello.py page and it will be displayed properly. In fact, when we run npm run build, we use files in the frontend/pubilc directory as templates. The generated index.html is also generated according to index.html under public. If we want to change the structure of the build file under the back-end static file. The index.html file in public needs to be modified at the same time. The static file address in the generated entry file can be found.

Modifying favicon.icon can change the icon on the file label.

The manifest.json file controls some configuration when adding a site to the home screen.

Posted by remlabm on Mon, 26 Aug 2019 02:05:45 -0700