hrsprojects commited on
Commit
fd2f1d1
·
verified ·
1 Parent(s): ec3a772

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +10 -24
app.py CHANGED
@@ -1,38 +1,24 @@
1
  from fastapi import FastAPI
2
- from fastapi.responses import JSONResponse
3
- from duckduckgo_search import DDGS
4
  from fastapi.middleware.cors import CORSMiddleware
 
5
 
6
- # Initialize FastAPI app
7
  app = FastAPI()
8
 
9
- # CORS Middleware to allow cross-origin requests
10
  app.add_middleware(
11
  CORSMiddleware,
12
- allow_origins=["*"], # Allow all origins
13
  allow_credentials=True,
14
- allow_methods=["*"], # Allow all methods (GET, POST, etc.)
15
- allow_headers=["*"], # Allow all headers
16
  )
17
 
18
- @app.get("/")
19
- def home():
20
- return {"message": "DuckDuckGo Search API is running!"}
21
-
22
  @app.get("/search")
23
- def search(query: str, max_results: int = 5):
24
  try:
25
- # Use headers to mimic a real browser
26
- headers = {
27
- "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:109.0) Gecko/20100101 Firefox/110.0"
28
- }
29
-
30
- # Use DuckDuckGo Search API with HTML backend
31
- with DDGS(headers=headers) as ddgs:
32
- results = list(ddgs.text(query, max_results=max_results, backend="html"))
33
-
34
- return JSONResponse(content={"query": query, "results": results})
35
-
36
  except Exception as e:
37
- return JSONResponse(content={"error": str(e)}, status_code=500)
38
 
 
1
  from fastapi import FastAPI
 
 
2
  from fastapi.middleware.cors import CORSMiddleware
3
+ from duckduckgo_search import DDGS
4
 
 
5
  app = FastAPI()
6
 
7
+ # CORS issue fix
8
  app.add_middleware(
9
  CORSMiddleware,
10
+ allow_origins=["*"],
11
  allow_credentials=True,
12
+ allow_methods=["*"],
13
+ allow_headers=["*"],
14
  )
15
 
 
 
 
 
16
  @app.get("/search")
17
+ async def search_duckduckgo(query: str):
18
  try:
19
+ with DDGS() as ddgs:
20
+ results = ddgs.text(query, max_results=10)
21
+ return {"query": query, "results": results}
 
 
 
 
 
 
 
 
22
  except Exception as e:
23
+ return {"error": str(e)}
24