Install the Python flask Framework on Linux and the tutorial on creating the first app instance _python

Source: Internet
Author: User
Tags memory usage mkdir vps python script virtual environment

Whether you're entertaining or working on Linux, this is a great opportunity for you to program with Python. Back in 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'll take you through Python and a micro-framework called flask to build a simple application that displays useful information such as memory usage for each process, CPU percentages, and so on.
predecessor Requirements

Python basics, lists, classes, functions, modules. Html/css (Foundation).

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

Python is installed by default on most Linux distributions. The following command allows you to see the installed version.

[Root@linux-vps ~]# python-v
python 2.7.5

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

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

The following steps are based on a red Hat version such as CentOS (6 and 7), which can be skipped based on Debian versions such as Ubuntumint and Resbian, Pythonn 3 should be installed by default. If it is not installed, use Apt-get instead of Yum to install the appropriate package below.

[Leo@linux-vps] Yum groupinstall ' Development Tools '
[Leo@linux-vps] Yum install-y Zlib-dev 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
# recommends using make Altinstall to overwrite the current Python library
[Leo@linux-vps] Make Altinstall

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

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

Using the PIP to install the package

Python has its own package management, which is 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 of dependencies that place your project. This is a good way to isolate projects that have different dependencies on the environment. It allows you to install packages without sudo commands.

[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 creates a directory named Lib inside the Venv folder, where the packages that the project depends on are installed. This also creates a bin folder that accommodates the PIP and Python executables in that 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 first module flask framework, which can handle access routing and render the templates that display our app.

[Leo@linux-vps python3.4-flask]pip3.4 Install flask

Create the first application in flask
The first step: Create your App Directory

[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 that contains two subfolders "Static" and "templates". Our Python script will be placed in the app folder, such as CSS/JS files in the static folder, template folder will contain our HTML templates.
Step Two: Create an initialization file inside of the app folder

[Leo@linux-vps Python3.4-flask] vim app/_init_.py from
flask import flask
 
app = Flask (__name__) from
app Import Index

This file creates a new instance of flask and loads the Python program we store in the index.py file-the file we'll create later.

[Leo@linux-vps Python3.4-flask]vim app/index.py from
app import app
 
@app. Route ('/')
def index ():
Import subprocess
cmd = subprocess. Popen ([' Ps_mem '],stdout=subprocess.) Pipe,stderr=subprocess. PIPE)
out,error = Cmd.communicate ()
memory = Out.splitlines ()
 
return

Access routes in flask are handled through the routing adorner. It is used to bind a URL to a function.

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

To run the shell command 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 an argument, and the first item of the list defaults to an executable program, and the next item is a parameter, and here's another example.

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

StdOut and stderr store the output and errors of the command accordingly. You can use the Popen communicate method to access the output.

Out,error = Cmd.communicate ()

To better display the output with an HTML template, I use the Splitlines () method,

Memory = Out.splitlines ()

More information about the Subprocess module will be given at the end of the tutorial.
Step three: Create an HTML template to display the output of our command.

To do this we use the JINJA2 template engine in flask to render it for us.

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

From flask import Render_template the From
app import App
 
def index ():
import subprocess
cmd = 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 a index.html template in your template directory, and flask will automatically search for templates 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 the result, {% ...%} to do loops and assignments. I use the "decode ()" method to format.
Fourth step: Running the app

[Leo@linux-vps Python3.4-flask]vim run.py from
app Import app
app.debug = True
app.run (host= ' 174.140.165.231 ', port=80)

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

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

I've added more code to show CPU, I/O, and average load.

You can browse through the complete code here.

This is a short tutorial on flask, and I suggest you read the tutorials and documentation below to learn more.

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

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.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.