fwd / app.py
thinh-vu's picture
Create app.py
150b9cd verified
Raw
History Blame Contribute Delete
2.1 kB
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
import httpx
# Import bộ sinh header từ vnstock
from vnstock.core.utils.user_agent import get_headers
app = FastAPI(title="Proxy API với Header Browser động (vnstock)")
class ProxyPayload(BaseModel):
url: str
method: str = "POST"
params: dict = None
headers: dict = None # Header client truyền thêm (nếu có)
body: dict | str | None = None
data_source: str = "SSI" # 'SSI', 'VND', 'VDS', v.v.
random_agent: bool = True
browser: str = "chrome"
platform: str = "windows"
@app.get("/")
async def root():
return {"message": "Hello from Proxy API!"}
@app.post("/request")
async def flexible_request(payload: ProxyPayload):
# Sinh header browser-like + data_source
headers = get_headers(
data_source=payload.data_source,
random_agent=payload.random_agent,
browser=payload.browser,
platform=payload.platform
)
# Merge thêm header từ client (nếu có), client truyền sẽ ưu tiên
if payload.headers:
headers.update(payload.headers)
try:
async with httpx.AsyncClient(timeout=15) as client:
response = await client.request(
payload.method.upper(),
payload.url,
headers=headers,
params=payload.params,
json=payload.body if isinstance(payload.body, dict) else None,
data=payload.body if isinstance(payload.body, str) else None,
)
try:
resp_json = response.json()
except Exception:
resp_json = {"error": "response is not JSON", "raw": response.text}
return {
"status_code": response.status_code,
"headers": dict(response.headers),
"data": resp_json
}
except httpx.RequestError as exc:
raise HTTPException(status_code=502, detail=f"Request error: {exc}")
except Exception as exc:
raise HTTPException(status_code=500, detail=f"Other error: {exc}")