Tornado web简介
[b]Thread-safety notes: [/b] [quote] In general, methods on RequestHandler and elsewhere in tornado are not thread-safe. In particular, methods such as write(), finish(), and flush() must only be called from the main thread. If you use multiple threads it is important to use IOLoop.add_callback to transfer control back to the main thread before finishing the request.[/quote] [b]Collections: [/b] [list] [*]1、functools.partial用法 [*]2、tornado.web.asynchronous用法 [/list] [quote]functools.partial(func[,*args][, **keywords])Return a new partial object which when called will behave like func called with the positional arguments args and keyword arguments keywords. If more arguments are supplied to the call, they are appended to args. If additional keyword arguments are supplied, they extend and override keywords.[/quote] For example, partial() can be used to create a callable that behaves like the int() function where the base argument defaults to two [code="python"] >>> import functors >>> f=functools.partial(int, base=2) >>> f.args () >>> f.func >>> f.keywords {'base': 2}[/code] [code="python"] >>>from functools imports partial >>>basetwo = partial(int, base=2) >>>basetwo('10010') 18[/code] 一般,函数在执行时,需要带上所必要的参数进行调用。然后,有时参数可以在函数被调用前提前获知。这种情况下,一个函数有一个或多个参数预先就能用上,一遍函数能用更少的参数进行调用。 [b]Decorators: [/b] [b]tornado.web.asynchronous(method) [/b]Wrap request handler methods with this if they are asynchronous. [quote]If this decorator is given, the response is not finished when the method returns. It is up to the request handler to call self.finish() to finish the HTTP request. Without this decorator, the request is automatically finished when the get() or post() method returns.[/quote] [code="python"] class MyRequestHandler(web.RequestHandler): @web.asynchronous def get(self): http = httpclient.AsyncHTTPClient() http.fetch("http://friendfeed.com/", self._on_download) def _on_download(self, response): self.write("Downloaded!") self.finish() [/code] 示例: [code="python"] #!/usr/bin/env python #-*-coding:utf-8-*- import tornado import functors import tornado.httpserver from tornado.web import RequestHandler from tornado.httpclient import AsyncHTTPClient class AsyncHandler(RequestHandler): @tornado.web.asynchronous def get(self): http_client = AsyncHTTPClient() http_client.fetch("http://www.google.com", callback=functools.partial(self.on_fetch,'love it')) def on_fetch(self, param, response): print response.body print param self.write('This is a demo.') self.finish() settings = { "debug": True, } application = tornado.web.Application([ (r"/", AsyncHandler), ], **settings) if __name__ == "__main__": http_server = tornado.httpserver.HTTPServer(application) http_server.listen(8088) tornado.ioloop.IOLoop.instance().start() [/code] [b]tornado.web.authenticated(method) [/b] [quote]Decorate methods with this to require that the user be logged in. [/quote] [b]tornado.web.addslash(method) [/b] [quote]Use this decorator to add a missing trailing slash to the request path. For example, a request to ‘/foo’ would redirect to ‘/foo/’ with this decorator. Your request handler mapping should use a regular expression like r’/foo/?’ in conjunction with using the decorator.[/quote] [b]tornado.web.removeslash(method) [/b] [quote]Use this decorator to remove trailing slashes from the request path. For example, a request to '/foo/' would redirect to '/foo' with this decorator. Your request handler mapping should use a regular expression like r'/foo/*'in conjunction with using the decorator.[/quote] [b]Others: [/b] 一、@property可以把function变成属性。 [quote]property([fget[,fset[,fdel[,doc]]]])Return a property attribute for new-style classes (classes that derive from object).[/quote] [code="java"]If given, doc will be the docstring of the property attribute. Otherwise, the property will copy fget‘s docstring (if it exists). This makes it possible to create read-only properties easily using property() as a decorator:[/code] 示例: [code="python"] class Person(object): def __init__(self): self._name = '' def fget(self): print "Getting: %s" % self._name return self._name def fset(self, value): print "Setting: %s" % value self._name = value.title() def fdel(self): print "Deleting: %s" %self._name del self._name name = property(fget, fset, fdel, "I'm the property.") p=Person() p.name='Eric Su' p.name del p.name[/code] [quote]A property object has getter, setter, and deleter methods usable as decorators that create a copy of the property with the corresponding accessor function set to the decorated function. [/quote] Descriptors: [code="python"] class Person(object): def __init__(self): self._name = '' @property def name(self): print "Getting: %s" % self._name return self._name @name.setter def name(self, value): print "Setting: %s" % value self._name = value.title() @name.deleter def name(self): print "Deleting: %s" % self._name del self._name p=Person() p.name='Eric Su' p.name del p.name[/code] 有关另外异步调用tornado.gen以及generator的用法会在下一篇进行整理。参考资料: http://joy2everyone.iteye.com/blog/910950 http://docs.python.org/2/library/functools.html http://www.tornadoweb.org/documentation/web.html http://docs.python.org/2/library/functions.html#property http://www.ibm.com/developerworks/library/os-pythondescriptors/index.html http://stackoverflow.com/questions/6618002/python-property-versus-getters-and-setters http://stackoverflow.com/questions/3252228/python-why-is-functools-partial-necessary