tornado作为鼎鼎大名的web异步框架,用来作为高性能服务器以及web框架都是首选。自从python3.4加入了asyncio原生协程后,tornado的最新版本也开始使用了原生的协程。定义协程函数的时候就很简单了,也可以像sanic一样使用async def了。

  1. class LoginHandler(RequestHandler):
  2. async def post(self, *args, **kwargs):
  3. ...
  4. pass

一般的web项目都会有登陆的功能,这就涉及到了登陆验证,在做这一部分功能的时候,我使用的是 jwt -- json web token的方法验证是否登陆。当然也可以使用类似于django的session验证。各自均有优缺点。

通常需要验证是否登陆的模块很多,一般都会写一个登陆验证装饰器,tornado实现了登陆验证装饰器 :

  1. def authenticated(method):
  2. """Decorate methods with this to require that the user be logged in.
  3.  
  4. If the user is not logged in, they will be redirected to the configured
  5. `login url <RequestHandler.get_login_url>`.
  6.  
  7. If you configure a login url with a query parameter, Tornado will
  8. assume you know what you're doing and use it as-is. If not, it
  9. will add a `next` parameter so the login page knows where to send
  10. you once you're logged in.
  11. """
  12. @functools.wraps(method)
  13. def wrapper(self, *args, **kwargs):
  14. if not self.current_user:
  15. if self.request.method in ("GET", "HEAD"):
  16. url = self.get_login_url()
  17. if "?" not in url:
  18. if urlparse.urlsplit(url).scheme:
  19. # if login url is absolute, make next absolute too
  20. next_url = self.request.full_url()
  21. else:
  22. next_url = self.request.uri
  23. url += "?" + urlencode(dict(next=next_url))
  24. self.redirect(url)
  25. return
  26. raise HTTPError(403)
  27. return method(self, *args, **kwargs)
  28. return wrapper

method(self,*args,**kwargs)即为要装饰的函数。但是如果 像上面定义的post方法 async def post(self, *args, **kwargs),作为一个协程函数,就不能再使用这个装饰器了,就需要改写一下这个装饰器。def authenticated_async(method):

初始化app的过程:

  1. import tornado
  2. from peewee_async import Manager
  3.  
  4. from YourApp.urls import urlpattern
  5. from YourApp.settings import settings, database
  6.  
  7. if __name__ == "__main__":
  8.  
  9. #集成json到wtforms
  10. import wtforms_json
  11. wtforms_json.init()
  12.  
  13. app = web.Application(urlpattern, debug=True, **settings)
  14. app.listen(80)
  15.  
  16. objects = Manager(database)
  17. database.set_allow_sync(False)
  18. app.objects = objects
  19.  
  20. tornado.ioloop.IOLoop.current().start()

登陆装饰器改写

  1. @functools.wraps(method)
  2. async def wrapper(self, *args, **kwargs):
  3. tsessionid = self.request.headers.get("tsessionid", None)
  4. if tsessionid:
  5. try:
  6. send_data = jwt.decode(tsessionid, self.settings["secret_key"], leeway=self.settings["jwt_expire"], options={"verify_exp": True})
  7. user_id = send_data["id"]
  8. # User 的model类,根据实际情况调整
  9. #从数据库中获取到user并设置给_current_user
  10. try:
  11. user = await self.application.objects.get(User, id=user_id)
  12. self._current_user = user
  13. # 协程的调用方式
  14. await method(self, *args, **kwargs)
  15. except User.DoesNotExist as e:
  16. self.set_status(401)
  17. except jwt.ExpiredSignatureError as e: # 验证jwt 是否过期
  18. self.set_status(401)
  19. else:
  20. self.set_status(401)
  21. self.finish({})
  22. return wrapper

  

tornado登陆装饰器的更多相关文章

  1. tornado利用装饰器记录每个http请求

    python利用装饰器记录每个http请求 设置装饰器 from functools import wraps from datetime import datetime ""&q ...

  2. 动态页面的登陆——装饰器应用<代码>

    log_status = False f = open("info", "r", encoding="utf8") source = f.r ...

  3. python之路之装饰器

    一 装饰器进化之路1) import time def index(): start_time=time.time() time.sleep() print('welcome to index wor ...

  4. tornado之用户验证装饰器

    authenticated装饰器 为了使用Tornado的认证功能,我们需要对登录用户标记具体的处理函数.我们可以使用@tornado.web.authenticated装饰器完成它.当我们使用这个装 ...

  5. 抽屉之Tornado实战(9)--装饰器实现用户登录状态验证

    当然今天讲的验证,不只Tornado会用,以后用到web框架都会用到,最常见的场景就是只有用户登陆了才能执行某些操作,所以在执行这些操作前要先做登陆状态的验证. 比如:点赞,发布,评论等需要验证,都需 ...

  6. 装饰器实现session登陆 验证功能

    装饰器 登陆验证功能 1.装饰器模板 from django.shortcuts import render, redirect, HttpResponse from django.conf impo ...

  7. (26)基于cookie的登陆认证(写入cookie、删除cookie、登陆后所有域下的网页都可访问、登陆成功跳转至用户开始访问的页面、使用装饰器完成所有页面的登陆认证)

    获取cookie request.COOKIES['key'] request.get_signed_cookie(key, default=RAISE_ERROR, salt='', max_age ...

  8. python基础学习1-双层装饰器(实现登陆注册)

    LOGIN_USER = {"IsLogin":False} def check_login(func): #检查登陆的装饰器 def inner(*args,**kwargs): ...

  9. flask笔记(三)Flask 添加登陆验证装饰器报错,及解析

    Flask 添加登陆验证装饰器报错,及解析 写这个之前,是想到一个需求,这个是关于之前写Flask笔记(二)中的一个知识点,路由相关 需求为 : 有一些页面必须是登陆之后才能访问的,比如Shoppin ...

随机推荐

  1. SqlServer在视图上创建索引

    在视图上创建索引需要三个条件: 一.视图必须绑定到架构. 要做到这点,在 CREATE VIEW 语句中,必须加上 WITH SCHEMABINDING,如果是使用企业管理器,则在设计界面的空白处点击 ...

  2. python BitTornado P2P分发大文件

    P2P分发大文件思路 1.将软件包生成种子文件 2.通过saltstack将种子文件分发至每台服务器 3.每台服务器进行种子下载 推荐使用Twitter开源的murder.Twitter用它来分发大文 ...

  3. Codeforces 923 B. Producing Snow

    http://codeforces.com/contest/923/problem/B 题意: 有n天,每天产生一堆体积为Vi的雪,每天所有雪堆体积减少Ti 当某一堆剩余体积vi<=Ti时,体积 ...

  4. 使用 git 托管代码

    1. 下载安装好 git 客户端 2. 找一个家代码托管平台 我用 coding.net,注册个账号,建一个空项目 然后打开安装好的 git bash 客户端,使用 git clone 命令克隆下远程 ...

  5. Here’s just a fraction of what you can do with linear algebra

    Here’s just a fraction of what you can do with linear algebra The next time someone wonders what the ...

  6. Metasploit输出重定向到文件

    Metasploit是我们经常会使用到的神器,但是运行exploit/run无法保存输出信息,查看不是很方便. 现在可以使用spool来保存输出信息: Metasploit Framework Con ...

  7. flask_sqlalchemy的使用

    第一配置文件 # coding:utf-8 DIALECT = 'mysql' DRIVER = 'pymysql' USERNAME = 'root' PASSWORD = ' HOST = '12 ...

  8. python代码在IDE下调试设置命令行参数

    带命令行参数的代码在IDE下调试,需要把参数赋值,本文mark一下具体的命令行参数在代码中赋值方法. if __name__ == "__main__": sys.argv = [ ...

  9. start-stop-daemon 启动停止系统守护进程

    1.start-stop-daemon start-stop-daemon是一个Debian体系里的一个守护进程管理软件,可以用指定的用户启停软件.CentOS有自己的daemon()机制(在/etc ...

  10. 【译】EntityFramework6与EntityFrameworkCore的区别

    EntityFramework6 EF6 是一个久经考验的数据库访问技术,发展多年,拥有许多特性,并且成熟稳定.2008年EF作为 .Net 3.5 Sp1 和Visual Studio 2008 S ...