Created
July 19, 2014 03:59
-
-
Save slezica/39d5134b53cf039d3919 to your computer and use it in GitHub Desktop.
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 types, time, functools | |
from twisted.internet import reactor, protocol, threads | |
# --- | |
def async(func): | |
def wrapper(*args, **kwargs): | |
async_continue(func(*args, **kwargs)) | |
functools.update_wrapper(wrapper, func) | |
return wrapper | |
def async_continue(func_generator, prev_result = None): | |
try: | |
func = func_generator.send(prev_result) | |
except StopIteration: | |
return | |
deferred = threads.deferToThread(func) | |
callback = lambda result: async_continue(func_generator, result) | |
deferred.addCallback(callback) | |
def fake_async(func): | |
def wrapper(*args, **kwargs): | |
generator = func(*args, **kwargs) | |
try: | |
subfunc = generator.next() | |
while True: | |
subfunc = generator.send(subfunc()) | |
except StopIteration: | |
return | |
return wrapper | |
# --- | |
class Listing(protocol.Protocol): | |
@async | |
def connectionMade(self): | |
print 'before' | |
yield lambda: time.sleep(1) # every blocking call must instead yield lambda | |
print 'after' | |
self.transport.loseConnection() | |
def main(): | |
factory = protocol.ServerFactory() | |
factory.protocol = Listing | |
reactor.listenTCP(8000, factory) | |
reactor.run() | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment