diff options
| author | Sergey Shepelev <temotor@gmail.com> | 2014-07-18 15:21:26 +0400 |
|---|---|---|
| committer | Sergey Shepelev <temotor@gmail.com> | 2014-08-27 10:21:55 +0400 |
| commit | 203e629212be5cf6e53d577734421d494b255754 (patch) | |
| tree | 5b7039ad6c4aa17cd2b65b7163595d9c8c45e25e /examples | |
| parent | e9486899e0d62325cc8ff4966291956ce01b87d0 (diff) | |
| download | eventlet-203e629212be5cf6e53d577734421d494b255754.tar.gz | |
PEP-8 fixes
Diffstat (limited to 'examples')
| -rw-r--r-- | examples/chat_bridge.py | 4 | ||||
| -rw-r--r-- | examples/chat_server.py | 9 | ||||
| -rw-r--r-- | examples/distributed_websocket_chat.py | 15 | ||||
| -rw-r--r-- | examples/echoserver.py | 4 | ||||
| -rw-r--r-- | examples/feedscraper-testclient.py | 2 | ||||
| -rw-r--r-- | examples/feedscraper.py | 8 | ||||
| -rw-r--r-- | examples/forwarder.py | 9 | ||||
| -rw-r--r-- | examples/producer_consumer.py | 16 | ||||
| -rw-r--r-- | examples/recursive_crawler.py | 7 | ||||
| -rw-r--r-- | examples/twisted/twisted_xcap_proxy.py | 2 | ||||
| -rw-r--r-- | examples/websocket.py | 1 | ||||
| -rw-r--r-- | examples/websocket_chat.py | 8 | ||||
| -rw-r--r-- | examples/wsgi.py | 3 | ||||
| -rw-r--r-- | examples/zmq_chat.py | 9 | ||||
| -rw-r--r-- | examples/zmq_simple.py | 2 |
15 files changed, 61 insertions, 38 deletions
diff --git a/examples/chat_bridge.py b/examples/chat_bridge.py index 84d7bb3..e0fd537 100644 --- a/examples/chat_bridge.py +++ b/examples/chat_bridge.py @@ -2,10 +2,10 @@ import sys from zmq import FORWARDER, PUB, SUB, SUBSCRIBE from zmq.devices import Device - + if __name__ == "__main__": usage = 'usage: chat_bridge sub_address pub_address' - if len (sys.argv) != 3: + if len(sys.argv) != 3: print(usage) sys.exit(1) diff --git a/examples/chat_server.py b/examples/chat_server.py index e608497..77f0924 100644 --- a/examples/chat_server.py +++ b/examples/chat_server.py @@ -1,16 +1,17 @@ import eventlet from eventlet.green import socket -PORT=3001 +PORT = 3001 participants = set() + def read_chat_forever(writer, reader): line = reader.readline() while line: print("Chat:", line.strip()) for p in participants: try: - if p is not writer: # Don't echo + if p is not writer: # Don't echo p.write(line) p.flush() except socket.error as e: @@ -30,8 +31,8 @@ try: print("Participant joined chat.") new_writer = new_connection.makefile('w') participants.add(new_writer) - eventlet.spawn_n(read_chat_forever, - new_writer, + eventlet.spawn_n(read_chat_forever, + new_writer, new_connection.makefile('r')) except (KeyboardInterrupt, SystemExit): print("ChatServer exiting.") diff --git a/examples/distributed_websocket_chat.py b/examples/distributed_websocket_chat.py index fc530b8..526f3ab 100644 --- a/examples/distributed_websocket_chat.py +++ b/examples/distributed_websocket_chat.py @@ -13,7 +13,8 @@ $ python examples/distributed_websocket_chat.py -p tcp://127.0.0.1:12345 -s tcp: So all messages are published to port 12345 and the device forwards all the messages to 12346 where they are subscribed to """ -import os, sys +import os +import sys import eventlet from collections import defaultdict from eventlet import spawn_n, sleep @@ -26,6 +27,7 @@ from uuid import uuid1 use_hub('zeromq') ctx = zmq.Context() + class IDName(object): def __init__(self): @@ -44,12 +46,13 @@ class IDName(object): def unpack_message(self, msg): sender, message = msg sender_name = 'you said' if sender.id == self.id \ - else '%s says' % sender + else '%s says' % sender return "%s: %s" % (sender_name, message) participants = defaultdict(IDName) + def subscribe_and_distribute(sub_socket): global participants while True: @@ -62,6 +65,7 @@ def subscribe_and_distribute(sub_socket): except: del participants[ws] + @websocket.WebSocketWSGI def handle(ws): global pub_socket @@ -81,7 +85,8 @@ def handle(ws): sleep() finally: del participants[ws] - + + def dispatch(environ, start_response): """Resolves to the web page or the websocket depending on the path.""" global port @@ -90,14 +95,14 @@ def dispatch(environ, start_response): else: start_response('200 OK', [('content-type', 'text/html')]) return [open(os.path.join( - os.path.dirname(__file__), + os.path.dirname(__file__), 'websocket_chat.html')).read() % dict(port=port)] port = None if __name__ == "__main__": usage = 'usage: websocket_chat -p pub address -s sub address port number' - if len (sys.argv) != 6: + if len(sys.argv) != 6: print(usage) sys.exit(1) diff --git a/examples/echoserver.py b/examples/echoserver.py index 9a341a5..33927fd 100644 --- a/examples/echoserver.py +++ b/examples/echoserver.py @@ -13,12 +13,14 @@ from __future__ import print_function import eventlet + def handle(fd): print("client connected") while True: # pass through every non-eof line x = fd.readline() - if not x: break + if not x: + break fd.write(x) fd.flush() print("echoed", x, end=' ') diff --git a/examples/feedscraper-testclient.py b/examples/feedscraper-testclient.py index 952f029..b68da8d 100644 --- a/examples/feedscraper-testclient.py +++ b/examples/feedscraper-testclient.py @@ -22,4 +22,4 @@ http://ln.hixie.ch/rss/html url = 'http://localhost:9010/' result = urllib2.urlopen(url, big_list_of_feeds) -print(result.read())
\ No newline at end of file +print(result.read()) diff --git a/examples/feedscraper.py b/examples/feedscraper.py index b9e7e11..a28a020 100644 --- a/examples/feedscraper.py +++ b/examples/feedscraper.py @@ -7,15 +7,17 @@ feedparser = eventlet.import_patched('feedparser') # the pool provides a safety limit on our concurrency pool = eventlet.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 = eventlet.GreenPile(pool) @@ -23,7 +25,7 @@ def app(environ, start_response): url = line.strip() if url: pile.spawn(fetch_title, url) - # since the pile is an iterator over the results, + # 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')]) @@ -32,4 +34,4 @@ def app(environ, start_response): if __name__ == '__main__': from eventlet import wsgi - wsgi.server(eventlet.listen(('localhost', 9010)), app)
\ No newline at end of file + wsgi.server(eventlet.listen(('localhost', 9010)), app) diff --git a/examples/forwarder.py b/examples/forwarder.py index d00db2a..124d072 100644 --- a/examples/forwarder.py +++ b/examples/forwarder.py @@ -1,14 +1,17 @@ -""" 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 +""" 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 eventlet + + def closed_callback(): print("called back") -def forward(source, dest, cb = lambda: None): + +def forward(source, dest, cb=lambda: None): """Forwards bytes unidirectionally from source to dest""" while True: d = source.recv(32384) diff --git a/examples/producer_consumer.py b/examples/producer_consumer.py index 3812a29..214ed3f 100644 --- a/examples/producer_consumer.py +++ b/examples/producer_consumer.py @@ -1,12 +1,12 @@ """This is a recursive web crawler. Don't go pointing this at random sites; -it doesn't respect robots.txt and it is pretty brutal about how quickly it +it doesn't respect robots.txt and it is pretty brutal about how quickly it fetches pages. -This is a kind of "producer/consumer" example; the fetch function produces -jobs, and the GreenPool itself is the consumer, farming out work concurrently. +This is a kind of "producer/consumer" example; the fetch function produces +jobs, and the GreenPool itself is the consumer, farming out work concurrently. It's easier to write it this way rather than writing a standard consumer loop; GreenPool handles any exceptions raised and arranges so that there's a set -number of "workers", so you don't have to write that tedious management code +number of "workers", so you don't have to write that tedious management code yourself. """ from __future__ import with_statement @@ -29,16 +29,16 @@ def fetch(url, outq): new_url = url_match.group(0) outq.put(new_url) - + def producer(start_url): - """Recursively crawl starting from *start_url*. Returns a set of + """Recursively crawl starting from *start_url*. Returns a set of urls that were found.""" pool = eventlet.GreenPool() seen = set() q = eventlet.Queue() q.put(start_url) # keep looping if there are new urls, or workers that may produce more urls - while True: + while True: while not q.empty(): url = q.get() # limit requests to eventlet.net so we don't crash all over the internet @@ -48,7 +48,7 @@ def producer(start_url): pool.waitall() if q.empty(): break - + return seen diff --git a/examples/recursive_crawler.py b/examples/recursive_crawler.py index e44e291..6ecf5b4 100644 --- a/examples/recursive_crawler.py +++ b/examples/recursive_crawler.py @@ -1,5 +1,5 @@ """This is a recursive web crawler. Don't go pointing this at random sites; -it doesn't respect robots.txt and it is pretty brutal about how quickly it +it doesn't respect robots.txt and it is pretty brutal about how quickly it fetches pages. The code for this is very short; this is perhaps a good indication @@ -34,9 +34,10 @@ def fetch(url, seen, pool): # while this seems stack-recursive, it's actually not: # spawned greenthreads start their own stacks pool.spawn_n(fetch, new_url, seen, pool) - + + def crawl(start_url): - """Recursively crawl starting from *start_url*. Returns a set of + """Recursively crawl starting from *start_url*. Returns a set of urls that were found.""" pool = eventlet.GreenPool() seen = set() diff --git a/examples/twisted/twisted_xcap_proxy.py b/examples/twisted/twisted_xcap_proxy.py index e7f5f84..1ee5ee3 100644 --- a/examples/twisted/twisted_xcap_proxy.py +++ b/examples/twisted/twisted_xcap_proxy.py @@ -13,7 +13,7 @@ class LineOnlyReceiver(basic.LineOnlyReceiver): print('received: %r' % line) if not line: return - app, context, node = (line + ' ').split(' ', 3) + app, context, node = (line + ' ').split(' ', 3) context = {'u' : 'users', 'g': 'global'}.get(context, context) d = deferToGreenThread(client._get, app, node, globaltree=context=='global') def callback(result): diff --git a/examples/websocket.py b/examples/websocket.py index 66a2165..a644716 100644 --- a/examples/websocket.py +++ b/examples/websocket.py @@ -24,6 +24,7 @@ def handle(ws): ws.send("0 %s %s\n" % (i, random.random())) eventlet.sleep(0.1) + def dispatch(environ, start_response): """ This resolves to the web page or the websocket depending on the path.""" diff --git a/examples/websocket_chat.py b/examples/websocket_chat.py index c0202bb..3866674 100644 --- a/examples/websocket_chat.py +++ b/examples/websocket_chat.py @@ -8,6 +8,7 @@ PORT = 7000 participants = set() + @websocket.WebSocketWSGI def handle(ws): participants.add(ws) @@ -20,7 +21,8 @@ def handle(ws): 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': @@ -29,9 +31,9 @@ def dispatch(environ, start_response): 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 + # run an example app from the command line listener = eventlet.listen(('127.0.0.1', PORT)) print("\nVisit http://localhost:7000/ in your websocket-capable browser.\n") wsgi.server(listener, dispatch) diff --git a/examples/wsgi.py b/examples/wsgi.py index ba3f433..05668a4 100644 --- a/examples/wsgi.py +++ b/examples/wsgi.py @@ -8,11 +8,12 @@ http://pypi.python.org/pypi/Spawning/ import eventlet from eventlet 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(eventlet.listen(('', 8090)), hello_world) diff --git a/examples/zmq_chat.py b/examples/zmq_chat.py index 2c5aad1..c24e161 100644 --- a/examples/zmq_chat.py +++ b/examples/zmq_chat.py @@ -1,4 +1,5 @@ -import eventlet, sys +import eventlet +import sys from eventlet.green import socket, zmq from eventlet.hubs import use_hub use_hub('zeromq') @@ -7,6 +8,7 @@ ADDR = 'ipc:///tmp/chat' ctx = zmq.Context() + def publish(writer): print("connected") @@ -23,7 +25,8 @@ def publish(writer): writer.flush() -PORT=3001 +PORT = 3001 + def read_chat_forever(reader, pub_socket): @@ -61,4 +64,4 @@ try: new_connection.makefile('r'), pub_socket) except (KeyboardInterrupt, SystemExit): - print("ChatServer exiting.")
\ No newline at end of file + print("ChatServer exiting.") diff --git a/examples/zmq_simple.py b/examples/zmq_simple.py index f47dab1..6f5f11e 100644 --- a/examples/zmq_simple.py +++ b/examples/zmq_simple.py @@ -3,6 +3,7 @@ import eventlet CTX = zmq.Context(1) + def bob_client(ctx, count): print("STARTING BOB") bob = zmq.Socket(CTX, zmq.REQ) @@ -13,6 +14,7 @@ def bob_client(ctx, count): bob.send("HI") print("BOB GOT:", bob.recv()) + def alice_server(ctx, count): print("STARTING ALICE") alice = zmq.Socket(CTX, zmq.REP) |
