-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.py
More file actions
55 lines (43 loc) · 2.05 KB
/
server.py
File metadata and controls
55 lines (43 loc) · 2.05 KB
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
49
50
51
52
53
54
55
# This script implements a FastAPI server that provides an API endpoint
# for retrieving information about packages from a repository,
# based on user-provided query parameters.
import json
import os
from fastapi import FastAPI, HTTPException, Depends
from pydantic import BaseModel
from typing import Optional
# Usage example:
# Return the complete list of packages for a given branch and architecture
# curl -X GET "http://127.0.0.1:8000/packages/?architecture=amd64&branch=main"
# Return only the information of a specific package
# curl -X GET "http://127.0.0.1:8000/packages/?package_name=0ad&architecture=amd64&branch=main"
# Use of Pydantic for validation of query parameters
class PackageQueryParams(BaseModel):
package_name: Optional[str] = None
architecture: str
branch: str
app = FastAPI()
def get_query_params(query_params: PackageQueryParams = Depends()):
return query_params
# Main endpoint
@app.get("/packages/")
async def get_packages(query_params: PackageQueryParams = Depends(get_query_params)):
try:
# Access validated input using query_params.package_name, query_params.architecture, query_params.branch
# Build the path to the Packages.json file
file_path = os.path.join("output", query_params.branch, f"binary-{query_params.architecture}", "Packages.json")
# Read the contents of the Packages.json file.
with open(file_path, "r") as file:
packages_data = json.load(file)
if query_params.package_name:
# If a package name is specified, it searches only for that package
package = next((pkg for pkg in packages_data if pkg["Package"] == query_params.package_name), None)
if package:
return [package]
else:
raise HTTPException(status_code=404, detail="Package not found")
else:
# If no package name is specified, return the full list of packages
return packages_data
except FileNotFoundError:
raise HTTPException(status_code=404, detail="Repository not found")