translated

This commit is contained in:
zhengsihua 2014-12-19 22:40:23 +08:00
parent ca0e7cb31b
commit 690324d4a9
2 changed files with 208 additions and 210 deletions

View File

@ -1,210 +0,0 @@
Translating-----geekpi
Creating your First App on Linux with Python and Flask
================================================================================
![](http://techarena51.com/wp-content/uploads/2014/12/python-logo.png)
Whether playing on Linux or working on Linux there is high chance you have come across a program written in python. Back in college I wish they thought us Python instead of Java like they do today, its fun to learn and useful in building practical applications like the yum package manager.
In this tutorial I will take you through how I built a simple application which displays useful information like [memory usage per process][1], CPU percentage etc using python and a micro framework called flask.
### Prerequisites ###
Python Basics, Lists, Classes, Functions, Modules.
HTML/CSS (basic)
You dont need to be an advanced python programmer to follow this tutorial, But before you go further I recommend you read https://wiki.python.org/moin/BeginnersGuide/NonProgrammers
### Installing Python 3 on Linux ###
On most Linux distributions python is installed by default. This is how you can find out the python version on your system.
[root@linux-vps ~]# python -V
Python 2.7.5
We will be using python version 3.x to build our app. As per [Python.org][2] all improvements are now only available in this version which is not backward compatible with python 2.
**Caution**: Before your proceed I strongly recommend you try this tutorial out on a Virtual machine, since python is a core component of many Linux Distributions any accidents may cause permanent damage to your system.
This step is for RedHat based variants like CentOS (6&7), Debian based variants like Ubuntu,Mint and Rasbian can skip this step as you should have python version 3 installed by default. If not use apt-get instead of yum to install the relevant packages below.
[leo@linux-vps] yum groupinstall 'Development Tools'
[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 as make install can overwrite the current python binary,
[leo@linux-vps] make altinstall
After a successful, installation you should be able to access the python 3.4 shell with the command below.
[leo@linux-vps]# python3.4
Python 3.4.2 (default, Dec 12 2014, 08:01:15)
[GCC 4.8.2 20140120 (Red Hat 4.8.2-16)] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> exit ()
### Installing packages in python with PIP ###
Python comes with its own package manager, similar to yum and apt-get. You will need to use it to download, install and uninstall packages.
[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 projects dependencies are installed. This is a good way to segregate projects with different dependencies. It also allows you to install packages without the need for sudo access.
[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 the virtual environment you will need to use the “pyvenv-3.4” command. This will create a directory called “lib” inside the venv folder where the dependencies for this project will be installed. It will also create a bin folder which will contain pip and python executables for this virtual environment.
### Activating 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
### Installing flask with PIP ###
Lets go ahead and install out first module the flask framework which will take care of the routing and template rendering of our app.
[leo@linux-vps python3.4-flask]pip3.4 install flask
### Creating your first app in flask. ###
Step 1:Create directories where your app will reside.
[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
Inside the python3.4-flask folder create a folder called app which will contain two sub-folders “static” and “templates”. Our python script will reside inside the app folder, files like css/js inside the static folder and templates folder will contain our html templates.
Step 2:Create an initialization file inside 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 will create a new instance of Flask and load our python program stored in a file called index.py which we will create next.
[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
Routing in flask is handled by the route decorator. It is used to bind a URL to a function.
@app.route('/')
@app.route('/index')
In order to run a shell command in python you can use the Popen class from Subprocess module.
subprocess.Popen(['ps_mem'],stdout=subprocess.PIPE,stderr=subprocess.PIPE)
This class will take a list as an argument, the first item of the list will default to being executable while the next item will be considered the option. Here is another example
subprocess.Popen(['ls', -l],stdout=subprocess.PIPE,stderr=subprocess.PIPE)
stdout and stderr will store the output and error of this command respectively. You can then access this output via the communicate method of the Popen class.
out,error = cmd.communicate()
To display the output in a better way via the html template, I have used the splitlines () method,
memory = out.splitlines()
More information on python subprocess module is available in the docs at the end of this tutorial.
Step 3: Create an html template where we can display the output of our command.
In order to do this we need to use the Jinja2 template engine in flask which will do the template rendering for us.
Your final index.py file should look as follows
from flask import render_template
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 an index.html template inside the templates folder, flask will search for templates in this folder.
[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 the “{{ … }}” delimiter to print results and {% … %} for loops and value assignment. I used the “decode()” method for formatting purposes.
Step 4: 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 above code will run the app in debug mode. If you leave out the IP address and port it will default to localhost:5000.
[leo@linux-vps python3.4-flask] chmod +x run.py
[leo@linux-vps python3.4-flask] python3.4 run.py
![](http://techarena51.com/wp-content/uploads/2014/12/install-python3-flask.png)
I have added more code to the app so that it gives you cpu, I/O and load avg as well.
![](http://techarena51.com/wp-content/uploads/2014/12/install-python3-flask-on-linux.png)
You can access the code to this app [here][3].
This is a brief introduction to flask and I recommend you reading the tutorials and docs below for indepth information.
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
--------------------------------------------------------------------------------
via: http://techarena51.com/index.php/how-to-install-python-3-and-flask-on-linux/
作者:[Leo G][a]
译者:[译者ID](https://github.com/译者ID)
校对:[校对者ID](https://github.com/校对者ID)
本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创翻译,[Linux中国](http://linux.cn/) 荣誉推出
[a]:http://techarena51.com/
[1]:http://techarena51.com/index.php/linux-memory-usage/
[2]:https://wiki.python.org/moin/Python2orPython3
[3]:https://github.com/Leo-g/python-flask-cmd

View File

@ -0,0 +1,208 @@
在Linux上使用Python和Flask创建你的第一个应用
================================================================================
![](http://techarena51.com/wp-content/uploads/2014/12/python-logo.png)
无论你在linux上娱乐还是工作这对你而言都是一个很好的机会使用python来编程。回到大学我希望他们教我的是Python而不是Java这学起来很有趣且在实际的应用如yum包管理器中很有用。
本篇教程中我会带你使用python和一个称为flask的微型框架来构建一个简单的应用来显示诸如[每个进程的内存使用][1]CPU百分比之类有用的信息。
### 前提 ###
Python基础、列表、类、函数、模块。
HTML/CSS (基础)
学习这篇教程你不必是一个python高级开发者但是首先我建议你阅读https://wiki.python.org/moin/BeginnersGuide/NonProgrammers。
### I在Linux上安装Python 3 ###
在大多数Linux发行版上Python是默认安装的。下面的你命令可以让你看到安装的版本。
[root@linux-vps ~]# python -V
Python 2.7.5
我们会使用3.x的版本来构建我们的app。根据[Python.org][2]所说这版本上面所有的改进都不向后兼容Python 2。
**注意**: 在开始之前我强烈建议你在虚拟机中尝试这个教程因为Python许多Linux发行版的核心组建任何意外都可能会损坏你的系统。
这步是基于红帽的版本如CentOS6和7基于Debian的版本如UbuntuMint和Resbian可以跳过这步Pythonn 3应该默认已经安装了。如果没有安装请用apt-get而不是yum来安装下面相应的包。
[leo@linux-vps] yum groupinstall 'Development Tools'
[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 as make install can overwrite the current python binary,
[leo@linux-vps] make altinstall
成功安装后你应该可以用下面的命令进入Python3.4的shell了。
[leo@linux-vps]# python3.4
Python 3.4.2 (default, Dec 12 2014, 08:01:15)
[GCC 4.8.2 20140120 (Red Hat 4.8.2-16)] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> exit ()
### 使用pip来安装包 ###
Python有它自己的包管理去与yum和apt-get相似。你将需要它来下载、安装和卸载包。
[leo@linux-vps] pip3.4 install "packagename"
[leo@linux-vps] pip3.4 list
[leo@linux-vps] pip3.4 uninstall "packagename"
### Python虚拟环境 ###
在Python中虚拟环境是一个你项目依赖的目录。隔离项目的一个好主意是使用不同的依赖。这可以让你不用sudo命令就能安装包。
[leo@linux-vps] mkdir python3.4-flask
[leo@linux-vps] cd python3.4-flask
[leo@linux-vps python3.4-flask] pyvenv-3.4 venv
要创建虚拟环境你需要使用“pyvenv-3.4”命令。这会在venv文件夹的内部创建一个名为lib的目录这里会安装项目所依赖的包。这里同样会创建一个bin文件夹容纳该环境下的pip和python可执行文件。
### 为我们的Linux系统信息项目激活虚拟环境 ###
[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
### 使用pip安装flask ###
让我们继续安装第一个模块flask框架它可以处理路由和渲染我们app的模板。
[leo@linux-vps python3.4-flask]pip3.4 install flask
### 在flask中创建第一个应用 ###
第一步创建你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
在python3.4-flask文件家中创建一个一个名为app的文件夹它包含了两个子文件夹“static”和“templates”。我们的Python脚本会在app文件夹像css/js这类文件会在static文件夹template文件夹会包含我们的html模板。
第二步在app文件夹内部创建一个初始化文件。
[leo@linux-vps python3.4-flask] vim app/_init_.py
from flask import Flask
app = Flask(__name__)
from app import index
这个文件创建一个Flask的新的实例并加载我们存储在index.py文件中的python程序这个文件我们之后会创建。
[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
flask中的路由由路由装饰器处理。这用于给函数绑定URL。
@app.route('/')
@app.route('/index')
要在python中运行shell命令你可以使用Subprocess模块中的Popen类。
subprocess.Popen(['ps_mem'],stdout=subprocess.PIPE,stderr=subprocess.PIPE)
这个类会使用一个列表作为参数,列表的第一项默认是可执行的程序,下一项会是参数,这里是个另外一个例子。
subprocess.Popen(['ls', -l],stdout=subprocess.PIPE,stderr=subprocess.PIPE)
stdout和stderr会相应地存储命令的输出和错误。你可以使用Popen的communicate方法来访问输出了。
out,error = cmd.communicate()
要更好地用html模板显示输出我会使用splitlines()方法,
memory = out.splitlines()
关于subprocess模块更多的信息会在教程的最后给出。
第三步创建一个html模板来显示我们命令的输出。
要做到这个我们使用flask中的Jinja2模板引擎来为我们渲染。
最后你的index.py文件应该看起来像这样
from flask import render_template
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)
现在在你的模板目录下创建一个index.html模板flask会自动搜索这个目录下的模板。
[leo@linux-vps python3.4-flask]vim app/templates/index.html
Memory usage per process
{% for line in memory %}
{{ line.decode('utf-8') }}
{% endfor %}
Jinja2模板引擎允许你使用“{{ … }}”分隔符来打印结果,{% … %}来做循环和赋值。我使用“decode()”方法来格式化。
第四步运行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)
上面的代码会在debug模式下运行app。如果你不写IP地址和端口默认则是localhost:5000。
[leo@linux-vps python3.4-flask] chmod +x run.py
[leo@linux-vps python3.4-flask] python3.4 run.py
![](http://techarena51.com/wp-content/uploads/2014/12/install-python3-flask.png)
我已经加了更多的带来来显示CPU、I/O和平均负载。
![](http://techarena51.com/wp-content/uploads/2014/12/install-python3-flask-on-linux.png)
你可以在[这里][3]浏览代码。
这是一个对flask的简短教程我建议你阅读下面的教程和文档来更深入地了解。
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
--------------------------------------------------------------------------------
via: http://techarena51.com/index.php/how-to-install-python-3-and-flask-on-linux/
作者:[Leo G][a]
译者:[geekpi](https://github.com/gekpi)
校对:[校对者ID](https://github.com/校对者ID)
本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创翻译,[Linux中国](http://linux.cn/) 荣誉推出
[a]:http://techarena51.com/
[1]:http://techarena51.com/index.php/linux-memory-usage/
[2]:https://wiki.python.org/moin/Python2orPython3
[3]:https://github.com/Leo-g/python-flask-cmd