hrsprojects commited on
Commit
3809b9b
·
verified ·
1 Parent(s): d3ff814

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +23 -15
app.py CHANGED
@@ -1,17 +1,18 @@
1
- from fastapi import FastAPI, Query
2
- from fastapi.middleware.cors import CORSMiddleware
3
  from duckduckgo_search import DDGS
4
- import uvicorn
5
 
 
6
  app = FastAPI()
7
 
8
- # Enable CORS for all origins (fixes CORS issues)
9
  app.add_middleware(
10
  CORSMiddleware,
11
- allow_origins=["*"],
12
  allow_credentials=True,
13
- allow_methods=["*"],
14
- allow_headers=["*"],
15
  )
16
 
17
  @app.get("/")
@@ -19,12 +20,19 @@ def home():
19
  return {"message": "DuckDuckGo Search API is running!"}
20
 
21
  @app.get("/search")
22
- def search(query: str = Query(..., title="Search Query"), max_results: int = 10):
23
- """ DuckDuckGo Search API - Returns top search results. """
24
- with DDGS() as ddgs:
25
- results = list(ddgs.text(query, max_results=max_results))
26
- return {"query": query, "results": results}
 
 
 
 
 
 
 
 
 
 
27
 
28
- # Ensure the API runs properly
29
- if __name__ == "__main__":
30
- uvicorn.run(app, host="0.0.0.0", port=7860)
 
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("/")
 
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