summaryrefslogtreecommitdiff
path: root/eventlet
diff options
context:
space:
mode:
authorJakub Stasiak <jakub@stasiak.at>2014-07-13 20:43:33 +0100
committerSergey Shepelev <temotor@gmail.com>2014-07-18 09:11:02 +0400
commit99f4f18c33e3bddca2f6253e956bd8e13e7879dc (patch)
tree290bafa03d9f6d837461f2758d9c57786cc78480 /eventlet
parent6afd8bdee225b04352a629fda7f3302c16905a92 (diff)
downloadeventlet-99f4f18c33e3bddca2f6253e956bd8e13e7879dc.tar.gz
wsgi: websocket: Reformat code + tests (PEP-8)
Diffstat (limited to 'eventlet')
-rw-r--r--eventlet/websocket.py27
-rw-r--r--eventlet/wsgi.py57
2 files changed, 44 insertions, 40 deletions
diff --git a/eventlet/websocket.py b/eventlet/websocket.py
index 8a60816..c8b2e4a 100644
--- a/eventlet/websocket.py
+++ b/eventlet/websocket.py
@@ -11,7 +11,7 @@ from socket import error as SocketError
try:
from hashlib import md5, sha1
-except ImportError: #pragma NO COVER
+except ImportError: # pragma NO COVER
from md5 import md5
from sha import sha as sha1
@@ -72,6 +72,7 @@ class WebSocketWSGI(object):
function. Note that the server will log the websocket request at
the time of closure.
"""
+
def __init__(self, handler):
self.handler = handler
self.protocol_version = None
@@ -171,8 +172,8 @@ class WebSocketWSGI(object):
"Connection: Upgrade\r\n"
"WebSocket-Origin: %s\r\n"
"WebSocket-Location: %s\r\n\r\n" % (
- environ.get('HTTP_ORIGIN'),
- location))
+ environ.get('HTTP_ORIGIN'),
+ location))
elif self.protocol_version == 76:
handshake_reply = ("HTTP/1.1 101 WebSocket Protocol Handshake\r\n"
"Upgrade: WebSocket\r\n"
@@ -181,11 +182,11 @@ class WebSocketWSGI(object):
"Sec-WebSocket-Protocol: %s\r\n"
"Sec-WebSocket-Location: %s\r\n"
"\r\n%s" % (
- environ.get('HTTP_ORIGIN'),
- environ.get('HTTP_SEC_WEBSOCKET_PROTOCOL', 'default'),
- location,
- response))
- else: #pragma NO COVER
+ environ.get('HTTP_ORIGIN'),
+ environ.get('HTTP_SEC_WEBSOCKET_PROTOCOL', 'default'),
+ location,
+ response))
+ else: # pragma NO COVER
raise ValueError("Unknown WebSocket protocol version.")
sock.sendall(handshake_reply)
return WebSocket(sock, environ, self.protocol_version)
@@ -215,7 +216,7 @@ class WebSocketWSGI(object):
negotiated_protocol = p
break
#extensions = environ.get('HTTP_SEC_WEBSOCKET_EXTENSIONS', None)
- #if extensions:
+ # if extensions:
# extensions = [i.strip() for i in extensions.split(',')]
key = environ['HTTP_SEC_WEBSOCKET_KEY']
@@ -245,6 +246,7 @@ class WebSocketWSGI(object):
spaces += 1
return int(out) / spaces
+
class WebSocket(object):
"""A websocket object that handles the details of
serialization/deserialization to the socket.
@@ -264,6 +266,7 @@ class WebSocket(object):
The full WSGI environment for this request.
"""
+
def __init__(self, sock, environ, version=76):
"""
:param socket: The eventlet socket
@@ -310,10 +313,10 @@ class WebSocket(object):
if frame_type == 0:
# Normal message.
end_idx = buf.find("\xFF")
- if end_idx == -1: #pragma NO COVER
+ if end_idx == -1: # pragma NO COVER
break
msgs.append(buf[1:end_idx].decode('utf-8', 'replace'))
- buf = buf[end_idx+1:]
+ buf = buf[end_idx + 1:]
elif frame_type == 255:
# Closing handshake.
assert ord(buf[1]) == 0, "Unexpected closing handshake: %r" % buf
@@ -367,7 +370,7 @@ class WebSocket(object):
except SocketError:
# Sometimes, like when the remote side cuts off the connection,
# we don't care about this.
- if not ignore_send_errors: #pragma NO COVER
+ if not ignore_send_errors: # pragma NO COVER
raise
self.websocket_closed = True
diff --git a/eventlet/wsgi.py b/eventlet/wsgi.py
index 94a6334..4854fb5 100644
--- a/eventlet/wsgi.py
+++ b/eventlet/wsgi.py
@@ -21,14 +21,14 @@ MAX_HEADER_LINE = 8192
MAX_TOTAL_HEADER_SIZE = 65536
MINIMUM_CHUNK_SIZE = 4096
# %(client_port)s is also available
-DEFAULT_LOG_FORMAT= ('%(client_ip)s - - [%(date_time)s] "%(request_line)s"'
- ' %(status_code)s %(body_length)s %(wall_seconds).6f')
+DEFAULT_LOG_FORMAT = ('%(client_ip)s - - [%(date_time)s] "%(request_line)s"'
+ ' %(status_code)s %(body_length)s %(wall_seconds).6f')
__all__ = ['server', 'format_date_time']
# Weekday and month names for HTTP date/time formatting; always English!
_weekdayname = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]
-_monthname = [None, # Dummy so we can use 1-based month numbers
+_monthname = [None, # Dummy so we can use 1-based month numbers
"Jan", "Feb", "Mar", "Apr", "May", "Jun",
"Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]
@@ -85,7 +85,7 @@ class Input(object):
def _do_read(self, reader, length=None):
if self.wfile is not None:
- ## 100 Continue
+ # 100 Continue
self.wfile.write(self.wfile_line)
self.wfile = None
self.wfile_line = None
@@ -105,7 +105,7 @@ class Input(object):
def _chunked_read(self, rfile, length=None, use_readline=False):
if self.wfile is not None:
- ## 100 Continue
+ # 100 Continue
self.wfile.write(self.wfile_line)
self.wfile = None
self.wfile_line = None
@@ -221,7 +221,7 @@ class HttpProtocol(BaseHTTPServer.BaseHTTPRequestHandler):
self.wfile = socket._fileobject(conn, "wb", self.wbufsize)
else:
# it's a SSLObject, or a martian
- raise NotImplementedError("wsgi.py doesn't support sockets "\
+ raise NotImplementedError("wsgi.py doesn't support sockets "
"of type %s" % type(conn))
def handle_one_request(self):
@@ -325,13 +325,13 @@ class HttpProtocol(BaseHTTPServer.BaseHTTPRequestHandler):
client_conn = self.headers.get('Connection', '').lower()
send_keep_alive = False
if self.close_connection == 0 and \
- self.server.keepalive and (client_conn == 'keep-alive' or \
- (self.request_version == 'HTTP/1.1' and
- not client_conn == 'close')):
+ self.server.keepalive and (client_conn == 'keep-alive' or
+ (self.request_version == 'HTTP/1.1' and
+ not client_conn == 'close')):
# only send keep-alives back to clients that sent them,
# it's redundant for 1.1 connections
- send_keep_alive = (client_conn == 'keep-alive')
- self.close_connection = 0
+ send_keep_alive = (client_conn == 'keep-alive')
+ self.close_connection = 0
else:
self.close_connection = 1
@@ -351,7 +351,7 @@ class HttpProtocol(BaseHTTPServer.BaseHTTPRequestHandler):
# end of header writing
if use_chunked[0]:
- ## Write the chunked encoding
+ # Write the chunked encoding
towrite.append("%x\r\n%s\r\n" % (len(data), data))
else:
towrite.append(data)
@@ -359,17 +359,18 @@ class HttpProtocol(BaseHTTPServer.BaseHTTPRequestHandler):
_writelines(towrite)
length[0] = length[0] + sum(map(len, towrite))
except UnicodeEncodeError:
- self.server.log_message("Encountered non-ascii unicode while attempting to write wsgi response: %r" % [x for x in towrite if isinstance(x, six.text_type)])
+ self.server.log_message(
+ "Encountered non-ascii unicode while attempting to write wsgi response: %r" % [x for x in towrite if isinstance(x, six.text_type)])
self.server.log_message(traceback.format_exc())
_writelines(
["HTTP/1.1 500 Internal Server Error\r\n",
- "Connection: close\r\n",
- "Content-type: text/plain\r\n",
- "Content-length: 98\r\n",
- "Date: %s\r\n" % format_date_time(time.time()),
- "\r\n",
- ("Internal Server Error: wsgi application passed "
- "a unicode object to the server instead of a string.")])
+ "Connection: close\r\n",
+ "Content-type: text/plain\r\n",
+ "Content-length: 98\r\n",
+ "Date: %s\r\n" % format_date_time(time.time()),
+ "\r\n",
+ ("Internal Server Error: wsgi application passed "
+ "a unicode object to the server instead of a string.")])
def start_response(status, response_headers, exc_info=None):
status_code[0] = status.split()[0]
@@ -398,7 +399,7 @@ class HttpProtocol(BaseHTTPServer.BaseHTTPRequestHandler):
try:
result = self.application(self.environ, start_response)
if (isinstance(result, _AlreadyHandled)
- or isinstance(getattr(result, '_obj', None), _AlreadyHandled)):
+ or isinstance(getattr(result, '_obj', None), _AlreadyHandled)):
self.close_connection = 1
return
@@ -441,9 +442,9 @@ class HttpProtocol(BaseHTTPServer.BaseHTTPRequestHandler):
if hasattr(result, 'close'):
result.close()
if (self.environ['eventlet.input'].chunked_input or
- self.environ['eventlet.input'].position \
+ self.environ['eventlet.input'].position
< self.environ['eventlet.input'].content_length):
- ## Read and discard body if there was no pending 100-continue
+ # Read and discard body if there was no pending 100-continue
if not self.environ['eventlet.input'].wfile:
# NOTE: MINIMUM_CHUNK_SIZE is used here for purpose different than chunking.
# We use it only cause it's at hand and has reasonable value in terms of
@@ -595,7 +596,7 @@ class Server(BaseHTTPServer.HTTPServer):
Please, make sure you know what you are doing.
HTTP headers names are case-insensitive per RFC standard.
Most likely, you need to fix HTTP parsing in your client software.""",
- DeprecationWarning, stacklevel=3)
+ DeprecationWarning, stacklevel=3)
def get_environ(self):
d = {
@@ -740,10 +741,10 @@ def server(sock, site,
try:
pool.spawn_n(serv.process_request, client_socket)
except AttributeError:
- warnings.warn("wsgi's pool should be an instance of " \
- "eventlet.greenpool.GreenPool, is %s. Please convert your"\
- " call site to use GreenPool instead" % type(pool),
- DeprecationWarning, stacklevel=2)
+ warnings.warn("wsgi's pool should be an instance of "
+ "eventlet.greenpool.GreenPool, is %s. Please convert your"
+ " call site to use GreenPool instead" % type(pool),
+ DeprecationWarning, stacklevel=2)
pool.execute_async(serv.process_request, client_socket)
except ACCEPT_EXCEPTIONS as e:
if get_errno(e) not in ACCEPT_ERRNO: