Flask 教程,第一部分:Hello,World! 已翻译 100%

oschina 投递于 2012/12/28 08:49 (共 12 段, 翻译完成于 12-30)
阅读 199739
收藏 288
72
加载中

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

已有 3 人翻译此段
我来翻译
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.

已有 2 人翻译此段
我来翻译

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.

已有 1 人翻译此段
我来翻译

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.

已有 1 人翻译此段
我来翻译

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.

已有 1 人翻译此段
我来翻译

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.

已有 2 人翻译此段
我来翻译

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.

已有 1 人翻译此段
我来翻译

"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.

已有 1 人翻译此段
我来翻译

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.

已有 1 人翻译此段
我来翻译

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.

已有 1 人翻译此段
我来翻译
本文中的所有译文仅用于学习和交流目的,转载请务必注明文章译者、出处、和本文链接。
我们的翻译工作遵照 CC 协议,如果我们的工作有侵犯到您的权益,请及时联系我们。
加载中

评论(39)

Amor_Fatim
Amor_Fatim
请教一下,按照教程来的,但是在运行run.py 的时候提示ImportError: cannot import name 'app'这个问题应该怎样解决?
一只bug
一只bug
这讲解真的是醉了,代码都不换行的。@app.route('/index')路由到这里,能出来吗? 肯定出不来啊,@app.route('/')路由到这里才能看到效果。
sunsama
sunsama
为什么不分行,好坑啊
笔阁
笔阁
我也写过一篇,还获得了推荐。
http://my.oschina.net/u/2275217/blog/522474
lls8672
lls8672
给各位看不懂这里面代码,和原样输入代码后会出错的提个醒:一定要记得拉到页面下面,下载源代码,查看源代码里的文件层次结构和每个文件里的每行代码,因为在这个教程里没有把每个文件里的所有代码都讲解一下,所以这对于刚入门的新手来说,少一行代码可能就陷入困境了,所以千万记得下载源代码。
u
unfun
执行:flask\Scripts\pip install sqlalchemy-migrate
出现一大堆红色错误,最后一句提示是:flask\Scripts\pip install sqlalchemy-migrate
请问该什么解决
r
renxiangG
代码少了好多
TaceyWong
TaceyWong
Python代码不缩进不换行,亮瞎眼了
tank064
tank064
额 支持楼主, 不过现在楼主没说用flask哪个版本啊, 用现在的 0.10的 有些代码报错和有警告啊!
V
Vanker
能run么。。
返回顶部
顶部