翻译于 2012/12/28 10:06
13 人 顶 此译文
This is the first article in a series where I will be documenting my experience writing web applications in Python using the Flask microframework.
Here is an index of all the articles in the series that have been published to date:
> You can learn more about Python: https://www.pcwdld.com/python-cheat-sheet
这是我用Python的轻量级框架 Flask 编写web程序时的一些经验,我将它记录在此,本篇是一系列文章中的第一篇。
下面是这个系列中已经发布的文章的目录:
I'm a software engineer with double digit years of experience developing complex applications in several languages. I first learned Python as part of an effort to create bindings for a C++ library at work.
In addition to Python, I've written web apps in PHP, Ruby, Smalltalk and believe it or not, also in C++. Of all these, the Python/Flask combination is the one that I've found to be the most flexible.
The app I'm going to develop as part of this tutorial is a decently featured microblogging server that I decided to call microblog. Pretty creative, I know.
These are some of the topics I will cover as we make progress with the app:
So as you see, I'm going pretty much for the whole thing. I hope this app, when finished, will serve as a sort of template for writing other web applications.
作为这个教程的一部分,我即将要开发一个专门用于发送微博服务的应用,我叫它微博(无聊的名字),相当给力,我当然知道,哈!
我在开发这个应用的过程中会涉及到如下几个话题:
正如你所看到的,整个过程我将花费不少精力。我希望这个应用,当它开发完成后,将作为一种编写其它web应用的模板。
If you have a computer that runs Python 2.6 or 2.7 then you are probably good to go. The tutorial application should run just fine on Windows, OS X and Linux.
The tutorial assumes that you are familiar with the terminal window (command prompt for Windows users) and know the basic command line file management functions of your operating system. If you don't, then I recommend that you learn how to create directories, copy files, etc. using the command line before continuing.
Finally, you should be somewhat comfortable writing Python code. Familiarity with Python modules and packages is also recommended.
Okay, let's get started!
If you haven't yet, go ahead and install Python 2.7.
Now we have to install Flask and several extensions that we will be using. My preferred way to do this is to create a virtual environment where everything gets installed, so that your main Python installation is not affected. As an added benefit, you won't need root access to do the installation in this way.
So, open up a terminal window, choose a location where you want your application to live and create a new folder there to contain it. Let's call the application foldermicroblog.
Next, download virtualenv.py and put it inside the new folder.
To create the virtual environment enter the following command:
python virtualenv.py flask
The above command creates a complete Python environment inside theflaskfolder.
废话少说,开始吧!
如果你还没准备好,去安装Python 2.7吧。
现在我们必须要安装Flask和服务端扩展,这些都是我们即将要用到的。我偏爱的方式是创建一个虚拟环境,所有东西都已经安装在这个虚拟环境中了,因此你自已主要的Python安装环境则不会受影响。附加的一个好处是,用这种方式来安装时不需要root管理员权限。
好了,打开终端窗口,选择一个位置用来落脚我们的应用,并且在此创建一个新目录,这个目录就叫作microblog。
下一步,下载virtualenv.py,并且把它放进这个新目录。
敲下以下命令行,用来创建一个虚拟环境:
python virtualenv.py flask上面的命令在flask目录里面创建一个完整的Python环境。
Virtual environments can be activated and deactivated, if desired. An activated environment adds the location of itsbinfolder to the system path, so that for example, when you typepythonyou get the environment's version and not the system's one. I personally do not like this feature, so I never activate any of my environments and instead just invoke the interpreter I want by typing its pathname.
If you are on Linux, OS X or Cygwin, install flask and extensions by entering the following commands, one after another:
flask/bin/pip install flask flask/bin/pip install flask-login flask/bin/pip install flask-openid flask/bin/pip install flask-mail flask/bin/pip install flask-sqlalchemy flask/bin/pip install sqlalchemy-migrate flask/bin/pip install flask-whooshalchemy flask/bin/pip install flask-wtf flask/bin/pip install flask-babel flask/bin/pip install flup
If you are on Windows the commands are slightly different:
flask\Scripts\pip install flask flask\Scripts\pip install flask-login flask\Scripts\pip install flask-openid flask\Scripts\pip install flask-sqlalchemy flask\Scripts\pip install sqlalchemy-migrate flask\Scripts\pip install flask-whooshalchemy flask\Scripts\pip install flask-wtf flask\Scripts\pip install flask-babel flask\Scripts\pip install flup
These commands will download and install all the packages that we will use for our application.
虚拟环境可以是激活的,也可以是失效的。如果你希望的话,可以将 flask 的 bin 目录路径加到系统环境变量 path 的后面。这样就使虚拟环境为激活的,当你在终端输入 python 命令时,你将看到的是环境的版本信息而不是 python 的版本信息。我个人不喜欢这种特性,所以我从来不激活我的环境参数,就只是写它的完整路径来进行调用。
如果你的环境是 Linux,OS X or Cygwin,使用以下命令安装 flask 和 扩张包,按顺序一个接一个:
flask/bin/pip install flask flask/bin/pip install flask-login flask/bin/pip install flask-openid flask/bin/pip install flask-mail flask/bin/pip install flask-sqlalchemy flask/bin/pip install sqlalchemy-migrate flask/bin/pip install flask-whooshalchemy flask/bin/pip install flask-wtf flask/bin/pip install flask-babel flask/bin/pip install flup
如果你的是 Windows 环境,那么命令有点不同:
flask\Scripts\pip install flask flask\Scripts\pip install flask-login flask\Scripts\pip install flask-openid flask\Scripts\pip install flask-sqlalchemy flask\Scripts\pip install sqlalchemy-migrate flask\Scripts\pip install flask-whooshalchemy flask\Scripts\pip install flask-wtf flask\Scripts\pip install flask-babel flask\Scripts\pip install flup
这些命令会下载和安装我们应用中所需要的包。
Note about SQLAlchemy: version 0.8 of SQLAlchemy is not backwards compatible with previous releases. In particular, the sqlalchemy-migrate module does not work with it. For that reason we need to force the install of release 0.7.9, with the following commands:
flask/bin/pip uninstall sqlalchemy flask/bin/pip install sqlalchemy==0.7.9
Once sqlalchemy-migrate is updated to support 0.8 we should be able to work with the latest and greatest.
Windows users have one more step. If you have good observation skills you may have noticed thatflask-mailwas not included in the Windows installation command list. This extension does not install cleanly on Windows, so we have to get it installed via a workaround:
flask\Scripts\pip install --no-deps lamson chardet flask-mail
I won't go into details regarding this, if you want more information please refer to the flask-mail documentation.
If the installation of all the packages was successful you can deletevirtualenv.py, since we won't need it anymore.
关于SQLAlchemy,需要注意:SQLAlchemy v0.8 并不兼容之前的一些版本。尤其是sqlalchemy-migrate模块无法和v0.8一起使用。所以我们需要强制安装v0.7.9,命令如下:
flask/bin/pip uninstall sqlalchemy flask/bin/pip install sqlalchemy==0.7.9
等sqlalchemy-migrate更新到支持SQLAlchemy v0.8的时候再使用吧。
Windows用户需要多一个步骤。如果你善于观察,你会注意到上一段中的windows环境包安装命令并没安装flask-mail包,因为它在windows上安装时默认会附带一些其他包,所以我们使用另一个命令来解决:
flask\Scripts\pip install --no-deps lamson chardet flask-mail关于这个问题,我不会进入细节,如果你想要了解更多,请参考flask-mail的官方文档。
如果你成功安装完了所有包,那你可以删除virtualenv.py了(译者注:这个是作者的个人喜好,可以不用删),因为我们不再需要它了。
You now have aflasksub-folder inside yourmicroblogfolder that is populated with a Python interpreter and the Flask framework and extensions that we will use for this application. Now it's time to write our first web application!
After youcdto themicroblogfolder, let's create the basic folder structure for our app:
mkdir app mkdir app/static mkdir app/templates mkdir tmp
Theappfolder will be where we will put our application package. Thestaticsub-folder is where we will store static files like images, javascripts, and style sheets. Thetemplatessub-folder is obviously where our templates will go.
Let's start by creating a simple init script for ourapppackage (fileapp/__init__.py):
from flask import Flask app = Flask(__name__) from app import views
The script above simply creates the application object (of classFlask) and then imports the views module, which we haven't written yet.
The views are the handlers that respond to requests from web browsers. In Flask views are written as Python functions. Each view function is mapped to one or more request URLs.
Let's write our first view function (fileapp/views.py):
from app import app @app.route('/') @app.route('/index') def index(): return "Hello, World!"
This view is actually pretty simple, it just returns a string, to be displayed on the client's web browser. The tworoutedecorators above the function create the mappings from urls/and/indexto this function.
The final step to have a fully working web app is to create a script that starts up the development web server with our application. Let's call this scriptrun.py.
#!flask/bin/python from app import app app.run(debug = True)
The script simply imports theappvariable from our app package and invokes itsrunmethod to start the server. Remember that theappvariable holds theFlaskinstance, we created it above.
下面让我们来写第一个视图功能(app/views.py):
from app import app @app.route('/') @app.route('/index') def index
这个视图非常的简单,它仅仅就是返回一个string语句,先后显示在用户的web浏览器上。功能上的两条路径连接这从urls/and/index到这个功能的映射。
下面,使web应用能完全运行的最后一步就是创建一个能启动我们开发的这个应用web服务器的脚本。我们叫它scriptrun.py。
#!flask/bin/python from app import app app.run(debug = True)
这段脚本只是从我们的app包中导入了app的变量,然后调用它的方法来启动服务器。记住,这个变量保存着我们上面创建的Flask实例。