Skip to content

Commit

Permalink
use httpx to replace requests
Browse files Browse the repository at this point in the history
  • Loading branch information
sgrtye committed Jan 6, 2025
1 parent 2f41024 commit 56f28a1
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 8 deletions.
26 changes: 19 additions & 7 deletions apiserver/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,12 @@
import time
import json
import math
import httpx
import signal
import random
import pandas
import asyncio
import yfinance
import requests
import datetime
from fastapi import FastAPI
import aioschedule as schedule
Expand Down Expand Up @@ -52,7 +52,7 @@
COMMODITIES: (commodity_status, COMMODITY_CACHE_PATH),
}

xui_session = requests.Session()
xui_session: httpx.AsyncClient | None = None
tickers = yfinance.Tickers(
" ".join([STOCKS, INDICES, CRYPTOS, CURRENCIES, COMMODITIES])
)
Expand Down Expand Up @@ -151,21 +151,33 @@ def bytes_to_speed(bytes: int, decimal_place: int = 2) -> str:
return format_bytes(bytes, decimal_place) + "/s"


async def create_session() -> None:
global xui_session
xui_session = httpx.AsyncClient()


async def post_request(url: str, data: dict | None = None) -> dict:
if xui_session is None:
await create_session()

response = await xui_session.post(url, data=data)
return response.json()


async def xui_login() -> None:
global xui_rate_limit_time

if (sleep_time := 5 - (time.time() - xui_rate_limit_time)) > 0:
await asyncio.sleep(sleep_time)
xui_rate_limit_time = time.time()

xui_session.post(
XUI_URL + "/login",
data={"username": XUI_USERNAME, "password": XUI_PASSWORD},
await post_request(
XUI_URL + "/login", {"username": XUI_USERNAME, "password": XUI_PASSWORD}
)


async def get_xui_info(path_suffix: str) -> dict:
while (info := xui_session.post(XUI_URL + path_suffix)).status_code != 200:
while (info := await post_request(XUI_URL + path_suffix)).status_code != 200:
await xui_login()

return info.json()
Expand Down Expand Up @@ -254,7 +266,7 @@ def save_status() -> None:


async def start_api_server():
config = Config(app=app, host="127.0.0.1", port=80)
config = Config(app=app, host="0.0.0.0", port=80)
await Server(config).serve()


Expand Down
2 changes: 1 addition & 1 deletion apiserver/requirements.txt
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
httpx
pandas
fastapi
uvicorn
requests
yfinance
aioschedule

0 comments on commit 56f28a1

Please sign in to comment.