Install the Python Flask framework on Linux and create the first app instance.

Source: Internet
Author: User
Tags vps

Install the Python Flask framework on Linux and create the first app instance.

Whether you are entertaining or working on linux, this is a great opportunity for you to program using python. Back to college I want them to teach me Python instead of Java, which is interesting to learn and useful in practical applications such as yum Package Manager.

In this tutorial, I will show you how to use python and a micro-framework called flask to build a simple application to display useful information such as memory usage and CPU percentage of each process.
Prerequisites

Python basics, lists, classes, functions, and modules. HTML/CSS (basic ).

To learn this tutorial, you don't have to be a python advanced developer, but first I suggest you read the https://wiki.python.org/moin/BeginnersGuide/NonProgrammers.
Install Python 3 on Linux

Python is installed by default on most Linux distributions. The following command shows the installed version.
 

[root@linux-vps ~]# python -VPython 2.7.5

We will use version 3.x to build our app. According to Python.org, this version is only improved and is not backward compatible with Python 2.

Note:: Before you start, I strongly recommend that you try this tutorial on a virtual machine, because Python is the core component of many Linux distributions and may damage your system in any way.

The following steps are Red Hat-based versions such as CentOS (6 and 7). Debian-based versions such as tumint and Resbian can skip this step. Pythonn 3 should have been installed by default. If not, use apt-get instead of yum to install the corresponding package.
 

[Leo @ linux-vps] yum groupinstall 'development tool' [leo @ linux-vps] yum install-y zlib-dev openssl-devel sqlite-devel bzip2-devel [leo @ linux-vps] wget https://www.python.org/ftp/python/3.4.2/Python-3.4.2.tgz[leo@linux-vps] tar-xvzf Python-3.4.2.tgz [leo @ linux-vps] cd Python-3.4.2 [leo @ linux-vps]. /configure [leo @ linux-vps] make # make altinstall is recommended to overwrite the current python Library [leo @ linux-vps] make altinstall

After successful installation, you should be able to use the following command to enter the shell of Python3.4.
 

[leo@linux-vps]# python3.4Python 3.4.2 (default, Dec 12 2014, 08:01:15)[GCC 4.8.2 20140120 (Red Hat 4.8.2-16)] on linuxType "help", "copyright", "credits" or "license" for more information.>>> exit ()

Use pip to install packages

Python has its own package management, similar to yum and apt-get. You will need it to download, install, and uninstall the package.
 

[leo@linux-vps] pip3.4 install "packagename"[leo@linux-vps] pip3.4 list[leo@linux-vps] pip3.4 uninstall "packagename"

Python Virtual Environment

In Python, a virtual environment is a directory where your project depends on the environment. This is a good way to isolate projects with different dependent environments. It allows you to install the installation package without using the sudo command.
 

[leo@linux-vps] mkdir python3.4-flask[leo@linux-vps] cd python3.4-flask[leo@linux-vps python3.4-flask] pyvenv-3.4 venv

To create a virtual environment, you need to use the pyvenv-3.4 command. The above command will create a directory named lib inside the venv folder, where the package on which the project depends will be installed. A bin folder will also be created to hold the pip and python executable files in the environment.
Activate the virtual environment for our Linux System Information Project
 

[leo@linux-vps python3.4-flask] source venv/bin/activate[leo@linux-vps python3.4-flask] which pip3.4~/python3.4-flask/venv/bin/pip3.4[leo@linux-vps python3.4-flask] which python3.4~/python3.4-flask/venv/bin/python3.4

Install flask using pip

Let's continue to install the flask framework of the first module, which can process access routing and render and display the template of our app.
 

[leo@linux-vps python3.4-flask]pip3.4 install flask

Create the first application in flask
Step 1: create a directory for your app
 

[leo@linux-vps python3.4-flask] mkdir app[leo@linux-vps python3.4-flask] mkdir app/static[leo@linux-vps python3.4-flask] mkdir app/templates

Create a folder named app in the python3.4-flask folder, which contains two subfolders: static and templates ". Our Python scripts are stored in the app folder, and files such as css and js are stored in the static folder. The template folder contains our html template.
Step 2: Create an initialization file in the app folder
 

[leo@linux-vps python3.4-flask] vim app/_init_.pyfrom flask import Flask app = Flask(__name__)from app import index

This file creates a new Flask instance and loads the python program stored in the index. py file. This file will be created later.
 

[leo@linux-vps python3.4-flask]vim app/index.pyfrom app import app @app.route('/')def index():import subprocesscmd = subprocess.Popen(['ps_mem'],stdout=subprocess.PIPE,stderr=subprocess.PIPE)out,error = cmd.communicate()memory = out.splitlines() return

The access route in flask is processed by the route decorator. It is used to bind a URL to a function.
 

@app.route('/')@app.route('/index')

To run shell commands in python, you can use the Popen class in the Subprocess module.
 

subprocess.Popen(['ps_mem'],stdout=subprocess.PIPE,stderr=subprocess.PIPE)

This class uses a list as a parameter. The first item in the list is an executable program by default, and the next item is a parameter. Here is another example.
 

subprocess.Popen(['ls', ‘-l'],stdout=subprocess.PIPE,stderr=subprocess.PIPE)

Stdout and stderr store command output and errors accordingly. You can use the communicate method of Popen to access the output.
 
Out, error = cmd. communicate ()

To better display the output using an html template, I will use the splitlines () method,
 

memory = out.splitlines()

More information about the subprocess module is provided at the end of the tutorial.
Step 3: Create an html template to display the output of our command.

To achieve this, we use the Jinja2 template engine in flask for rendering.

Finally, your index. py file should look like this:
 

from flask import render_templatefrom app import app def index():import subprocesscmd = subprocess.Popen(['ps_mem'],stdout=subprocess.PIPE,stderr=subprocess.PIPE)out,error = cmd.communicate()memory = out.splitlines() return render_template('index.html', memory=memory)

Now, create an index.html Template under your template directory. flask will automatically search for the template in this directory.
 

[leo@linux-vps python3.4-flask]vim app/templates/index.html Memory usage per process {% for line in memory %}{{ line.decode('utf-8') }} {% endfor %}

The Jinja2 template engine allows you to use "{… } "Separator to output results, {%... %. I used the "decode ()" method to format it.
Step 4: run the app
 

[leo@linux-vps python3.4-flask]vim run.pyfrom app import appapp.debug = Trueapp.run(host='174.140.165.231', port=80)

The above code runs the app in debug mode. If you do not specify the IP address and port, the default value is localhost: 5000.
 

[leo@linux-vps python3.4-flask] chmod +x run.py[leo@linux-vps python3.4-flask] python3.4 run.py

I have added more code to Display CPU, I/O, and average load.

You can view the complete code here.

This is a short tutorial on flask. I suggest you read the following tutorials and documents for a better understanding.

Http://flask.pocoo.org/docs/0.10/quickstart/

Https://docs.python.org/3.4/library/subprocess.html#popen-constructor

Http://blog.miguelgrinberg.com/post/the-flask-mega-tutorial-part-i-hello-world

Related Article

E-Commerce Solutions

Leverage the same tools powering the Alibaba Ecosystem

Learn more >

Apsara Conference 2019

The Rise of Data Intelligence, September 25th - 27th, Hangzhou, China

Learn more >

Alibaba Cloud Free Trial

Learn and experience the power of Alibaba Cloud with a free trial worth $300-1200 USD

Learn more >

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.