Skip to content

Commit c01ecee

Browse files
author
Rafa de la Torre
committed
Apply pep8 style rules
I used `pycodestyle` in the files I modified.
1 parent bafd5ee commit c01ecee

File tree

5 files changed

+81
-48
lines changed

5 files changed

+81
-48
lines changed

carto/auth.py

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -70,13 +70,18 @@ class _ClientIdentifier:
7070
CARTO_VERSION = pkg_resources.require('carto')[0].version
7171

7272
def get_user_agent(self, name='carto-python-sdk'):
73-
return "{name}/{version}".format(name=name, version=self.CARTO_VERSION)
73+
return "{name}/{version}".format(
74+
name=name,
75+
version=self.CARTO_VERSION)
7476

7577
def get_client_identifier(self, prefix='cps'):
76-
return "{prefix}-{version}".format(prefix=prefix, version=self.CARTO_VERSION)
78+
return "{prefix}-{version}".format(
79+
prefix=prefix,
80+
version=self.CARTO_VERSION)
7781

7882

79-
class APIKeyAuthClient(_UsernameGetter, _BaseUrlChecker, _ClientIdentifier, BaseAuthClient):
83+
class APIKeyAuthClient(_UsernameGetter, _BaseUrlChecker, _ClientIdentifier,
84+
BaseAuthClient):
8085
"""
8186
This class provides you with authenticated access to CARTO's APIs using
8287
your API key.

carto/sql.py

Lines changed: 23 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,7 @@
2525
# The chunk size should be a multiple of the filesystem/buffers block
2626
# size. Big values can cause resource starvation and OTOH small values
2727
# incur in some protocol overhead. Typical linux block size is 4 KB.
28-
DEFAULT_CHUNK_SIZE = 8 * 1024 # 8 KB provides good results in practice
28+
DEFAULT_CHUNK_SIZE = 8 * 1024 # 8 KB provides good results in practice
2929

3030
# The compression level of gzip/zlib ranges from 1 (fastest, least
3131
# compression) to 9 (slowest, most compression). In our performance
@@ -276,15 +276,17 @@ def _read_in_chunks(self, file_object, chunk_size=DEFAULT_CHUNK_SIZE):
276276

277277
def _compress_chunks(self, chunk_generator, compression_level):
278278
zlib_mode = 16 + zlib.MAX_WBITS
279-
compressor = zlib.compressobj(compression_level, zlib.DEFLATED, zlib_mode)
279+
compressor = zlib.compressobj(compression_level,
280+
zlib.DEFLATED,
281+
zlib_mode)
280282
for chunk in chunk_generator:
281283
compressed_chunk = compressor.compress(chunk)
282284
if len(compressed_chunk) > 0:
283285
yield compressed_chunk
284286
yield compressor.flush()
285287

286-
287-
def copyfrom(self, query, iterable_data, compress=True, compression_level=DEFAULT_COMPRESSION_LEVEL):
288+
def copyfrom(self, query, iterable_data, compress=True,
289+
compression_level=DEFAULT_COMPRESSION_LEVEL):
288290
"""
289291
Gets data from an iterable object into a table
290292
@@ -306,11 +308,12 @@ def copyfrom(self, query, iterable_data, compress=True, compression_level=DEFAUL
306308
'Content-Type': 'application/octet-stream',
307309
'Transfer-Encoding': 'chunked'
308310
}
309-
params={'api_key': self.api_key, 'q': query}
311+
params = {'api_key': self.api_key, 'q': query}
310312

311313
if compress:
312314
headers['Content-Encoding'] = 'gzip'
313-
_iterable_data = self._compress_chunks(iterable_data, compression_level)
315+
_iterable_data = self._compress_chunks(iterable_data,
316+
compression_level)
314317
else:
315318
_iterable_data = iterable_data
316319

@@ -327,7 +330,8 @@ def copyfrom(self, query, iterable_data, compress=True, compression_level=DEFAUL
327330

328331
return response_json
329332

330-
def copyfrom_file_object(self, query, file_object, compress=True, compression_level=DEFAULT_COMPRESSION_LEVEL):
333+
def copyfrom_file_object(self, query, file_object, compress=True,
334+
compression_level=DEFAULT_COMPRESSION_LEVEL):
331335
"""
332336
Gets data from a readable file object into a table
333337
@@ -345,9 +349,11 @@ def copyfrom_file_object(self, query, file_object, compress=True, compression_le
345349
:raise CartoException:
346350
"""
347351
chunk_generator = self._read_in_chunks(file_object)
348-
return self.copyfrom(query, chunk_generator, compress, compression_level)
352+
return self.copyfrom(query, chunk_generator, compress,
353+
compression_level)
349354

350-
def copyfrom_file_path(self, query, path, compress=True, compression_level=DEFAULT_COMPRESSION_LEVEL):
355+
def copyfrom_file_path(self, query, path, compress=True,
356+
compression_level=DEFAULT_COMPRESSION_LEVEL):
351357
"""
352358
Gets data from a readable file into a table
353359
@@ -364,14 +370,15 @@ def copyfrom_file_path(self, query, path, compress=True, compression_level=DEFAU
364370
:raise CartoException:
365371
"""
366372
with open(path, 'rb') as f:
367-
result = self.copyfrom_file_object(query, f, compress, compression_level)
373+
result = self.copyfrom_file_object(query, f, compress,
374+
compression_level)
368375
return result
369376

370377
def copyto(self, query):
371378
"""
372379
Gets data from a table into a Response object that can be iterated
373380
374-
:param query: The "COPY { table_name [(column_name[, ...])] | ( query ) }
381+
:param query: The "COPY { table_name [(column_name[, ...])] | (query) }
375382
TO STDOUT [WITH(option[,...])]" query to execute
376383
:type query: str
377384
@@ -381,7 +388,7 @@ def copyto(self, query):
381388
:raise CartoException:
382389
"""
383390
url = self.api_url + '/copyto'
384-
params={'api_key': self.api_key, 'q': query}
391+
params = {'api_key': self.api_key, 'q': query}
385392

386393
try:
387394
response = self.client.send(url,
@@ -393,7 +400,8 @@ def copyto(self, query):
393400
if 400 <= response.status_code < 500:
394401
# Client error, provide better reason
395402
reason = response.json()['error'][0]
396-
error_msg = u'%s Client Error: %s' % (response.status_code, reason)
403+
error_msg = u'%s Client Error: %s' % (response.status_code,
404+
reason)
397405
raise CartoException(error_msg)
398406
else:
399407
raise CartoException(e)
@@ -406,7 +414,7 @@ def copyto_file_object(self, query, file_object):
406414
"""
407415
Gets data from a table into a writable file object
408416
409-
:param query: The "COPY { table_name [(column_name[, ...])] | ( query ) }
417+
:param query: The "COPY { table_name [(column_name[, ...])] | (query) }
410418
TO STDOUT [WITH(option[,...])]" query to execute
411419
:type query: str
412420
@@ -424,7 +432,7 @@ def copyto_file_path(self, query, path, append=False):
424432
"""
425433
Gets data from a table into a writable file
426434
427-
:param query: The "COPY { table_name [(column_name[, ...])] | ( query ) }
435+
:param query: The "COPY { table_name [(column_name[, ...])] | (query) }
428436
TO STDOUT [WITH(option[,...])]" query to execute
429437
:type query: str
430438

examples/copy_example.py

Lines changed: 6 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -20,13 +20,13 @@
2020
parser = argparse.ArgumentParser(description='External database connector')
2121

2222
parser.add_argument('--base_url', type=str, dest='CARTO_BASE_URL',
23-
default=os.environ['CARTO_API_URL'] if 'CARTO_API_URL' in os.environ else '',
23+
default=os.environ.get('CARTO_API_URL', ''),
2424
help='Set the base URL. For example:' +
2525
' https://username.carto.com/ ' +
2626
'(defaults to env variable CARTO_API_URL)')
2727

2828
parser.add_argument('--api_key', dest='CARTO_API_KEY',
29-
default=os.environ['CARTO_API_KEY'] if 'CARTO_API_KEY' in os.environ else '',
29+
default=os.environ.get('CARTO_API_KEY', ''),
3030
help='Api key of the account' +
3131
' (defaults to env variable CARTO_API_KEY)')
3232

@@ -38,12 +38,11 @@
3838
auth_client = APIKeyAuthClient(
3939
args.CARTO_BASE_URL, args.CARTO_API_KEY)
4040
else:
41-
logger.error('You need to provide valid credentials, run with -h parameter for details')
41+
logger.error('You need to provide valid credentials, run with '
42+
'-h parameter for details')
4243
import sys
4344
sys.exit(1)
4445

45-
46-
4746
# Create and cartodbfy a table
4847
sqlClient = SQLClient(auth_client)
4948
sqlClient.send("""
@@ -55,13 +54,12 @@
5554
""")
5655
sqlClient.send("SELECT CDB_CartodbfyTable(current_schema, 'copy_example')")
5756

58-
59-
6057
copyClient = CopySQLClient(auth_client)
6158

6259
# COPY FROM example
6360
logger.info("COPY'ing FROM file...")
64-
query = 'COPY copy_example (the_geom, name, age) FROM stdin WITH (FORMAT csv, HEADER true)'
61+
query = ('COPY copy_example (the_geom, name, age) '
62+
'FROM stdin WITH (FORMAT csv, HEADER true)')
6563
result = copyClient.copyfrom_file_path(query, 'files/copy_from.csv')
6664
logger.info('result = %s' % result)
6765

@@ -71,7 +69,5 @@
7169
copyClient.copyto_file_path(query, output_file)
7270
logger.info('Table copied to %s' % output_file)
7371

74-
75-
7672
# Truncate the table to make this example repeatable
7773
sqlClient.send('TRUNCATE TABLE copy_example RESTART IDENTITY')

tests/test_auth.py

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,7 @@ def test_on_prem_url():
3939
assert user2 == 'user2'
4040
assert user3 == 'user3'
4141

42+
4243
USER1_BASE_URL = 'https://user1.carto.com/'
4344
USER1_USERNAME = 'user1'
4445

@@ -107,19 +108,23 @@ def test_client_identifier():
107108
client_id_pattern = re.compile('test/\d+\.\d+\.\d+')
108109
assert client_id_pattern.match(ci.get_user_agent('test'))
109110

111+
110112
def test_user_agent():
111113
expected_user_agent = _ClientIdentifier().get_user_agent()
112114
adapter = requests_mock.Adapter()
113115
session = requests.Session()
114116

115-
# Using file:// cause urllib's urljoin (used in pyrestcli) does not support a mock:// schema
117+
# Using file:// cause urllib's urljoin (used in pyrestcli)
118+
# does not support a mock:// schema
116119
session.mount('file', adapter)
117120
adapter.register_uri('POST', 'file://test.carto.com/headers',
118121
request_headers={'User-Agent': expected_user_agent})
119122

120-
client = APIKeyAuthClient('file://test.carto.com', 'some_api_key', None, session)
123+
client = APIKeyAuthClient('file://test.carto.com', 'some_api_key',
124+
None, session)
121125
client.send('headers', 'post')
122126

127+
123128
def test_client_id_in_requests():
124129
expected_client_id = _ClientIdentifier().get_client_identifier()
125130
client = APIKeyAuthClient('https://test.carto.com', 'some_api_key')

tests/test_sql_copy.py

Lines changed: 37 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -28,13 +28,18 @@
2828
BATCH_TERMINAL_STATES = ['done', 'failed', 'cancelled', 'unknown']
2929

3030
# Please note the newline characters to delimit rows
31-
TABLE_CONTENTS=[
31+
TABLE_CONTENTS = [
3232
b'the_geom,name,age\n',
3333
b'SRID=4326;POINT(-126 54),North West,89\n',
3434
b'SRID=4326;POINT(-96 34),South East,99\n',
3535
b'SRID=4326;POINT(-6 -25),Souther Easter,124\n'
3636
]
3737

38+
COPY_FROM_QUERY = (
39+
'COPY carto_python_sdk_copy_test (the_geom, name, age) FROM stdin WITH ',
40+
'(FORMAT csv, HEADER true)'
41+
)
42+
3843

3944
@pytest.fixture(scope="module")
4045
def test_table(api_key_auth_client_usr):
@@ -45,26 +50,26 @@ def test_table(api_key_auth_client_usr):
4550
job = batch_client.read(job['job_id'])
4651
assert job['status'] == 'done'
4752

53+
4854
@pytest.fixture
4955
def copy_client(api_key_auth_client_usr):
5056
return CopySQLClient(api_key_auth_client_usr)
5157

5258

5359
def test_copyfrom(copy_client, test_table):
54-
query = 'COPY carto_python_sdk_copy_test (the_geom, name, age) FROM stdin WITH (FORMAT csv, HEADER true)'
5560
data = iter(TABLE_CONTENTS)
56-
result = copy_client.copyfrom(query, data)
61+
result = copy_client.copyfrom(COPY_FROM_QUERY, data)
5762

5863
assert result['total_rows'] == 3
5964

6065

6166
def test_copyfrom_no_compression(copy_client):
62-
query = 'COPY carto_python_sdk_copy_test (the_geom, name, age) FROM stdin WITH (FORMAT csv, HEADER true)'
6367
data = iter(TABLE_CONTENTS)
64-
result = copy_client.copyfrom(query, data, compress=False)
68+
result = copy_client.copyfrom(COPY_FROM_QUERY, data, compress=False)
6569

6670
assert result['total_rows'] == 3
6771

72+
6873
def test_copyfrom_wrong_query(copy_client):
6974
query = 'COPY any_wrong_table (any_wrong_column) FROM stdin'
7075
data = iter(TABLE_CONTENTS)
@@ -75,6 +80,7 @@ def test_copyfrom_wrong_query(copy_client):
7580

7681
IN_MEMORY_CSV_NROWS = 1000
7782

83+
7884
@pytest.fixture()
7985
def in_memory_csv(request):
8086
file_obj = InMemIO()
@@ -86,36 +92,44 @@ def fin():
8692

8793
for i in range(IN_MEMORY_CSV_NROWS):
8894
row = u'SRID=4326;POINT({lon} {lat}),{name},{age}\n'.format(
89-
lon = random.uniform(-170.0, 170.0),
90-
lat = random.uniform(-80.0, 80.0),
91-
name = random.choice(['fulano', 'mengano', 'zutano', 'perengano']),
92-
age = random.randint(18,99)
95+
lon=random.uniform(-170.0, 170.0),
96+
lat=random.uniform(-80.0, 80.0),
97+
name=random.choice(['fulano', 'mengano', 'zutano', 'perengano']),
98+
age=random.randint(18, 99)
9399
)
94100
file_obj.write(bytearray(row, 'utf-8'))
95101
file_obj.seek(0)
96102
return file_obj
97103

104+
98105
def test_copyfrom_file_object(copy_client, in_memory_csv):
99-
query = 'COPY carto_python_sdk_copy_test (the_geom, name, age) FROM stdin WITH (FORMAT csv, HEADER false)'
106+
query = (
107+
'COPY carto_python_sdk_copy_test (the_geom, name, age) '
108+
'FROM stdin WITH (FORMAT csv, HEADER false)'
109+
)
100110
result = copy_client.copyfrom_file_object(query, in_memory_csv)
101111

102112
assert result['total_rows'] == IN_MEMORY_CSV_NROWS
103113

114+
104115
def test_copyfrom_file_path(copy_client):
105-
query = 'COPY carto_python_sdk_copy_test (the_geom, name, age) FROM stdin WITH (FORMAT csv, HEADER true)'
106-
result = copy_client.copyfrom_file_path(query, 'tests/copy_from.csv')
116+
result = copy_client.copyfrom_file_path(COPY_FROM_QUERY,
117+
'tests/copy_from.csv')
107118

108119
assert result['total_rows'] == 3
109120

110121

111-
112-
113122
@pytest.fixture()
114123
def copyto_sample_query():
115-
arbitrary_subquery = 'SELECT i cartodb_id, ST_AsEWKT(ST_SetSRID(ST_MakePoint(i, i),4326)) the_geom FROM generate_series(1,10) i'
124+
arbitrary_subquery = (
125+
'SELECT i cartodb_id, ',
126+
'ST_AsEWKT(ST_SetSRID(ST_MakePoint(i, i),4326)) the_geom FROM ',
127+
'generate_series(1,10) i'
128+
)
116129
query = 'COPY ({subquery}) TO STDOUT'.format(subquery=arbitrary_subquery)
117130
return query
118131

132+
119133
@pytest.fixture()
120134
def copyto_expected_result():
121135
return bytearray(u'\n'.join([
@@ -141,15 +155,20 @@ def test_copyto(copy_client, copyto_sample_query, copyto_expected_result):
141155

142156
assert result == copyto_expected_result
143157

144-
def test_copyto_file_object(copy_client, copyto_sample_query, copyto_expected_result):
158+
159+
def test_copyto_file_object(copy_client, copyto_sample_query,
160+
copyto_expected_result):
145161
in_memory_target_fileobj = InMemIO()
146162

147-
copy_client.copyto_file_object(copyto_sample_query, in_memory_target_fileobj)
163+
copy_client.copyto_file_object(copyto_sample_query,
164+
in_memory_target_fileobj)
148165
assert in_memory_target_fileobj.getvalue() == copyto_expected_result
149166

150167
in_memory_target_fileobj.close()
151168

152-
def test_copyto_file_path(copy_client, copyto_sample_query, copyto_expected_result, tmpdir):
169+
170+
def test_copyto_file_path(copy_client, copyto_sample_query,
171+
copyto_expected_result, tmpdir):
153172
target_path = tmpdir.join('carto-python-sdk-copy-test.dump')
154173
copy_client.copyto_file_path(copyto_sample_query, target_path.strpath)
155174
assert target_path.read() == copyto_expected_result.decode('utf-8')

0 commit comments

Comments
 (0)