c10e54dd34
Some checks failed
Python package / build (3.10) (push) Has been cancelled
Python package / build (3.11) (push) Has been cancelled
Python package / build (3.9) (push) Has been cancelled
66 lines
2.4 KiB
Python
66 lines
2.4 KiB
Python
# Shim for requests
|
|
import json as j
|
|
import urllib.parse
|
|
import urllib.request
|
|
|
|
class Request:
|
|
def __init__(self, raw):
|
|
self.raw = raw
|
|
self.status_code = raw.status
|
|
self.headers = dict(raw.headers)
|
|
|
|
def json(self):
|
|
return j.load(self.raw)
|
|
|
|
def cookie_header(cookies):
|
|
if len(cookies) == 0: return {}
|
|
return {'Cookie': '; '.join(f'{name}={value}' for name, value in cookies.items())}
|
|
|
|
def get(url, cookies = {}, params = None, headers = {}, stream = False):
|
|
print(f'get: url={url}, cookies={cookies}, params={params}, headers={headers}')
|
|
if params is not None and len(params) != 0:
|
|
url = f'{url}?{urllib.parse.urlencode(params)}'
|
|
headers = {**headers, **cookie_header(cookies)}
|
|
request = urllib.request.Request(url, headers=headers, method='GET')
|
|
return Request(urllib.request.urlopen(request))
|
|
|
|
def multipart_form_data(data, files, separator):
|
|
lines = []
|
|
for (key, value) in data.items():
|
|
assert '"' not in key
|
|
lines.append(f'--{separator}'.encode())
|
|
lines.append(f'Content-Disposition: form-data; name="{key}"'.encode())
|
|
lines.append(b'')
|
|
lines.append(value.encode())
|
|
for (key, (filename, content, mimetype)) in files.items():
|
|
assert '"' not in key
|
|
assert '"' not in filename
|
|
lines.append(f'--{separator}'.encode())
|
|
lines.append(f'Content-Disposition: form-data; name="{key}"; filename="{filename}"'.encode())
|
|
lines.append(f'Content-Type: {mimetype}'.encode())
|
|
lines.append(b'')
|
|
lines.append(content)
|
|
lines.append(f'--{separator}--'.encode())
|
|
lines.append(b'')
|
|
return b'\r\n'.join(lines)
|
|
|
|
def post(url, cookies = {}, headers = {}, data = None, json = None, files = None, stream = False, __method = 'POST'):
|
|
print(f'{__method}: url={url}, cookies={cookies}, data={data}, json={json}, files={files}, headers={headers}')
|
|
if files is not None:
|
|
assert json is None
|
|
if data is None:
|
|
data = {}
|
|
separator = '9f4153bd638fbc3bff513d2611248d1d'
|
|
data = multipart_form_data(data=data, files=files, separator=separator)
|
|
headers = {**headers, 'Content-Type': f'multipart/form-data; boundary={separator}'}
|
|
elif json is not None:
|
|
data = j.dumps(json).encode('utf-8')
|
|
headers = {**headers, 'Content-Type': 'application/json'}
|
|
else:
|
|
data = urllib.parse.urlencode(data).encode('utf-8')
|
|
headers = {**headers, **cookie_header(cookies)}
|
|
request = urllib.request.Request(url, headers=headers, data=data, method=__method)
|
|
return Request(urllib.request.urlopen(request))
|
|
|
|
def put(url, *args, **kwargs):
|
|
return post(url, *args, **kwargs, __method = 'PUT')
|