| from fastapi import FastAPI, HTTPException |
| from pydantic import BaseModel |
| import httpx |
|
|
| |
| 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 |
| body: dict | str | None = None |
| data_source: str = "SSI" |
| 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): |
| |
| headers = get_headers( |
| data_source=payload.data_source, |
| random_agent=payload.random_agent, |
| browser=payload.browser, |
| platform=payload.platform |
| ) |
| |
| 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}") |