Created
August 15, 2018 13:45
-
-
Save zhangkaizhao/089f257b8d1856fb7c1308ccd09bab16 to your computer and use it in GitHub Desktop.
Global async Redis connection in Tornado web demo
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import asyncio_redis | |
import tornado.locks | |
import tornado.web | |
from tornado.options import define, options | |
define("port", default=8888, help="run on the given port", type=int) | |
class AsyncRedisConnectionContextManager: | |
def __init__(self, *args, **kwargs): | |
self.args = args | |
self.kwargs = kwargs | |
async def __aenter__(self): | |
self.rdb = await asyncio_redis.Connection.create(*self.args, | |
**self.kwargs) | |
return self.rdb | |
async def __aexit__(self, exc_type, exc, tb): | |
self.rdb.close() | |
class Application(tornado.web.Application): | |
def __init__(self, rdb): | |
self.rdb = rdb | |
handlers = [ | |
(r"/", MainHandler), | |
] | |
settings = { | |
'debug': True, | |
} | |
super(Application, self).__init__(handlers, **settings) | |
class MainHandler(tornado.web.RequestHandler): | |
async def get(self): | |
print('get you!') | |
connection = self.application.rdb | |
# subscriber = await connection.start_subscribe() | |
# await subscriber.subscribe(['chan1']) | |
print(id(connection)) | |
keys = await connection.keys('*') | |
print(f'keys: {keys}') | |
# _ = await connection.set('hello', 'world') | |
# world = await connection.get('hello') | |
# print(f'hello: {world}') | |
cnt = await connection.incr('cnt') | |
self.write("Hello, World, {}".format(cnt)) | |
# try: | |
# hit = await connection.brpop(["zzz"], timeout=60) | |
# except asyncio_redis.TimeoutError as _: | |
# hit = None | |
# # hit = await subscriber.next_published() | |
# self.write("Hello, World, {}".format(hit)) | |
async def main(): | |
tornado.options.parse_command_line() | |
# Create the global connection. | |
async with AsyncRedisConnectionContextManager('127.0.0.1', 6379) as rdb: | |
app = Application(rdb) | |
app.listen(options.port) | |
# In this demo the server will simply run until interrupted | |
# with Ctrl-C, but if you want to shut down more gracefully, | |
# call shutdown_event.set(). | |
shutdown_event = tornado.locks.Event() | |
await shutdown_event.wait() | |
if __name__ == "__main__": | |
tornado.ioloop.IOLoop.current().run_sync(main) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# By panfei via CPyUG 2018-08-15 | |
import tornado.web | |
import asyncio_redis | |
class MainHandler(tornado.web.RequestHandler): | |
@classmethod | |
async def redis_connection(cls): | |
if not hasattr(cls, '_redis_connection'): | |
cls._redis_connection = await asyncio_redis.Connection.create('127.0.0.1', 6379) | |
return cls._redis_connection | |
async def get(self): | |
print('get you!') | |
connection: asyncio_redis.Connection = await MainHandler.redis_connection() | |
# subscriber = await connection.start_subscribe() | |
# await subscriber.subscribe(['chan1']) | |
print(id(connection)) | |
try: | |
hit = await connection.brpop(["zzz"], timeout=60) | |
except asyncio_redis.TimeoutError as _: | |
hit = None | |
finally: | |
connection.close() | |
# hit = await subscriber.next_published() | |
self.write("Hello, World, {}".format(hit)) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
[[source]] | |
url = "https://pypi.org/simple" | |
verify_ssl = true | |
name = "pypi" | |
[packages] | |
tornado = "==5.1" | |
asyncio-redis = "==0.15.1" | |
[dev-packages] | |
[requires] | |
python_version = "3.7" |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{ | |
"_meta": { | |
"hash": { | |
"sha256": "b5211f547712f2a34691344cea49441d55cf6139db38d661331ba62f181d5488" | |
}, | |
"pipfile-spec": 6, | |
"requires": { | |
"python_version": "3.7" | |
}, | |
"sources": [ | |
{ | |
"name": "pypi", | |
"url": "https://pypi.org/simple", | |
"verify_ssl": true | |
} | |
] | |
}, | |
"default": { | |
"asyncio-redis": { | |
"hashes": [ | |
"sha256:067dbc251ab84d6e53ef8b33dbfd8afd62987ab08f72ca922f6870c96be53b54", | |
"sha256:f49e2c6626f3fcfddb478ee1d01f0335e22b6656add274e8a88fcdec9bd78745" | |
], | |
"index": "pypi", | |
"version": "==0.15.1" | |
}, | |
"tornado": { | |
"hashes": [ | |
"sha256:1c0816fc32b7d31b98781bd8ebc7a9726d7dce67407dc353a2e66e697e138448", | |
"sha256:4f66a2172cb947387193ca4c2c3e19131f1c70fa8be470ddbbd9317fd0801582", | |
"sha256:5327ba1a6c694e0149e7d9126426b3704b1d9d520852a3e4aa9fc8fe989e4046", | |
"sha256:6a7e8657618268bb007646b9eae7661d0b57f13efc94faa33cd2588eae5912c9", | |
"sha256:a9b14804783a1d77c0bd6c66f7a9b1196cbddfbdf8bceb64683c5ae60bd1ec6f", | |
"sha256:c58757e37c4a3172949c99099d4d5106e4d7b63aa0617f9bb24bfbff712c7866", | |
"sha256:d8984742ce86c0855cccecd5c6f54a9f7532c983947cff06f3a0e2115b47f85c" | |
], | |
"index": "pypi", | |
"version": "==5.1" | |
} | |
}, | |
"develop": {} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment