2013-04-11 57 views
0

我正在使用龍捲風框架和我的所有功能已被寫入同步。我將如何使這些異步?如何使用回調將同步函數轉換爲python中的異步函數?

class AuthLoginHandler(BaseHandler): 
    @tornado.web.asynchronous 
    def get(self): 

     self.render("login.html") 

    def post(self): 
     username = self.get_argument("UserName",strip = True) 
     password = self.get_argument("Password",strip = True) 
     user = auth_actions.login(username,password) 
     if not user: 
      self.redirect("/auth/login") 
      return 

     #user = user_actions.get_my_data(self.db,user['_id']) 

     self.set_secure_cookie("userdata", tornado.escape.json_encode(dumps(user.to_mongo()))) 
     self.redirect("/") 


def login(username,password,callback=None): 
    m = hashlib.md5() 
    m.update(password) 
    hashed = m.hexdigest() 
    login = User.objects(UserName=username.lower(),Password=hashed).exclude("Password","Wall","FriendsRequested","Friends","FriendsRequesting") 
    if login.first() is None: 
     login = User.objects(Email=username.lower(),Password=hashed).exclude("Password","Wall","FriendsRequested","Friends","FriendsRequesting") 
     if login.first() is None: 
      return None 
    logger.info(username + " has logged in") 
    if callback != None: 
     return callback(login.first()) 

    return login.first() 

回答

2

正如安迪提到的那樣,你將需要一個單獨的線程。以下代碼使用tornado-gengenerator - coroutine方法。 另請注意run_asyncdecorator將自己的函數包裝在自己的線程中。

import tornado.ioloop 
import tornado.web 
import tornado.gen 
import time 
from threading import Thread 
from functools import wraps 

def run_async(func): 
    @wraps(func) 
    def async_func(*args, **kwargs): 
    func_hl = Thread(target = func, args = args, kwargs = kwargs) 
    func_hl.start() 
    return func_hl 

    return async_func 

@run_async 
def login(username,password,callback=None): 
    m = hashlib.md5() 
    m.update(password) 
    hashed = m.hexdigest() 
    login = User.objects(UserName=username.lower(),Password=hashed).exclude("Password","Wall","FriendsRequested","Friends","FriendsRequesting") 
    if login.first() is None: 
    login = User.objects(Email=username.lower(),Password=hashed).exclude("Password","Wall","FriendsRequested","Friends","FriendsRequesting") 
    if login.first() is None: 
     return None 
    logger.info(username + " has logged in") 
    if callback != None: 
    return callback(login.first()) 
    return login.first() 


class AuthLoginHandler(BaseHandler): 
    @tornado.web.asynchronous 
    def get(self): 
    self.render("login.html") 

    @tornado.web.asynchronous 
    @tornado.gen.coroutine 
    def post(self): 
    username = self.get_argument("UserName",strip = True) 
    password = self.get_argument("Password",strip = True) 
    user = yield tornado.gen.Task(auth_actions.login, username, password) 
    if not user: 
     self.redirect("/auth/login") 
     return 
    self.set_secure_cookie("userdata", tornado.escape.json_encode(dumps(user.to_mongo()))) 
    self.redirect("/")