You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Asynchronous Driver For Python <Tornado and Tulip> #2622
Change feed on 1.13 is very intersting feature.Multi-media-realtime HTML5 projects are getitng very popular these days , and i am building one right now too , a multi-media-webchat .It needs a lot of serverside notifications.
However , RethinkDB still needs async driver for Tornadoweb, like Motor driver by MongoDB does , that is only deal-blocking feature that blocking me changing from Mongo.
I Love ReQL and I really believe that RethinkDB is NoSQL-Done-Right.
Any Pointers on modifying current driver work async would be very good,I would like to contribute. (I am still quite new on Async and Tornado.
Thanks a lot for code example AtnNn.
That would work , but wouldn't that waste everything Tornado tried to avoid?
It won't block Tornado's IOLoop but create new thread for every new requests that needs rethinkdb features.
This will nullify c10k problem that Tornado addressed, solved well.
On asynchronous Mortor ,MongoDB driver equivilant can be done without using threads :
@gen.coroutinedeftail_example():
results= []
collection=db.my_capped_collectioncursor=collection.find(tailable=True, await_data=True)
whileTrue:
ifnotcursor.alive:
now=datetime.datetime.utcnow()
# While collection is empty, tailable cursor dies immediatelyyieldgen.Task(loop.add_timeout, datetime.timedelta(seconds=1)) ##Giving Control back to tornado IOLoop cursor=collection.find(tailable=True, await_data=True) ##<< This will block on normal Pymongo Driverif (yieldcursor.fetch_next):
results.append(cursor.next_object())
printresults
His approach is detailed on this video and slide , and should be able to apply to any Blocking NetworkIO drivers without much modification - Thats what i am talking about :) .
@v3ss0n -- thanks for chiming in. I'm moving this to backlog for now because there are much more pressing issues to take care of first, but I agree this would be valuable. As a data point, at least 5 people (may be more) have asked me for this.
I can't promise when we'll get to it, but I can say with almost complete certainty that there will be support for this eventually.
I am now seriously thinking about writing Async Tornado driver for RethinkDB after liking the changefeeds compare to tailable_cursors of MongoDB.
With changefeed , we can listen for Updates (Like Vote Up/Down) which is quite nice. Its not possible for MongoDB unless you hack into oplog. @tonich-sh , i saw re-writing RethinkDB client in twisted , but does it really necessary?
Current client is too mixed with socket code but twisted's protocols is an abstraction. So i went on easiest way... I made it simple and left only the asynchronous logic.
I tried two approaches about a month ago, threading & asyncio (Python3). Unfortunately, I don't have the time to make anything more than a hack, but I think the asyncio approach is promising seeing as it's in the standard library.
Hi I'm just evaluating rethinkDB at this point for use in a new project. Having support for an asynchronous tornado driver would be very compelling for me. Out of the box support for a python api that mirrors the node/javascript API (using generators/coroutines) would be really great.
We're going to consider different options (including Tornado and Python 3 asyncio) for making changefeeds work better in Python as part of #3298. This will happen very soon.
I'm not sure yet to what degree we are going to convert the rest of the driver (apart of changefeeds) to an asynchronous interface.
Ideally the outcome would be to refactor the python code to be event loop agnostic. The same "protocol" code reused in event loop drivers so their feature compatibility is ensured. I feel I have to point this out because unfortunately few libraries are written this way. I dont want to see a future where I'll be installing with pip install rethinkdb-twisted in one codebase and pip install rethinkdb-asyncio in another.
The Autobahn code is structured so if/when people need to use the protocol with some other unsupported event loop, they just have to rewrite the much smaller driver code to use their event loop.
In the case of rethinkdb there would be an additional 'synchronous' driver branch.
I think the cleanest way to get the driver to run on both Python 2 & 3 would be to use Tornado. Tornado coroutines are very similar to Asyncio's and are also compatible with Asyncio's event loop.
@danielmewes, I just tested this and it isn't the expected behavior (this is my fault due to some of the cursor changes in the refactor). yield future will raise a StopIteration exception once it is past the end of the cursor. Unfortunately, if the user doesn't catch this, it interacts poorly with Tornado, which assumes the StopIteration means that the coroutine has finished.
Note in Motor, you can create the cursor without a yield since it hasn't begun I/O yet, just stored the query in a MotorCursor object. Only on the first yield cursor.fetch_next do we send the query to the server and get the first batch:
Also, I chose the method name next_object instead of next to avoid interacting with Python's standard iterator protocol in any unexpected way, since a MotorCursor cannot act like a standard iterator:
Thanks @ajdavis .
For RethinkDB we need to yield on creating the cursor because we don't know whether a given query actually returns one before getting the first response from the server (some queries return a single value, which we handle differently).
Good point about the incompatibility with the iterator interface.
We could certainly use a special next function for Tornado cursors (not sure how we would call it). I can't tell whether it's important enough to warrant the separate function though.
I wonder how exactly a script fails if it tries to use a Tornado cursor as an iterator. I'll try that later.
@danielmewes, it's would be fine to iterate over a TornadoCursor, as long as you didn't do it eagerly (you would end up with an infinite loop that would probably be OOM-killed), and as far as I can tell, we can't safely do a comprehension like arr = [(yield x) for x in cursor if (yield cursor.fetch_next())]. Taking this into account, we should probably remove iteration from the TornadoCursor implementation.
con=yieldconncurs=yieldevt.run(con)
messages= []
while (yieldcurs.fetch_next()):
item=yieldcurs.next()
messages.append(item)
But i have a few other questions.
Right now Insert performance is not good with async , it takes 200-400 ms , locally , small document of < 2KB each (chat messages).
take a look at this code , i may be doing something wrong:
importloggingimporttornado.escapeimporttornado.ioloopimporttornado.webimportos.pathimportuuidimportrethinkdbasrfromtornado.concurrentimportFuturefromtornadoimportgenfromtornado.optionsimportdefine, options, parse_command_liner.set_loop_type("tornado")
define("port", default=8080, help="run on the given port", type=int)
define("debug", default=False, help="run in debug mode")
conn=r.connect("localhost")
evt=r.db("rechat").table("events")
# Making this a non-singleton is left as an exercise for the reader.classMainHandler(tornado.web.RequestHandler):
@gen.coroutinedefget(self):
con=yieldconncurs=yieldevt.run(con)
messages= []
while (yieldcurs.fetch_next()):
item=yieldcurs.next()
messages.append(item)
self.render("index.html", messages=messages)
classMessageNewHandler(tornado.web.RequestHandler):
@gen.coroutinedefpost(self):
con=yieldconnmessage= {
"body": self.get_argument("body")
}
# to_basestring is necessary for Python 3's json encoder,# which doesn't accept byte strings.messages= (yieldevt.insert(message).run(con))
message['id'] =messages['generated_keys'][0]
message["html"] =tornado.escape.to_basestring(
self.render_string("message.html", message=message))
ifself.get_argument("next", None):
self.redirect(self.get_argument("next"))
else:
self.write(message)
@v3ss0n I can't see anything obviously wrong about your insert code.
Which revision of the RethinkDB repository are you on ($ git status)? I wonder if you might be affected by #3998. It's closed in the latest revision which you should get through git pull.
@v3ss0n Both branches should be ok. The commit you mentioned actually includes the fix for that issue. So something else must be going on. I opened #4007 for further investigation into this.
Activity
AtnNn commentedon Jun 28, 2014
@v3ss0n Thanks for opening an issue. With the current driver you can use threads to perform asynchronous queries. Something like this should work:
A Python driver with an async API would be better.
v3ss0n commentedon Jun 29, 2014
Thanks a lot for code example AtnNn.
That would work , but wouldn't that waste everything Tornado tried to avoid?
It won't block Tornado's IOLoop but create new thread for every new requests that needs rethinkdb features.
This will nullify c10k problem that Tornado addressed, solved well.
On asynchronous Mortor ,MongoDB driver equivilant can be done without using threads :
Motor driver uses Greenlets to address this problem, without modifying any line of code of mongodb's PyMongo Driver, very interesting approach.
https://github.com/mongodb/motor/blob/master/motor/__init__.py (just over 2600 lines of code).
His approach is detailed on this video and slide , and should be able to apply to any Blocking NetworkIO drivers without much modification - Thats what i am talking about :) .
http://emptysqua.re/blog/video-slides-and-code-about-async-python-and-mongodb/
https://speakerdeck.com/mongodb/asynchronous-mongodb-with-python-and-tornado-a-jesse-jiryu-davis-python-evangelist
It will be very good feature for rethinkdb to have it build in. I will also look into rethinkdb's python driver when i get time.
coffeemug commentedon Jul 2, 2014
@v3ss0n -- thanks for chiming in. I'm moving this to backlog for now because there are much more pressing issues to take care of first, but I agree this would be valuable. As a data point, at least 5 people (may be more) have asked me for this.
I can't promise when we'll get to it, but I can say with almost complete certainty that there will be support for this eventually.
tonich-sh commentedon Sep 23, 2014
I wrote a twisted connector for python driver. It may help... https://github.com/tonich-sh/rethinkdb-twisted.git
v3ss0n commentedon Sep 23, 2014
Thanks , looking into it!
v3ss0n commentedon Oct 26, 2014
I am now seriously thinking about writing Async Tornado driver for RethinkDB after liking the changefeeds compare to tailable_cursors of MongoDB.
With changefeed , we can listen for Updates (Like Vote Up/Down) which is quite nice. Its not possible for MongoDB unless you hack into oplog.
@tonich-sh , i saw re-writing RethinkDB client in twisted , but does it really necessary?
tonich-sh commentedon Oct 26, 2014
Current client is too mixed with socket code but twisted's protocols is an abstraction. So i went on easiest way... I made it simple and left only the asynchronous logic.
csytan commentedon Oct 26, 2014
I tried two approaches about a month ago, threading & asyncio (Python3). Unfortunately, I don't have the time to make anything more than a hack, but I think the asyncio approach is promising seeing as it's in the standard library.
Maybe this will be helpful to someone:
https://github.com/csytan/rethinkdb/commits/next
v3ss0n commentedon Oct 27, 2014
@tonich-sh , so i think going gevent approach (the way motor did with mongodb ) will be easy for current client .
@csytan thanks a lot chris , i am looking into it.
EDIT: Very interesting approach , can be switched with tornado ioloop.
kzahel commentedon Jan 27, 2015
Hi I'm just evaluating rethinkDB at this point for use in a new project. Having support for an asynchronous tornado driver would be very compelling for me. Out of the box support for a python api that mirrors the node/javascript API (using generators/coroutines) would be really great.
danielmewes commentedon Jan 27, 2015
We're going to consider different options (including Tornado and Python 3 asyncio) for making changefeeds work better in Python as part of #3298. This will happen very soon.
I'm not sure yet to what degree we are going to convert the rest of the driver (apart of changefeeds) to an asynchronous interface.
techdragon commentedon Feb 15, 2015
Ideally the outcome would be to refactor the python code to be event loop agnostic. The same "protocol" code reused in event loop drivers so their feature compatibility is ensured. I feel I have to point this out because unfortunately few libraries are written this way. I dont want to see a future where I'll be installing with
pip install rethinkdb-twistedin one codebase andpip install rethinkdb-asyncioin another.The Autobahn project has a great structure for this kind of thing, https://github.com/tavendo/AutobahnPython/
The Autobahn code is structured so if/when people need to use the protocol with some other unsupported event loop, they just have to rewrite the much smaller driver code to use their event loop.
In the case of rethinkdb there would be an additional 'synchronous' driver branch.
csytan commentedon Feb 15, 2015
I think the cleanest way to get the driver to run on both Python 2 & 3 would be to use Tornado. Tornado coroutines are very similar to Asyncio's and are also compatible with Asyncio's event loop.
62 remaining items
Tryneus commentedon Mar 24, 2015
@danielmewes, I just tested this and it isn't the expected behavior (this is my fault due to some of the cursor changes in the refactor).
yield futurewill raise aStopIterationexception once it is past the end of the cursor. Unfortunately, if the user doesn't catch this, it interacts poorly with Tornado, which assumes theStopIterationmeans that the coroutine has finished.Opened #3974 for this issue.
Tryneus commentedon Mar 24, 2015
So based on my suggestion in #3974, that loop would throw
RqlCursorEmptyafter the end of the cursor.danielmewes commentedon Mar 24, 2015
Having to handle the
RqlCursorEmptyexception for every loop over a cursor sounds a little annoying.Should we add a
fetch_nextlike in Motor to guarantee that the next call tonextdoesn't throw?Tryneus commentedon Mar 24, 2015
@danielmewes, I think that would be useful, I'll do it alongside #3974.
danielmewes commentedon Mar 24, 2015
👍
ajdavis commentedon Mar 24, 2015
Note in Motor, you can create the cursor without a yield since it hasn't begun I/O yet, just stored the query in a MotorCursor object. Only on the first
yield cursor.fetch_nextdo we send the query to the server and get the first batch:http://motor.readthedocs.org/en/stable/api/motor_cursor.html#motor.MotorCursor.fetch_next
Also, I chose the method name
next_objectinstead ofnextto avoid interacting with Python's standard iterator protocol in any unexpected way, since a MotorCursor cannot act like a standard iterator:https://docs.python.org/2/library/stdtypes.html#iterator-types
danielmewes commentedon Mar 24, 2015
Thanks @ajdavis .
For RethinkDB we need to yield on creating the cursor because we don't know whether a given query actually returns one before getting the first response from the server (some queries return a single value, which we handle differently).
Good point about the incompatibility with the iterator interface.
We could certainly use a special
nextfunction for Tornado cursors (not sure how we would call it). I can't tell whether it's important enough to warrant the separate function though.I wonder how exactly a script fails if it tries to use a Tornado cursor as an iterator. I'll try that later.
Tryneus commentedon Mar 25, 2015
@danielmewes, it's would be fine to iterate over a
TornadoCursor, as long as you didn't do it eagerly (you would end up with an infinite loop that would probably be OOM-killed), and as far as I can tell, we can't safely do a comprehension likearr = [(yield x) for x in cursor if (yield cursor.fetch_next())]. Taking this into account, we should probably remove iteration from theTornadoCursorimplementation.v3ss0n commentedon Apr 2, 2015
No problem now , this code works well.
But i have a few other questions.
Right now Insert performance is not good with async , it takes 200-400 ms , locally , small document of < 2KB each (chat messages).
take a look at this code , i may be doing something wrong:
danielmewes commentedon Apr 2, 2015
@v3ss0n I can't see anything obviously wrong about your insert code.
Which revision of the RethinkDB repository are you on (
$ git status)? I wonder if you might be affected by #3998. It's closed in the latest revision which you should get throughgit pull.v3ss0n commentedon Apr 2, 2015
i am at 01fa526
v3ss0n commentedon Apr 2, 2015
what branch i should pool? next or v2.0x ?
danielmewes commentedon Apr 2, 2015
@v3ss0n Both branches should be ok. The commit you mentioned actually includes the fix for that issue. So something else must be going on. I opened #4007 for further investigation into this.
shivekkhurana commentedon Jun 25, 2017
After reviewing a lot of amazing work by David Beazley (https://github.com/dabeaz), and with the improvements in async python (mainly introduction of
async/awaitkeyword and inclusion of asyncio into the stdlib), we can do this very easily.I have created a gist here with a working example
https://gist.github.com/shivekkhurana/1de00e1e54c36d250a7f19905fe133b9
It gives a simple structure to listen to multiple change feeds asynchronously (tested on python 3.6)
Hope it helps.