This repository has been archived on 2023-10-01. You can view files and clone it, but cannot push or open issues or pull requests.
PyNyaaTa/pynyaata/session.py

55 lines
1.6 KiB
Python
Raw Normal View History

2022-12-21 22:32:42 +00:00
from io import BytesIO
2022-12-22 00:01:21 +00:00
from os import getenv
2022-12-21 22:32:42 +00:00
from urllib import parse
2023-01-05 14:23:22 +00:00
from requests import Response, Session, post
2022-12-21 22:32:42 +00:00
2022-12-22 00:01:21 +00:00
CLOUDPROXY_ENDPOINT = getenv("CLOUDPROXY_ENDPOINT")
2022-12-21 22:32:42 +00:00
class FlareRequests(Session):
2022-12-24 14:23:54 +00:00
def request(self, method, url, params=None, data=None, **kwargs):
2022-12-21 22:32:42 +00:00
if not CLOUDPROXY_ENDPOINT:
2022-12-24 14:23:54 +00:00
return super().request(method, url, params, data, **kwargs)
2022-12-21 22:32:42 +00:00
2022-12-24 14:23:54 +00:00
if params:
url += "&" if len(url.split("?")) > 1 else "?"
url = f"{url}{parse.urlencode(params)}"
2022-12-21 22:32:42 +00:00
post_data = {
2022-12-24 14:23:54 +00:00
"cmd": f"request.{method.lower()}",
2022-12-21 22:32:42 +00:00
"url": url,
}
2022-12-24 14:23:54 +00:00
if data:
post_data["postData"] = parse.urlencode(data)
2022-12-21 22:32:42 +00:00
2023-01-05 14:23:22 +00:00
response = post(
CLOUDPROXY_ENDPOINT,
json=post_data,
)
content = response.json()
if "solution" in content:
solution = content["solution"]
if "content-type" in solution["headers"]:
content_type = solution["headers"]["content-type"].split(";")
if len(content_type) > 1:
charset = content_type[1].split("=")
if len(charset) > 1:
encoding = charset[1]
resolved = Response()
resolved.status_code = solution["status"]
resolved.headers = solution["headers"]
resolved.raw = BytesIO(solution["response"].encode())
resolved.url = url
resolved.encoding = encoding or None
resolved.reason = content["status"]
resolved.cookies = solution["cookies"]
return resolved