"""This is a simple example of running a wsgi application with evy. For a more fully-featured server which supports multiple processes, multiple threads, and graceful code reloading, see: http://pypi.python.org/pypi/Spawning/ """ import evy from evy.web import wsgi def hello_world(env, start_response): if env['PATH_INFO'] != '/': start_response('404 Not Found', [('Content-Type', 'text/plain')]) return ['Not Found\r\n'] start_response('200 OK', [('Content-Type', 'text/plain')]) return ['Hello, World!\r\n'] wsgi.server(evy.listen(('', 8090)), hello_world)
pool = evy.GreenPool() def fetch_title (url): d = feedparser.parse(url) return d.feed.get('title', '') def app (environ, start_response): if environ['REQUEST_METHOD'] != 'POST': start_response('403 Forbidden', []) return [] # the pile collects the result of a concurrent operation -- in this case, # the collection of feed titles pile = evy.GreenPile(pool) for line in environ['wsgi.input'].readlines(): url = line.strip() if url: pile.spawn(fetch_title, url) # since the pile is an iterator over the results, # you can use it in all sorts of great Pythonic ways titles = '\n'.join(pile) start_response('200 OK', [('Content-type', 'text/plain')]) return [titles] if __name__ == '__main__': from evy import wsgi wsgi.server(evy.listen(('localhost', 9010)), app)
""" This is the websocket handler function. Note that we can dispatch based on path in here, too.""" if ws.path == "/echo": while True: m = ws.wait() if m is None: break ws.send(m) elif ws.path == "/data": for i in xrange(10000): ws.send("0 %s %s\n" % (i, random.random())) evy.sleep(0.1) def dispatch(environ, start_response): """ This resolves to the web page or the websocket depending on the path.""" if environ["PATH_INFO"] == "/data": return handle(environ, start_response) else: start_response("200 OK", [("content-type", "text/html")]) return [open(os.path.join(os.path.dirname(__file__), "websocket.html")).read()] if __name__ == "__main__": # run an example app from the command line listener = evy.listen(("127.0.0.1", 7000)) print "\nVisit http://localhost:7000/ in your websocket-capable browser.\n" wsgi.server(listener, dispatch)
def fetch_title(url): d = feedparser.parse(url) return d.feed.get('title', '') def app(environ, start_response): if environ['REQUEST_METHOD'] != 'POST': start_response('403 Forbidden', []) return [] # the pile collects the result of a concurrent operation -- in this case, # the collection of feed titles pile = evy.GreenPile(pool) for line in environ['wsgi.input'].readlines(): url = line.strip() if url: pile.spawn(fetch_title, url) # since the pile is an iterator over the results, # you can use it in all sorts of great Pythonic ways titles = '\n'.join(pile) start_response('200 OK', [('Content-type', 'text/plain')]) return [titles] if __name__ == '__main__': from evy import wsgi wsgi.server(evy.listen(('localhost', 9010)), app)
try: try: while True: socketpair = sock.accept() backdoor(socketpair, locals) except socket.error, e: # Broken pipe means it was shutdown if get_errno(e) != errno.EPIPE: raise finally: sock.close() def backdoor((conn, addr), locals=None): """ Sets up an interactive console on a socket with a single connected client. This does not block the caller, as it spawns a new greenlet to handle the console. This is meant to be called from within an accept loop (such as backdoor_server). """ host, port = addr print "backdoor to %s:%s" % (host, port) fl = conn.makefile("rw") console = SocketConsole(fl, (host, port), locals) hub = hubs.get_hub() hub.run_callback(console.switch) if __name__ == '__main__': backdoor_server(evy.listen(('127.0.0.1', 9000)), {})
if __name__ == "__main__": usage = 'usage: websocket_chat -p pub address -s sub address port number' if len(sys.argv) != 6: print usage sys.exit(1) pub_addr = sys.argv[2] sub_addr = sys.argv[4] try: port = int(sys.argv[5]) except ValueError: print "Error port supplied couldn't be converted to int\n", usage sys.exit(1) try: pub_socket = ctx.socket(zmq.PUB) pub_socket.connect(pub_addr) print "Publishing to %s" % pub_addr sub_socket = ctx.socket(zmq.SUB) sub_socket.connect(sub_addr) sub_socket.setsockopt(zmq.SUBSCRIBE, "") print "Subscribing to %s" % sub_addr except: print "Couldn't create sockets\n", usage sys.exit(1) spawn_n(subscribe_and_distribute, sub_socket) listener = evy.listen(('127.0.0.1', port)) print "\nVisit http://localhost:%s/ in your websocket-capable browser.\n" % port wsgi.server(listener, dispatch)
""" This is an incredibly simple port forwarder from port 7000 to 22 on localhost. It calls a callback function when the socket is closed, to demonstrate one way that you could start to do interesting things by starting from a simple framework like this. """ import evy def closed_callback(): print "called back" def forward(source, dest, cb=lambda: None): """Forwards bytes unidirectionally from source to dest""" while True: d = source.recv(32384) if d == '': cb() break dest.sendall(d) listener = evy.listen(('localhost', 7000)) while True: client, addr = listener.accept() server = evy.connect(('localhost', 22)) # two unidirectional forwarders make a bidirectional one evy.spawn_n(forward, client, server, closed_callback) evy.spawn_n(forward, server, client)
""" This is an incredibly simple port forwarder from port 7000 to 22 on localhost. It calls a callback function when the socket is closed, to demonstrate one way that you could start to do interesting things by starting from a simple framework like this. """ import evy def closed_callback (): print "called back" def forward (source, dest, cb = lambda: None): """Forwards bytes unidirectionally from source to dest""" while True: d = source.recv(32384) if d == '': cb() break dest.sendall(d) listener = evy.listen(('localhost', 7000)) while True: client, addr = listener.accept() server = evy.connect(('localhost', 22)) # two unidirectional forwarders make a bidirectional one evy.spawn_n(forward, client, server, closed_callback) evy.spawn_n(forward, server, client)
if line.startswith('name:'): who = line.split(':')[-1].strip() try: pub_socket.send_pyobj((who, line)) except socket.error, e: # ignore broken pipes, they just mean the participant # closed its connection already if e[0] != 32: raise line = reader.readline() print "Participant left chat." try: print "ChatServer starting up on port %s" % PORT server = evy.listen(('0.0.0.0', PORT)) pub_socket = ctx.socket(zmq.PUB) pub_socket.bind(ADDR) evy.spawn_n(publish, sys.stdout) while True: new_connection, address = server.accept() print "Participant joined chat." evy.spawn_n(publish, new_connection.makefile('w')) evy.spawn_n(read_chat_forever, new_connection.makefile('r'), pub_socket) except (KeyboardInterrupt, SystemExit): print "ChatServer exiting."
Connect to it with: telnet localhost 6000 You terminate your connection by terminating telnet (typically Ctrl-] and then 'quit') """ import evy def handle (fd): print "client connected" while True: # pass through every non-eof line x = fd.readline() if not x: break fd.write(x) fd.flush() print "echoed", x, print "client disconnected" print "server socket listening on port 6000" server = evy.listen(('0.0.0.0', 6000)) pool = evy.GreenPool() while True: try: new_sock, address = server.accept() print "accepted", address pool.spawn_n(handle, new_sock.makefile('rw')) except (SystemExit, KeyboardInterrupt): break
participants = set() @websocket.WebSocketWSGI def handle (ws): participants.add(ws) try: while True: m = ws.wait() if m is None: break for p in participants: p.send(m) finally: participants.remove(ws) def dispatch (environ, start_response): """Resolves to the web page or the websocket depending on the path.""" if environ['PATH_INFO'] == '/chat': return handle(environ, start_response) else: start_response('200 OK', [('content-type', 'text/html')]) html_path = os.path.join(os.path.dirname(__file__), 'websocket_chat.html') return [open(html_path).read() % {'port': PORT}] if __name__ == "__main__": # run an example app from the command line listener = evy.listen(('127.0.0.1', PORT)) print "\nVisit http://localhost:7000/ in your websocket-capable browser.\n" wsgi.server(listener, dispatch)
try: try: while True: socketpair = sock.accept() backdoor(socketpair, locals) except socket.error, e: # Broken pipe means it was shutdown if get_errno(e) != errno.EPIPE: raise finally: sock.close() def backdoor ((conn, addr), locals = None): """ Sets up an interactive console on a socket with a single connected client. This does not block the caller, as it spawns a new greenlet to handle the console. This is meant to be called from within an accept loop (such as backdoor_server). """ host, port = addr print "backdoor to %s:%s" % (host, port) fl = conn.makefile("rw") console = SocketConsole(fl, (host, port), locals) hub = hubs.get_hub() hub.run_callback(console.switch) if __name__ == '__main__': backdoor_server(evy.listen(('127.0.0.1', 9000)), {})
print "Chat:", line.strip() if line.startswith('name:'): who = line.split(':')[-1].strip() try: pub_socket.send_pyobj((who, line)) except socket.error, e: # ignore broken pipes, they just mean the participant # closed its connection already if e[0] != 32: raise line = reader.readline() print "Participant left chat." try: print "ChatServer starting up on port %s" % PORT server = evy.listen(('0.0.0.0', PORT)) pub_socket = ctx.socket(zmq.PUB) pub_socket.bind(ADDR) evy.spawn_n(publish, sys.stdout) while True: new_connection, address = server.accept() print "Participant joined chat." evy.spawn_n(publish, new_connection.makefile('w')) evy.spawn_n(read_chat_forever, new_connection.makefile('r'), pub_socket) except (KeyboardInterrupt, SystemExit): print "ChatServer exiting."
"""This is a simple example of running a wsgi application with evy. For a more fully-featured server which supports multiple processes, multiple threads, and graceful code reloading, see: http://pypi.python.org/pypi/Spawning/ """ import evy from evy.web import wsgi def hello_world (env, start_response): if env['PATH_INFO'] != '/': start_response('404 Not Found', [('Content-Type', 'text/plain')]) return ['Not Found\r\n'] start_response('200 OK', [('Content-Type', 'text/plain')]) return ['Hello, World!\r\n'] wsgi.server(evy.listen(('', 8090)), hello_world)