Skip to content

Remove dependency on six (py2 compat) #3525

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
May 1, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 6 additions & 6 deletions doc/python/colorscales.md
Original file line number Diff line number Diff line change
Expand Up @@ -400,10 +400,10 @@ fig.show()
```python
import plotly.graph_objects as go

import six.moves.urllib
import urllib
import json

response = six.moves.urllib.request.urlopen(
response = urllib.request.urlopen(
"https://raw.githubusercontent.com/plotly/datasets/master/custom_heatmap_colorscale.json"
)

Expand Down Expand Up @@ -492,11 +492,11 @@ Like axes, you can customize the color bar ticks, labels, and values with `ticks
```python
import plotly.graph_objects as go

import six.moves.urllib
import urllib
import json

# Load heatmap data
response = six.moves.urllib.request.urlopen(
response = urllib.request.urlopen(
"https://raw.githubusercontent.com/plotly/datasets/master/custom_heatmap_colorscale.json")
dataset = json.load(response)

Expand Down Expand Up @@ -525,11 +525,11 @@ By default, color bars are displayed vertically. You can change a color bar to b
```python
import plotly.graph_objects as go

import six.moves.urllib
import urllib
import json

# Load heatmap data
response = six.moves.urllib.request.urlopen(
response = urllib.request.urlopen(
"https://raw.githubusercontent.com/plotly/datasets/master/custom_heatmap_colorscale.json")
dataset = json.load(response)

Expand Down
4 changes: 2 additions & 2 deletions doc/python/graphing-multiple-chart-types.md
Original file line number Diff line number Diff line change
Expand Up @@ -85,9 +85,9 @@ import plotly.graph_objects as go

# Load data
import json
import six.moves.urllib
import urllib

response = six.moves.urllib.request.urlopen(
response = urllib.request.urlopen(
"https://raw.githubusercontent.com/plotly/datasets/master/steepest.json")

data = json.load(response)
Expand Down
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
import time
import six
import http.client
import os
import ssl
import time
from io import StringIO

from six.moves import http_client
from six.moves.urllib.parse import urlparse, unquote
from urllib.parse import urlparse, unquote

from chart_studio.api import utils

Expand Down Expand Up @@ -50,12 +50,12 @@ def write(self, data, reconnect_on=("", 200, 502)):
# Reconnect depending on the status code.
if (response == "" and "" in reconnect_on) or (
response
and isinstance(response, http_client.HTTPResponse)
and isinstance(response, http.client.HTTPResponse)
and response.status in reconnect_on
):
self._reconnect()

elif response and isinstance(response, http_client.HTTPResponse):
elif response and isinstance(response, http.client.HTTPResponse):
# If an HTTPResponse was recieved then
# make the users aware instead of
# auto-reconnecting in case the
Expand Down Expand Up @@ -85,7 +85,7 @@ def write(self, data, reconnect_on=("", 200, 502)):
"{msglen}\r\n{msg}\r\n".format(msglen=msglen, msg=msg).encode("utf-8")
)
self._conn.sock.setblocking(0)
except http_client.socket.error:
except http.client.socket.error:
self._reconnect()
self.write(data)

Expand Down Expand Up @@ -152,11 +152,11 @@ def _connect(self):
if proxy_server and proxy_port:
if ssl_enabled:
context = self._get_ssl_context()
self._conn = http_client.HTTPSConnection(
self._conn = http.client.HTTPSConnection(
proxy_server, proxy_port, context=context
)
else:
self._conn = http_client.HTTPConnection(proxy_server, proxy_port)
self._conn = http.client.HTTPConnection(proxy_server, proxy_port)

tunnel_headers = None
if proxy_auth:
Expand All @@ -166,9 +166,9 @@ def _connect(self):
else:
if ssl_enabled:
context = self._get_ssl_context()
self._conn = http_client.HTTPSConnection(server, port, context=context)
self._conn = http.client.HTTPSConnection(server, port, context=context)
else:
self._conn = http_client.HTTPConnection(server, port)
self._conn = http.client.HTTPConnection(server, port)

self._conn.putrequest("POST", self._url)
self._conn.putheader("Transfer-Encoding", "chunked")
Expand All @@ -179,14 +179,14 @@ def _connect(self):
# Set blocking to False prevents recv
# from blocking while waiting for a response.
self._conn.sock.setblocking(False)
self._bytes = six.b("")
self._bytes = b""
self._reset_retries()
time.sleep(0.5)

def close(self):
"""Close the connection to server.

If available, return a http_client.HTTPResponse object.
If available, return a http.client.HTTPResponse object.

Closing the connection involves sending the
Transfer-Encoding terminating bytes.
Expand All @@ -199,7 +199,7 @@ def close(self):
# require an extra \r\n.
try:
self._conn.send("\r\n0\r\n\r\n".encode("utf-8"))
except http_client.socket.error:
except http.client.socket.error:
# In case the socket has already been closed
return ""

Expand All @@ -219,28 +219,28 @@ def _getresponse(self):
while True:
try:
_bytes = self._conn.sock.recv(1)
except http_client.socket.error:
except http.client.socket.error:
# For error 54: Connection reset by peer
# (and perhaps others)
return six.b("")
if _bytes == six.b(""):
return b""
if _bytes == b"":
break
else:
response += _bytes
# Set recv to be non-blocking again
self._conn.sock.setblocking(False)

# Convert the response string to a http_client.HTTPResponse
# Convert the response string to a http.client.HTTPResponse
# object with a bit of a hack
if response != six.b(""):
if response != b"":
# Taken from
# http://pythonwise.blogspot.ca/2010/02/parse-http-response.html
try:
response = http_client.HTTPResponse(_FakeSocket(response))
response = http.client.HTTPResponse(_FakeSocket(response))
response.begin()
except:
# Bad headers ... etc.
response = six.b("")
response = b""
return response

def _isconnected(self):
Expand Down Expand Up @@ -268,10 +268,10 @@ def _isconnected(self):
# 3 - Check if the server has returned any data.
# If they have, then start to store the response
# in _bytes.
self._bytes = six.b("")
self._bytes = b""
self._bytes = self._conn.sock.recv(1)
return False
except http_client.socket.error as e:
except http.client.socket.error as e:
# Check why recv failed
# Windows machines are the error codes
# that start with 1
Expand Down Expand Up @@ -320,7 +320,7 @@ def _reconnect(self):
if not self._isconnected():
try:
self._connect()
except http_client.socket.error as e:
except http.client.socket.error as e:
# Attempt to reconnect if the connection was refused
if e.errno == 61 or e.errno == 10061:
# errno 61 is the "Connection Refused" error
Expand All @@ -345,8 +345,8 @@ def _reset_retries(self):
self._delay = 1


class _FakeSocket(six.StringIO):
# Used to construct a http_client.HTTPResponse object
class _FakeSocket(StringIO):
# Used to construct a http.client.HTTPResponse object
# from a string.
# Thx to: http://pythonwise.blogspot.ca/2010/02/parse-http-response.html
def makefile(self, *args, **kwargs):
Expand Down
11 changes: 4 additions & 7 deletions packages/python/chart-studio/chart_studio/plotly/plotly.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,11 +21,10 @@
import json
import os
import time
import urllib
import warnings
import webbrowser

import six
import six.moves
import json as _json

import _plotly_utils.utils
Expand Down Expand Up @@ -513,8 +512,6 @@ def get_figure(file_owner_or_url, file_id=None, raw=False):
fid = "{}:{}".format(file_owner, file_id)
response = v2.plots.content(fid, inline_data=True)
figure = response.json()
if six.PY2:
figure = byteify(figure)
# Fix 'histogramx', 'histogramy', and 'bardir' stuff
for index, entry in enumerate(figure["data"]):
try:
Expand Down Expand Up @@ -620,7 +617,7 @@ def get_streaming_specs(self):

# If no scheme (https/https) is included in the streaming_url, the
# host will be None. Use streaming_url in this case.
host = six.moves.urllib.parse.urlparse(streaming_url).hostname or streaming_url
host = urllib.parse.urlparse(streaming_url).hostname or streaming_url

headers = {"Host": host, "plotly-streamtoken": self.stream_id}
streaming_specs = {
Expand Down Expand Up @@ -1380,7 +1377,7 @@ def parse_grid_id_args(grid, grid_url):
else:
supplied_arg_name = supplied_arg_names.pop()
if supplied_arg_name == "grid_url":
path = six.moves.urllib.parse.urlparse(grid_url).path
path = urllib.parse.urlparse(grid_url).path
file_owner, file_id = path.replace("/~", "").split("/")[0:2]
return "{0}:{1}".format(file_owner, file_id)
else:
Expand All @@ -1392,7 +1389,7 @@ def add_share_key_to_url(plot_url, attempt=0):
Check that share key is enabled and update url to include the secret key

"""
urlsplit = six.moves.urllib.parse.urlparse(plot_url)
urlsplit = urllib.parse.urlparse(plot_url)
username = urlsplit.path.split("/")[1].split("~")[1]
idlocal = urlsplit.path.split("/")[2]
fid = "{}:{}".format(username, idlocal)
Expand Down
24 changes: 11 additions & 13 deletions packages/python/chart-studio/chart_studio/session.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,39 +9,37 @@

import copy

import six

import _plotly_utils.exceptions


_session = {"credentials": {}, "config": {}, "plot_options": {}}

CREDENTIALS_KEYS = {
"username": six.string_types,
"api_key": six.string_types,
"proxy_username": six.string_types,
"proxy_password": six.string_types,
"username": str,
"api_key": str,
"proxy_username": str,
"proxy_password": str,
"stream_ids": list,
}

CONFIG_KEYS = {
"plotly_domain": six.string_types,
"plotly_streaming_domain": six.string_types,
"plotly_api_domain": six.string_types,
"plotly_domain": str,
"plotly_streaming_domain": str,
"plotly_api_domain": str,
"plotly_ssl_verification": bool,
"plotly_proxy_authorization": bool,
"world_readable": bool,
"auto_open": bool,
"sharing": six.string_types,
"sharing": str,
}

PLOT_OPTIONS = {
"filename": six.string_types,
"fileopt": six.string_types,
"filename": str,
"fileopt": str,
"validate": bool,
"world_readable": bool,
"auto_open": bool,
"sharing": six.string_types,
"sharing": str,
}

SHARING_OPTIONS = ["public", "private", "secret"]
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,6 @@
"""
from __future__ import absolute_import

from unittest import skipIf

import six

import _plotly_utils.exceptions
from chart_studio import exceptions
from chart_studio.plotly import plotly as py
Expand Down Expand Up @@ -93,7 +89,6 @@ def test_get_figure_raw(self):


class TestBytesVStrings(PlotlyTestCase):
@skipIf(six.PY2, "Decoding and missing escapes only seen in PY3")
def test_proper_escaping(self):
un = "PlotlyImageTest"
ak = "786r5mecv0"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@
import copy

import requests
import six
import json as _json

from chart_studio.tests.utils import PlotlyTestCase
Expand All @@ -34,10 +33,7 @@ def test_user_does_not_exist(self):
hd["plotly-apikey"] = api_key
resource = "/apigetfile/{0}/{1}/".format(file_owner, file_id)
response = requests.get(server + resource, headers=hd)
if six.PY2:
content = _json.loads(response.content)
else:
content = _json.loads(response.content.decode("unicode_escape"))
content = _json.loads(response.content.decode("unicode_escape"))
error_message = (
"Aw, snap! We don't have an account for {0}. Want to "
"try again? Sign in is not case sensitive.".format(username)
Expand All @@ -55,10 +51,7 @@ def test_file_does_not_exist(self):
hd["plotly-apikey"] = api_key
resource = "/apigetfile/{0}/{1}/".format(file_owner, file_id)
response = requests.get(server + resource, headers=hd)
if six.PY2:
content = _json.loads(response.content)
else:
content = _json.loads(response.content.decode("unicode_escape"))
content = _json.loads(response.content.decode("unicode_escape"))
error_message = (
"Aw, snap! It looks like this file does " "not exist. Want to try again?"
)
Expand Down Expand Up @@ -91,10 +84,7 @@ def test_private_permission_defined(self):
hd["plotly-apikey"] = api_key
resource = "/apigetfile/{0}/{1}/".format(file_owner, file_id)
response = requests.get(server + resource, headers=hd)
if six.PY2:
content = _json.loads(response.content)
else:
content = _json.loads(response.content.decode("unicode_escape"))
content = _json.loads(response.content.decode("unicode_escape"))
self.assertEqual(response.status_code, 403)

# Private File that is shared
Expand All @@ -109,10 +99,7 @@ def test_missing_headers(self):
hd = copy.copy(default_headers)
del hd[header]
response = requests.get(server + resource, headers=hd)
if six.PY2:
content = _json.loads(response.content)
else:
content = _json.loads(response.content.decode("unicode_escape"))
content = _json.loads(response.content.decode("unicode_escape"))
self.assertEqual(response.status_code, 422)

def test_valid_request(self):
Expand All @@ -125,10 +112,7 @@ def test_valid_request(self):
hd["plotly-apikey"] = api_key
resource = "/apigetfile/{0}/{1}/".format(file_owner, file_id)
response = requests.get(server + resource, headers=hd)
if six.PY2:
content = _json.loads(response.content)
else:
content = _json.loads(response.content.decode("unicode_escape"))
content = _json.loads(response.content.decode("unicode_escape"))
self.assertEqual(response.status_code, 200)
# content = _json.loads(res.content)
# response_payload = content['payload']
Expand Down
Loading