Created
May 22, 2012 08:57
-
-
Save rossomax/2767703 to your computer and use it in GitHub Desktop.
Asynchronous programming with bottle and gevent
This file contains hidden or 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
| #!/usr/bin/env python | |
| # -*- coding:UTF-8 -*- | |
| # system libraries | |
| import sys | |
| import codecs | |
| # non standard libraries | |
| import bottle | |
| from bottle import get, post | |
| import gevent | |
| from gevent import queue, monkey | |
| monkey.patch_all() | |
| @get('/') | |
| def main(): | |
| return ''' | |
| <html lang="ja"><head> | |
| <meta charset="utf-8"> | |
| <meta http-equiv="Content-Script-Type" content="text/javascript"> | |
| <body> | |
| <button onclick="go();">go!</button> | |
| <div id="console" style="width:640;height:360;border:1px solid gray;overflow-y:scroll;">Click Go Button<br/></div> | |
| <script><!-- | |
| function go() { | |
| var console = document.getElementById("console"); | |
| var xhr = window.XMLHttpRequest ? new XMLHttpRequest() : (function() { | |
| try { return new ActiveXObject("Msxml2.XMLHTTP"); } | |
| catch(e) { return new ActiveXObject("Microsoft.XMLHTTP"); } | |
| })(); | |
| xhr.open('GET', '/ajax', true); | |
| xhr.onreadystatechange = function() { | |
| var console = document.getElementById("console") | |
| if (xhr.readyState == 3) { | |
| if(xhr.status == 200 || xhr.status == 201) { | |
| console.innerHTML = xhr.responseText + "*"; | |
| } | |
| } else if (xhr.readyState == 4) { | |
| if(xhr.status == 200 || xhr.status == 201) { | |
| console.innerHTML = xhr.responseText; | |
| } | |
| } | |
| }; | |
| xhr.send(null); | |
| } | |
| // --></script> | |
| </body></html> | |
| ''' | |
| def worker(q): | |
| counter = 0 | |
| q.put('START ') | |
| while counter < 100: | |
| gevent.sleep(1) | |
| q.put('{}{:02d} '.format('<br />' if counter % 10 == 0 else '', counter)) | |
| counter += 1 | |
| q.put('<br />END ') | |
| q.put(StopIteration) | |
| @get('/ajax') | |
| def ajax(): | |
| body = queue.Queue() | |
| gevent.Greenlet.spawn(worker, body) | |
| return body | |
| if __name__ == '__main__': | |
| bottle.debug=(True) | |
| bottle.run(host='localhost', port=8080, server='gevent') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment