tornado 整合jinja2 ,xsrf_form_html 的处理

tornado 整合jinja2,在应用到form欲上传数据时,会需要作如下的处理:

看解决方案:

    <form action="/auth/login" method="post">
        用户名: <input type="text" name="username" placeholder="用户名"/>
        密码: <input type="password" name="password" placeholder="密码"/>
        <input type="submit" value="登录" />
        {{ xsrf_form_html()|safe}} 
    </form>
class BaseHandler(tornado.web.RequestHandler):
    def get_current_user(self):
        username = self.get_secure_cookie("username")
        if not username: 
            return None
        return username
        
    def get_context(self):
        self.context = {
               'current_user':self.get_current_user(),
               }
        logging.info(self.xsrf_form_html)
        if config['app']['xsrf_cookies']:
            self.context['xsrf_form_html'] = self.xsrf_form_html
        return self.context
class AuthHandler(BaseHandler):
    def get(self):
        template = jinja_env.get_template('auth/login.html')
        self.write(template.render(self.get_context()))

 

这是我所想到的解决方案,希望能对大家有帮助 。

转载于:https://www.cnblogs.com/yeelone/archive/2012/11/29/2794960.html

`tornado.concurrent.run_on_executor` 是 Tornado 提供的一个装饰器,用于在异步函数中将 CPU 密集型操作转移到线程池中执行,从而避免阻塞 I/O 循环。 具体来说,`run_on_executor` 将一个异步函数转化为一个协程,该协程通过 `concurrent.futures.ThreadPoolExecutor` 的线程池来执行函数中的 CPU 密集型操作。`ThreadPoolExecutor` 是 Python 标准库中的一个线程池实现,可以在 `tornado.concurrent` 模块中以 `Future` 的形式使用。 使用 `run_on_executor` 装饰器可以实现将 CPU 密集型操作从 I/O 循环中分离出来,提高了应用程序的并发性能和响应速度。但是,由于线程池中的线程是有限的,如果使用不当,可能会导致线程池中的线程耗尽,从而影响应用程序的性能。 示例代码: ```python from tornado.concurrent import run_on_executor from concurrent.futures import ThreadPoolExecutor executor = ThreadPoolExecutor() @run_on_executor(executor) async def cpu_bound_task(): # CPU-bound task return async def some_handler(): # I/O-bound task await some_async_io_operation() # CPU-bound task await cpu_bound_task() # I/O-bound task await some_other_async_io_operation() ``` 在上面的代码中,`cpu_bound_task` 函数被装饰为一个协程,并通过 `ThreadPoolExecutor` 在一个线程池中执行。在 `some_handler` 函数中,`cpu_bound_task` 函数被调用,由于它被装饰成了协程,因此不会阻塞 I/O 循环。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值