Install Python's flask Framework on Linux and create a tutorial on the first app instance

Source: Internet
Author: User
Tags vps virtual environment
Whether you're entertaining or working on Linux, this is a great opportunity for you to program with Python. Back to college I want them to teach me python instead of Java, which is interesting to learn and useful in real-world applications like the Yum Package Manager.

In this tutorial I'll take you through the use of Python and a mini-framework called flask to build a simple application that shows useful information such as memory usage per process, CPU percentage, and so on.
Front-facing requirements

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

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.
Installing 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-vpython 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 is not backwards compatible with Python 2.

Note : Before you 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 accident can damage your system.

The following steps are based on Red Hat versions such as CentOS (6 and 7), Debian-based versions such as Ubuntumint and Resbian can skip this step, Pythonn 3 should already be installed by default. If not, install the appropriate package using Apt-get instead of yum.

[Leo@linux-vps] Yum Groupinstall ' development Tools ' [Leo@linux-vps] yum install-y zlib-dev openssl-devel sqlite-devel BZ Ip2-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# recommended make Altinstall To overwrite the current Python library [Leo@linux-vps] make Altinstall

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

[leo@linux-vps]# Python3.4python 3.4.2 (default, Dec, 08:01:15) [GCC 4.8.2 20140120 (Red Hat 4.8.2-16)] on Linuxtyp E "Help", "copyright", "credits" or "license" for more information.>>> exit ()

Using 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 of dependent environments where your project is placed. This is a good way to isolate projects with different dependent environments. It allows you to install packages without 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 creates a directory called Lib inside the Venv folder, where the packages that the project depends on are installed. A bin folder will also be created to accommodate Pip and Python executables in that environment.
Activating a 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

Installing Flask with PIP

Let's continue to install the first module flask framework, which can handle access to routes and render templates that display our app.

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

Create the first app in flask
First step: Create your app's 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, which contains two subfolders "Static" and "templates". Our Python script will be placed in the app folder, such as CSS/JS files will be in the static folder, the template folder will contain our HTML template.
Step Two: Create an initialization file inside 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 instance of flask and loads the python program we stored in the index.py file-this file we'll create 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

Access routes in flask are handled through the route 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 a parameter, the first item in the list is the executable program by default, and the next one is the parameter, and here is a different example.

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

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

Out,error = Cmd.communicate ()

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

Memory = Out.splitlines ()

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

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

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 a index.html template in your template directory, flask will automatically search for the template under this directory.

[Leo@linux-vps python3.4-flask]vim app/templates/index.html Memory usage per process {% for line in Memory%}{{line.decod E (' Utf-8 ')}} {% endfor%}

The JINJA2 template engine allows you to use "{{...}}" Delimiter to output the result, {% ...%} to do the loop and assign the value. I use the "decode ()" method to format.
Fourth step: 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 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 the full code here.

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

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

    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.