tornado使用@tornado.web.authenticated鉴权以后怎么跳转到首页
时间: 2024-05-05 07:15:28 浏览: 10
在使用@tornado.web.authenticated鉴权后,如果用户没有登录,则会自动跳转到登录页面。如果用户已经登录,但是需要跳转到首页,可以使用tornado.web.RequestHandler.redirect方法,将URL重定向到首页。
例如:
```python
import tornado.web
class MainHandler(tornado.web.RequestHandler):
@tornado.web.authenticated
def get(self):
# do something
self.redirect("/")
```
在这个例子中,如果用户已经登录,访问MainHandler时会执行get方法中的代码,然后重定向到首页。如果用户没有登录,则会跳转到登录页面。
相关问题
tornado6 @gen.engine 使用说明
`tornado6` 中的 `@gen.engine` 装饰器可以使函数以协程的方式运行。使用 `@gen.engine` 可以让函数在运行过程中遇到阻塞操作自动挂起,等待操作完成后再继续执行。这使得我们可以编写异步的代码,而不用手动地去管理回调函数。
具体使用方法如下:
1. 导入 `tornado.gen` 模块中的 `engine`。
```python
from tornado.gen import engine
```
2. 在函数上添加 `@gen.engine` 装饰器。
```python
@gen.engine
def my_func(arg1, arg2, callback):
# 函数体
```
3. 在函数中使用 `callback` 参数来传递回调函数。
```python
@gen.engine
def my_func(arg1, arg2, callback):
result = yield some_async_func(arg1, arg2)
callback(result)
```
4. 在函数中使用 `yield` 来挂起函数的执行。
```python
@gen.engine
def my_func(arg1, arg2, callback):
result1 = yield some_async_func(arg1, arg2)
result2 = yield another_async_func(result1)
callback(result2)
```
注意事项:
1. `@gen.engine` 装饰器会将函数转换为协程函数,因此不能使用 `return` 语句返回值,而必须使用回调函数来返回结果。
2. 回调函数的第一个参数应该是结果值。
3. `@gen.engine` 装饰器只能用于 `tornado.gen` 模块中的异步函数,不能用于普通的同步函数。
@tornado.web.asynchronous 版本
`tornado.web.asynchronous`是Tornado的旧版异步装饰器,它已经在Tornado 6.0版本中被废弃,并在Tornado 6.1版本中完全移除。新版异步装饰器是`async def`,它更加简单、清晰,并且支持更多的Python异步库。
如果你要使用旧版异步装饰器,你需要将你的Tornado版本降级到5.1及以下。但是,为了避免不必要的麻烦,建议使用新版异步装饰器。例如:
```python
class MyHandler(tornado.web.RequestHandler):
async def get(self):
result = await some_async_function()
self.write(result)
```
需要注意的是,使用新版异步装饰器需要Python 3.5或以上的版本。