preface

Recently, I did a small query system in my work. Because it was relatively simple, I did it all by myself. Here from the perspective of front-end students explain and record the process of simultaneous development of the front and back end, hoping to provide ideas for the majority of students interested in the front and back end ~

A. Related technology

1. The front end

The front end mainly uses Vue+ElementUI+ AXIOS (HTTP data request)

IDE I recommend VSCode (mixes •_•)

VSCode: VSCode download address

2. The back end

The backend access layer uses Python (version 3.7) + Flask

Here IDE I used PyCharm

PyCharm: PyCharm

Use Gunicorn as Flask’s Web Server

Process management using Supervisor (you can quickly start, shut down, restart, and view the status of our Flask application from the command line)

2. Demand analysis and development ideas

1. Requirements analysis

The system is mainly used for operation and maintenance colleagues to do data analysis, the main function is the compound condition query, and then in the form of a list to show the data

2. Development ideas

1) According to our requirements, front-end SPA (single-page application) was developed with Vue+ElementUI, and HTTP data request was initiated for Flask application from the front-end

Druid = Druid; Druid = Druid; Druid = Druid; Druid = Druid; Druid = Druid

To sum up: The interface of the request is written in Flask application. After obtaining the query conditions, Python is used to initiate data requests to Druid according to the query conditions. When Druid returns the query results, After some logical processing (such as exception processing or return format processing), it is finally returned to the front end for the front end to display data, as shown in the figure below.

Roll up your sleeves and start Coding

1. Set up front-end engineering

1) Preparations required:

Nodejs installation: nodeJS download address

2) After the preparation work is completed, we use NPM to download the latest VUE-CLI3 as of January 30, 2019 so that we can get the latest VUE scaffolding works

npm install -g @vue/cli

After vuE-CLI3 is downloaded, use the command line to get the latest VUE scaffolding works

vue create my-project

3) At this point, we have an official scaffold project where we can make changes based on project requirements

2. Set up the Flask application

1) Python installation: Python download address

And configure the environment variables

2) Install VirtualEnv using python’s package management tool PIP

pip install virtualenv

The VirtualEnv virtual environment is used to develop multiple Flask applications that depend on different versions and packages

3) Create the Flask application project using PyCharm, as shown below.

Note: If you do not create the Flask project by PyCharm, install the Flask using the PIP command alone

3. Implement front-end access layer API with Flask application

So let’s go to the code

from flask import Flask, render_template
from flask import request
Install PIP Install Requests, JSON before importing requests and JSON
import requests,json
app = Flask(__name__)
@app.route('/')
def index():
    return render_template('index.html')
	
@app.route('/here/js_get', methods=['GET'])
def js_get():
     #python requests Druid's URL
     url = "http://x.x.x.x:x/druid/v2/? pretty"
     headers = {'content-type':'application/json'.'Accept-Charset':'UTF8'}
	 Python requests parameters from Druid
	 Values are the key parameters passed from the front end
	 Request. Values ['timeStamp']
	 Loads (request. Values ['timeStamp']) with json.loads(request. Values ['timeStamp']
	 param={
	  requestId:request.values['requestId'],
	  fileKey:request.values['fileKey'],
	  timeStamp:request.values['timeStamp']}Here Python makes a request to Druid
	 r = requests.post(url, data=json.dumps(param), headers=headers)
	 # r.ext is the data that Python requested. Json.dumps () converts it to a string and returns it
	 result = json.dumps(r.text)
	 return result
if __name__ == '__main__':
     app.run("0.0.0.0")
Copy the code

I simplified the code in my project, removing the logic processing, format processing and other parts that affect intuitive understanding. Let’s take a look at the code above. First we need to understand the following part of the code, which specifies that our Flask application will let the front-end user access our front-end application from index.html after opening the link

@app.route('/')
def index():
    return render_template('index.html')
Copy the code

In Flask, there is an API called /here/js_get, and the request method is GET. Because the front-end engineering is packaged and stored in the Flask application, the domain name is automatically completed. For example, if the domain name I use to access the front-end interface is www.test.com, the complete request link is www.test.com/here/js_get. When the front-end interface makes a request, the domain name does not need to be added (the front-end request code will be written later).

@app.route('/here/js_get', methods=['GET'])
def js_get():
Copy the code

Finally, let’s look at the following part of the code, where app.run(0.0.0.0) refers to our Flask application that does not restrict access to IP addresses

if __name__ == '__main__':
     app.run("0.0.0.0")
Copy the code

Flask (@app.route(‘/’)) controls the user’s access to index.html. Don’t worry, we’ll go through it step by step

4. How does the front end call the Flask application API

NPM install axios –save-dev in Vue project, as shown in the following code, use AXIos to make an HTTP request, call Flask’s API, and the data will be returned via res.data. If the request fails, The ERR section is entered

<script>
import axios from 'axios'
export default {
 name:'Example'.data() {return{
    requestId:' ',
    fileKey:' ',
    timeStamp:' '
  }
 }
 methods:{
   startSearching(){
    axios.get('/here/js_get',{ params:{ requestId:this.requestId, fileKey:this.fileKey, TimeStamp: this.timestamp}}). Then ((res)=>{//res.data =>{,(err)=>{ })}}} </script>Copy the code

In this way, the simple front-end call Flask application API part of the code is finished, if in the development stage, the front and back end need to be coordinated, you can use webpack proxy for cross-domain processing, to prevent cross-domain problems caused by inconsistent localhost and API domain name.

Let’s talk about how to publish the front-end engineering and Flask applications once they have been developed

5. Front-end packaging and back-end deployment

1) Firstly, the scaffolding project of VUE-Cli3 is integrated with Webpack4. By default, NPM run build can be used to pack. The dist directory after I packed is shown in the figure below.

It is recommended that you use VirtualEnv to create dependent virtual environments for multiple Flask applications on the same server

3) After the environment is configured, upload our Python project code. If your project does not have a static folder and a templates folder in the root directory, please create one. Remember the code I packed with Webpack on the front end above? Put the index.html in the templates folder and everything else in the static folder.

4) After putting the front-end packaged code in the corresponding position, run our Python code. Since this project only uses Python to develop the API of the access layer, all my codes are in a Python file. For example, if my file is called app.py, THEN I execute it through Python app.py. The entire Flask application is then up and running, and the user can access the front-end interface via a browser using the configured domain name (nginx is used for this step).

Remember the following part of our Flask application?

@app.route('/')
def index():
    return render_template('index.html')
Copy the code

The ‘/’ of the route means that we access index.html in the Flask application by opening the domain name, assuming that our domain name is www.test.com, we rewrite the route to app.route(‘/first’), So our domain name for accessing index.html would be www.test.com/first, which is not as intuitive as www.test.com, right? So the route configuration app.route(‘/’) allows visitors to access index.html directly from the domain name

6. Gunicorn and supervisor

What we said before is that when we execute Python code and make it accessible to the user through the browser, in this case, when we disconnect from the server, the Python service terminates. Even if we don’t terminate python services by disconnecting from the server, if we have multiple Flask applications on the same server, we don’t have much control over which Flask applications start, which end, and which restart without the help of tools. At this point, my python backend developer recommended Gunicorn + Supervisor to me. The former is used as a Web Server and the latter is used for process management of Flask applications

1) gunicorn

Run the command to install Gunicorn in Linux

pip install gunicorn

2) the supervisor

Install the Supervisor in Linux

pip install supervisor

Then run the following command to generate the Supervisor initial configuration file

echo_supervisord_conf > /usr/etc/supervisord.conf

At the back of the/usr/etc/supervisord. Conf is to generate the configuration file path

After the configuration file is generated, we use vim to enter the configuration file and add at the end

[include]
files = /root/flask_demo/supervisord.conf
Copy the code

The above code indicates that the configuration information in the configuration file also contains the relevant configuration information in the path of files, which means that the combination of the two is the final configuration information, but at this time I have not created the configuration file in the relevant path, flask_demo is my Flask project directory, enter it, It’s going to create the supervisord.conf and it’s going to be edited using Vim. My configuration file is going to look like this

[program:app]
command=/usr/bin/gunicorn -w 4 -b 0.0.0.0:5000 app:app
process_name=%(program_name)s
numprocs=1
directory=/root/flask_demo/
autostart=true
autorestart=unexpected
stdout_logfile=/root/flask_demo/log/stdout.log
stderr_logfile=/root/flask_demo/log/stderr.log
Copy the code

-w refers to the worker, -w refers to the number of workers, -b refers to the address, followed by the address information, app:app, where the former refers to the name of the Python file, mine is app.py, and the latter refers to the name of the Flask application

After the configuration information is edited, run the command

supervisord -c /root/usr/etc/supervisord.conf

It’s going to be a little bit of a surprise, isn’t it supervisor, is it going to be supervisorord? The Supervisor is made up of two command lines, the supervisord and the supervisorCTL. Conf configuration file, which contains our own custom configuration file for the project. Execute the command after executing the internal configuration file of our project

supervisorctl

At this time, if the status of our Flask application appears, it means that we have succeeded, as shown in the figure below

In the Flask application startup state, you can verify the current Flask application process by running Linux commands

ps aux|grep app:app

See the following figure:

4. To summarize

That’s what I want to share with you this time. I hope this post will help you (ฅ´ω ‘ฅ).