加载中

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:

这是我用Python的轻量级框架 Flask 编写web程序时的一些经验,我将它记录在此,本篇是一系列文章中的第一篇。

下面是这个系列中已经发布的文章的目录:

My background

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.

我的背景:

我是个用多种语言开发复杂程序有超过10+年经验的码农,一开始我工作时学习Python来写C++库的Python接口。

除了Python,我还用PHP, Ruby, Smalltalk来写Web app,不管你信不信,我还用C++写web app,反正我是信了。所有这些东西中,我觉得Python+Flask是最灵活的.

The application

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:

  • User management, including managing logins, sessions, user roles, profiles and user avatars.
  • Database management, including migration handling.
  • Web form support, including field validation and captcha use for spam prevention.
  • Pagination of long lists of items.
  • Full text search.
  • Email notifications to users.
  • HTML and RSS templates.
  • Support for multiple languages.
  • Caching and other performance optimizations.
  • Debugging techniques for development and production servers.
  • Installation on a production server.

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表单支持,包括字段检验和用于防止垃圾邮件的验证码功能。
  • 大数据的分页功能。
  • 全文检索。
  • 用户邮件通知。
  • HTML和RSS模板。
  • 多语言支持。
  • 缓存和其它性能优化。
  • 用于开发和生产环境服务器上的调试技术。
  • 生产环境服务器上的部署安装。

正如你所看到的,整个过程我将花费不少精力。我希望这个应用,当它开发完成后,将作为一种编写其它web应用的模板。

Requirements

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.

要求

如果你拥有一台运行着Python 2.6或者2.7的电脑那么你可以很好的进行下去。这个教程应用应该可以刚刚好地运行在Windows,OS X和Linux上。

教程假设你熟练终端窗口(对于Windows用户就是命令行提示CMD)以及了解你的操作系统上基本的命令行文件管理函数。如果不是这样,在继续我们的教程之前,那么我推荐你去学一下怎么创建目录,复制文件等操作,要利用命令得哦,亲!

最后,你应该对于编写Python代码有点感觉,不要太菜。对于Python模块和包这一块要熟悉是必须的。

Installing Flask

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.

安装Flask

废话少说,开始吧!

如果你还没准备好,去安装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了(译者注:这个是作者的个人喜好,可以不用删),因为我们不再需要它了。


"Hello, World" in Flask

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.

通过Flask创建 "Hello, World"

现在在你的微博文件夹下有一个flask字文件夹,它被加入了一段Python注释,而且我们将在App应用中使用Flask框架和它的扩展。现在让我们来写我们的第一个web应用吧。

在你通过cd命令行进到微博文件夹下后,让我们来创建我们应用的文件结构:

mkdir app
mkdir app/static mkdir app/templates
mkdir tmp

我们将把应用的包存放在这个app文件夹下。这个静态子文件件夹我们用来放诸如图片、JS或者CSS之类的文件,而template子文件夹则明显用于存放template文件的。

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.

现在让我们来给我们的app包创建一个简单的初始化脚本(app/__init__.py)。

from flask import Flask app = Flask(__name__) from app import views

上面的这段简单的脚本创建了Flask类的应用对象然后导入我们还没写的views视图模块。

这个模块相当于一个执行者来返回用户的web请求。在Flask中,视图一般会被作为Python写出,每一个视图映射一个或者多个URL

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实例。

返回顶部
顶部