Spaces:
Runtime error
Runtime error
Update app.py
Browse files
app.py
CHANGED
@@ -1,17 +1,18 @@
|
|
1 |
-
from fastapi import FastAPI
|
2 |
-
from fastapi.
|
3 |
from duckduckgo_search import DDGS
|
4 |
-
import
|
5 |
|
|
|
6 |
app = FastAPI()
|
7 |
|
8 |
-
#
|
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
|
23 |
-
|
24 |
-
|
25 |
-
|
26 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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 |
|
|
|
|
|
|