| 12345678910111213141516171819202122232425262728293031323334 |
- from fastapi import FastAPI, HTTPException, Query
- import httpx
- import re
- app = FastAPI()
- @app.get("/")
- def read_root():
- return {"message": "FastAPI is running"}
- @app.get("/fetch-url/")
- async def fetch_url(url: str = Query(..., description="The URL to fetch")):
- async with httpx.AsyncClient() as client:
- try:
- response = await client.get(url)
- response.raise_for_status() # Check if the request was successful
- content = response.text
- price = '$' + re.findall('mainPrice__tM6aY"><p title="\$(.*?)"', content)[0]
- percentage = re.findall('"name\\":\\"Percent Change 24H\\",\"value\\":(.*?)},', content)[0] + '%'
- res = f"{price} {percentage}"
- return res
- except httpx.RequestError as e:
- raise HTTPException(status_code=400, detail=f"An error occurred while requesting {url}: {str(e)}")
- except httpx.HTTPStatusError as e:
- raise HTTPException(status_code=e.response.status_code,
- detail=f"Error response {e.response.status_code} while requesting {url}: {str(e)}")
- if __name__ == "__main__":
- import uvicorn
- uvicorn.run(app, host="0.0.0.0", port=34567)
|