Skip to content

Commit

Permalink
remove dependency on the six package
Browse files Browse the repository at this point in the history
  • Loading branch information
miguelgrinberg committed Dec 1, 2020
1 parent 12879f1 commit c181e85
Show file tree
Hide file tree
Showing 27 changed files with 104 additions and 200 deletions.
5 changes: 2 additions & 3 deletions engineio/async_drivers/aiohttp.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@
from urllib.parse import urlsplit

from aiohttp.web import Response, WebSocketResponse
import six


def create_route(app, engineio_server, engineio_endpoint):
Expand Down Expand Up @@ -113,8 +112,8 @@ async def send(self, message):

async def wait(self):
msg = await self._sock.receive()
if not isinstance(msg.data, six.binary_type) and \
not isinstance(msg.data, six.text_type):
if not isinstance(msg.data, bytes) and \
not isinstance(msg.data, str):
raise IOError()
return msg.data

Expand Down
8 changes: 3 additions & 5 deletions engineio/async_drivers/gevent_uwsgi.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,5 @@
from __future__ import absolute_import

import six

import gevent
from gevent import queue
from gevent.event import Event
Expand Down Expand Up @@ -75,7 +73,7 @@ def close(self):
def _send(self, msg):
"""Transmits message either in binary or UTF-8 text mode,
depending on its type."""
if isinstance(msg, six.binary_type):
if isinstance(msg, bytes):
method = uwsgi.websocket_send_binary
else:
method = uwsgi.websocket_send
Expand All @@ -86,11 +84,11 @@ def _send(self, msg):

def _decode_received(self, msg):
"""Returns either bytes or str, depending on message type."""
if not isinstance(msg, six.binary_type):
if not isinstance(msg, bytes):
# already decoded - do nothing
return msg
# only decode from utf-8 if message is not binary data
type = six.byte2int(msg[0:1])
type = ord(msg[0:1])
if type >= 48: # no binary
return msg.decode('utf-8')
# binary message, don't try to decode
Expand Down
5 changes: 2 additions & 3 deletions engineio/async_drivers/sanic.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@
except ImportError:
HTTPResponse = None
WebSocketProtocol = None
import six


def create_route(app, engineio_server, engineio_endpoint): # pragma: no cover
Expand Down Expand Up @@ -129,8 +128,8 @@ async def send(self, message):

async def wait(self):
data = await self._sock.recv()
if not isinstance(data, six.binary_type) and \
not isinstance(data, six.text_type):
if not isinstance(data, bytes) and \
not isinstance(data, str):
raise IOError()
return data

Expand Down
8 changes: 3 additions & 5 deletions engineio/async_drivers/tornado.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,15 +5,13 @@

import tornado.web
import tornado.websocket
import six


def get_tornado_handler(engineio_server):
class Handler(tornado.websocket.WebSocketHandler): # pragma: no cover
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
if isinstance(engineio_server.cors_allowed_origins,
six.string_types):
if isinstance(engineio_server.cors_allowed_origins, str):
if engineio_server.cors_allowed_origins == '*':
self.allowed_origins = None
else:
Expand Down Expand Up @@ -170,8 +168,8 @@ async def send(self, message):

async def wait(self):
msg = await self.tornado_handler.get_next_message()
if not isinstance(msg, six.binary_type) and \
not isinstance(msg, six.text_type):
if not isinstance(msg, bytes) and \
not isinstance(msg, str):
raise IOError()
return msg

Expand Down
7 changes: 3 additions & 4 deletions engineio/asyncio_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@
import aiohttp
except ImportError: # pragma: no cover
aiohttp = None
import six

from . import client
from . import exceptions
Expand Down Expand Up @@ -100,7 +99,7 @@ async def connect(self, url, headers=None, transports=None,
raise ValueError('Client is not in a disconnected state')
valid_transports = ['polling', 'websocket']
if transports is not None:
if isinstance(transports, six.text_type):
if isinstance(transports, str):
transports = [transports]
transports = [transport for transport in transports
if transport in valid_transports]
Expand Down Expand Up @@ -225,8 +224,8 @@ async def _connect_polling(self, url, headers, engineio_path):
p = payload.Payload(encoded_payload=(await r.read()).decode(
'utf-8'))
except ValueError:
six.raise_from(exceptions.ConnectionError(
'Unexpected response from server'), None)
raise exceptions.ConnectionError(
'Unexpected response from server') from None
open_packet = p.packets[0]
if open_packet.packet_type != packet.OPEN:
raise exceptions.ConnectionError(
Expand Down
6 changes: 2 additions & 4 deletions engineio/asyncio_server.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,5 @@
import asyncio

import six
from six.moves import urllib
import urllib

from . import exceptions
from . import packet
Expand Down Expand Up @@ -175,7 +173,7 @@ async def disconnect(self, sid=None):
del self.sockets[sid]
else:
await asyncio.wait([client.close()
for client in six.itervalues(self.sockets)])
for client in self.sockets.values()])
self.sockets = {}

async def handle_request(self, *args, **kwargs):
Expand Down
7 changes: 2 additions & 5 deletions engineio/asyncio_socket.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import asyncio
import six
import sys
import time

Expand Down Expand Up @@ -97,7 +96,7 @@ async def handle_get_request(self, environ):
except exceptions.QueueEmpty:
exc = sys.exc_info()
await self.close(wait=False)
six.reraise(*exc)
raise exc[1].with_traceback(exc[2])
return packets

async def handle_post_request(self, environ):
Expand Down Expand Up @@ -159,9 +158,7 @@ async def _websocket_handler(self, ws):
'%s: Failed websocket upgrade, no PING packet', self.sid)
self.upgrading = False
return
await ws.send(packet.Packet(
packet.PONG,
data=six.text_type('probe')).encode())
await ws.send(packet.Packet(packet.PONG, data='probe').encode())
await self.queue.put(packet.Packet(packet.NOOP)) # end poll

try:
Expand Down
15 changes: 5 additions & 10 deletions engineio/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,8 @@
import ssl
import threading
import time
import urllib

import six
from six.moves import urllib
try:
import requests
except ImportError: # pragma: no cover
Expand All @@ -27,9 +26,6 @@
default_logger = logging.getLogger('engineio.client')
connected_clients = []

if six.PY2: # pragma: no cover
ConnectionError = OSError


def signal_handler(sig, frame):
"""SIGINT handler.
Expand Down Expand Up @@ -179,7 +175,7 @@ def connect(self, url, headers=None, transports=None,
raise ValueError('Client is not in a disconnected state')
valid_transports = ['polling', 'websocket']
if transports is not None:
if isinstance(transports, six.string_types):
if isinstance(transports, str):
transports = [transports]
transports = [transport for transport in transports
if transport in valid_transports]
Expand Down Expand Up @@ -302,8 +298,8 @@ def _connect_polling(self, url, headers, engineio_path):
try:
p = payload.Payload(encoded_payload=r.content.decode('utf-8'))
except ValueError:
six.raise_from(exceptions.ConnectionError(
'Unexpected response from server'), None)
raise exceptions.ConnectionError(
'Unexpected response from server') from None
open_packet = p.packets[0]
if open_packet.packet_type != packet.OPEN:
raise exceptions.ConnectionError(
Expand Down Expand Up @@ -426,8 +422,7 @@ def _connect_websocket(self, url, headers, engineio_path):
else:
raise exceptions.ConnectionError('Connection error')
if upgrade:
p = packet.Packet(packet.PING,
data=six.text_type('probe')).encode()
p = packet.Packet(packet.PING, data='probe').encode()
try:
ws.send(p)
except Exception as e: # pragma: no cover
Expand Down
10 changes: 4 additions & 6 deletions engineio/packet.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,10 @@
import base64
import json as _json

import six

(OPEN, CLOSE, PING, PONG, MESSAGE, UPGRADE, NOOP) = (0, 1, 2, 3, 4, 5, 6)
packet_names = ['OPEN', 'CLOSE', 'PING', 'PONG', 'MESSAGE', 'UPGRADE', 'NOOP']

binary_types = (six.binary_type, bytearray)
binary_types = (bytes, bytearray)


class Packet(object):
Expand All @@ -17,7 +15,7 @@ class Packet(object):
def __init__(self, packet_type=NOOP, data=None, encoded_packet=None):
self.packet_type = packet_type
self.data = data
if isinstance(data, six.text_type):
if isinstance(data, str):
self.binary = False
elif isinstance(data, binary_types):
self.binary = True
Expand All @@ -37,8 +35,8 @@ def encode(self, b64=False):
else:
encoded_packet = self.data
else:
encoded_packet = six.text_type(self.packet_type)
if isinstance(self.data, six.string_types):
encoded_packet = str(self.packet_type)
if isinstance(self.data, str):
encoded_packet += self.data
elif isinstance(self.data, dict) or isinstance(self.data, list):
encoded_packet += self.json.dumps(self.data,
Expand Down
4 changes: 2 additions & 2 deletions engineio/payload.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
from . import packet
import urllib

from six.moves import urllib
from . import packet


class Payload(object):
Expand Down
11 changes: 5 additions & 6 deletions engineio/server.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,11 @@
import gzip
import importlib
import io
import logging
import urllib
import uuid
import zlib

import six
from six.moves import urllib

from . import exceptions
from . import packet
from . import payload
Expand Down Expand Up @@ -293,7 +292,7 @@ def disconnect(self, sid=None):
if sid in self.sockets: # pragma: no cover
del self.sockets[sid]
else:
for client in six.itervalues(self.sockets):
for client in self.sockets.values():
client.close()
self.sockets = {}

Expand Down Expand Up @@ -658,7 +657,7 @@ def _cors_allowed_origins(self, environ):
allowed_origins = default_origins
elif self.cors_allowed_origins == '*':
allowed_origins = None
elif isinstance(self.cors_allowed_origins, six.string_types):
elif isinstance(self.cors_allowed_origins, str):
allowed_origins = [self.cors_allowed_origins]
else:
allowed_origins = self.cors_allowed_origins
Expand Down Expand Up @@ -686,7 +685,7 @@ def _cors_headers(self, environ):

def _gzip(self, response):
"""Apply gzip compression to a response."""
bytesio = six.BytesIO()
bytesio = io.BytesIO()
with gzip.GzipFile(fileobj=bytesio, mode='w') as gz:
gz.write(response)
return bytesio.getvalue()
Expand Down
7 changes: 2 additions & 5 deletions engineio/socket.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import six
import sys
import time

Expand Down Expand Up @@ -112,7 +111,7 @@ def handle_get_request(self, environ, start_response):
except exceptions.QueueEmpty:
exc = sys.exc_info()
self.close(wait=False)
six.reraise(*exc)
raise exc[1].with_traceback(exc[2])
return packets

def handle_post_request(self, environ):
Expand Down Expand Up @@ -179,9 +178,7 @@ def _websocket_handler(self, ws):
'%s: Failed websocket upgrade, no PING packet', self.sid)
self.upgrading = False
return []
ws.send(packet.Packet(
packet.PONG,
data=six.text_type('probe')).encode())
ws.send(packet.Packet(packet.PONG, data='probe').encode())
self.queue.put(packet.Packet(packet.NOOP)) # end poll

pkt = ws.wait()
Expand Down
4 changes: 1 addition & 3 deletions setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,9 +29,7 @@
zip_safe=False,
include_package_data=True,
platforms='any',
install_requires=[
'six>=1.9.0',
],
install_requires=[],
extras_require={
'client': [
'requests>=2.21.0',
Expand Down
12 changes: 2 additions & 10 deletions tests/asyncio/test_async_aiohttp.py
Original file line number Diff line number Diff line change
@@ -1,18 +1,10 @@
import sys
import unittest
from unittest import mock

import six
from engineio.async_drivers import aiohttp as async_aiohttp

if six.PY3:
from unittest import mock
else:
import mock

if sys.version_info >= (3, 5):
from engineio.async_drivers import aiohttp as async_aiohttp


@unittest.skipIf(sys.version_info < (3, 5), 'only for Python 3.5+')
class AiohttpTests(unittest.TestCase):
def test_create_route(self):
app = mock.MagicMock()
Expand Down
13 changes: 3 additions & 10 deletions tests/asyncio/test_async_asgi.py
Original file line number Diff line number Diff line change
@@ -1,17 +1,10 @@
import asyncio
import os
import sys
import unittest
from unittest import mock

import six

if six.PY3:
from unittest import mock
else:
import mock

if sys.version_info >= (3, 5):
import asyncio
from engineio.async_drivers import asgi as async_asgi
from engineio.async_drivers import asgi as async_asgi


def AsyncMock(*args, **kwargs):
Expand Down
Loading

0 comments on commit c181e85

Please sign in to comment.