File size: 2,101 Bytes
150b9cd | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 | 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}") |