Last active
August 29, 2015 14:08
-
-
Save Deiru2k/e5ba10caa4749d96c30e to your computer and use it in GitHub Desktop.
Using RethinkDB with tornado
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
from tornado.gen import coroutine | |
from tornado.web import RequestHandler | |
from tornado.web import Application | |
from tornado.ioloop import IOLoop | |
import rethinkdb.net as net | |
import rethinkdb as r | |
connection = r.connect(host='localhost') | |
class BaseHandler(RequestHandler): | |
db = r.db("lsd_dev") | |
c = connection | |
@coroutine | |
def run_query(self, query): | |
""" | |
Run a query against RethinkDB database and yield a result. | |
Convert cursor to list if neccesary | |
:param query: an RQL query. | |
""" | |
result = query.run(self.c, time_format="raw") | |
if isinstance(result, net.Cursor): | |
result = [doc for doc in result] | |
if len(result) == 1: | |
result = result[0] | |
return result | |
class HelloHandler(BaseHandler): | |
@coroutine | |
def get(self, _id): | |
hello = yield self.run_query(self.db.table("worlds").get(_id)) | |
self.write("<html><body><center color=red><h1>Hello, %s</h1></center></body></html>") | |
self.finish() | |
routes = [ | |
(r'/(.*)', HelloHandler) | |
] | |
app = Application( | |
handlers=routes | |
) | |
if __name__ == '__main__': | |
print("Routes:") | |
for route in routes: | |
print("%s -> %s" % (route[0], route[1].__name__)) | |
app.listen(8080) | |
IOLoop.instance().start() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment