-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapi.py
48 lines (38 loc) · 1.53 KB
/
api.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
import os
from fastapi import FastAPI, HTTPException, Request
from scraper import search_papers, get_working_proxy, init_proxies
from dotenv import load_dotenv
app = FastAPI()
# Load environment variables from .env file
load_dotenv()
# Retrieve the API keys from the environment variable and split into a set
API_KEYS = set(os.getenv("API_KEYS", "").split(","))
if not API_KEYS:
raise Exception("API_KEYS environment variable is not set.")
@app.on_event("startup")
async def startup_event():
init_proxies()
def validate_api_key(api_key: str):
"""Validate the provided API key."""
return api_key in API_KEYS
@app.get("/search/")
async def search(request: Request, keyword: str):
# Extract the API key from the request headers
api_key = request.headers.get("x-api-key")
if not api_key or not validate_api_key(api_key):
raise HTTPException(status_code=401, detail="Invalid or missing API key")
if not keyword:
raise HTTPException(status_code=400, detail="Keyword is required")
working_proxy = get_working_proxy() # Attempt to get a working proxy
if not working_proxy:
raise HTTPException(status_code=500, detail="No working proxies available.")
try:
results = search_papers(keyword, working_proxy)
return results
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
#show the privacy.txt in the root of the project
@app.get("/privacy")
async def privacy():
with open("privacy.txt", "r") as file:
return file.read()