Files
Alpaca/src/connection_handler.py

57 lines
2.3 KiB
Python
Raw Normal View History

2024-05-12 18:18:25 -06:00
# connectionhandler.py
import json, requests
2024-05-25 23:03:26 -06:00
url = None
2024-06-28 21:29:36 -06:00
bearer_token = None
def get_headers(include_json:bool) -> dict:
headers = {}
if include_json:
headers["Content-Type"] = "application/json"
2024-06-28 21:29:36 -06:00
if bearer_token:
headers["Authorization"] = "Bearer {}".format(bearer_token)
return headers if len(headers.keys()) > 0 else None
2024-05-25 23:03:26 -06:00
2024-05-12 18:18:25 -06:00
def simple_get(connection_url:str) -> dict:
try:
response = requests.get(connection_url, headers=get_headers(False))
2024-05-12 18:18:25 -06:00
if response.status_code == 200:
return {"status": "ok", "text": response.text, "status_code": response.status_code}
else:
2024-05-14 00:27:02 -06:00
return {"status": "error", "status_code": response.status_code}
2024-05-12 18:18:25 -06:00
except Exception as e:
2024-05-14 00:27:02 -06:00
return {"status": "error", "status_code": 0}
2024-05-12 18:18:25 -06:00
2024-06-01 00:07:34 -06:00
def simple_post(connection_url:str, data) -> dict:
try:
response = requests.post(connection_url, headers=get_headers(True), data=data, stream=False)
2024-06-01 00:07:34 -06:00
if response.status_code == 200:
return {"status": "ok", "text": response.text, "status_code": response.status_code}
else:
return {"status": "error", "status_code": response.status_code}
except Exception as e:
return {"status": "error", "status_code": 0}
2024-05-12 18:18:25 -06:00
def simple_delete(connection_url:str, data) -> dict:
try:
response = requests.delete(connection_url, headers=get_headers(False), json=data)
2024-05-12 18:18:25 -06:00
if response.status_code == 200:
return {"status": "ok", "status_code": response.status_code}
else:
return {"status": "error", "text": "Failed to delete", "status_code": response.status_code}
except Exception as e:
2024-05-14 00:27:02 -06:00
return {"status": "error", "status_code": 0}
2024-05-12 18:18:25 -06:00
def stream_post(connection_url:str, data, callback:callable) -> dict:
try:
response = requests.post(connection_url, headers=get_headers(True), data=data, stream=True)
2024-05-12 18:18:25 -06:00
if response.status_code == 200:
for line in response.iter_lines():
if line:
callback(json.loads(line.decode("utf-8")))
2024-05-14 00:27:02 -06:00
return {"status": "ok", "status_code": response.status_code}
2024-05-12 18:18:25 -06:00
else:
2024-05-14 00:27:02 -06:00
return {"status": "error", "status_code": response.status_code}
2024-05-12 18:18:25 -06:00
except Exception as e:
2024-05-14 00:27:02 -06:00
return {"status": "error", "status_code": 0}