Debian Codegraph @

src/rdflib_endpoint/sparql_endpoint.py

raw
1 import time
2 from typing import Any, Callable, Dict, Optional, Union
3
4 from fastapi import FastAPI, Request, Response
5 from fastapi.middleware.cors import CORSMiddleware
6 from rdflib import Dataset, Graph
7 from rdflib.query import Processor
8
9 from rdflib_endpoint.sparql_router import SparqlRouter
10 from rdflib_endpoint.utils import Defaults, QueryExample
11
12
13 class SparqlEndpoint(FastAPI):
14 """Class to deploy a SPARQL endpoint using a RDFLib Graph."""
15
16 def __init__(
17 self,
18 *args: Any,
19 path: str = "/",
20 title: str = Defaults.title,
21 description: str = Defaults.description,
22 version: str = Defaults.version,
23 graph: Union[None, Graph, Dataset] = None,
24 functions: Optional[Dict[str, Callable[..., Any]]] = None,
25 processor: Union[str, Processor] = "sparql",
26 custom_eval: Optional[Callable[..., Any]] = None,
27 enable_update: bool = False,
28 cors_enabled: bool = True,
29 public_url: str = Defaults.public_url,
30 example_query: str = Defaults.example,
31 example_queries: Optional[Dict[str, QueryExample]] = None,
32 favicon: str = Defaults.favicon,
33 **kwargs: Any,
34 ) -> None:
35 """
36 Create a SPARQL endpoint.
37
38 It's mainly a wrapper to include the SPARQL router. Everything happens in the router.
39 """
40 self.title = title
41 self.description = description
42 self.version = version
43
44 # Instantiate FastAPI
45 super().__init__(
46 *args,
47 title=title,
48 description=description,
49 version=version,
50 **kwargs,
51 )
52
53 sparql_router = SparqlRouter(
54 path=path,
55 title=title,
56 description=description,
57 version=version,
58 graph=graph,
59 functions=functions,
60 processor=processor,
61 custom_eval=custom_eval,
62 enable_update=enable_update,
63 public_url=public_url,
64 example_query=example_query,
65 example_queries=example_queries,
66 favicon=favicon,
67 )
68 self.include_router(sparql_router)
69
70 if cors_enabled:
71 self.add_middleware(
72 CORSMiddleware,
73 allow_origins=["*"],
74 allow_credentials=True,
75 allow_methods=["*"],
76 allow_headers=["*"],
77 )
78
79 @self.middleware("http")
80 async def add_process_time_header(request: Request, call_next: Any) -> Response:
81 """Add a Server-Timing header with the total processing time for each request."""
82 start_time = time.time()
83 response: Response = await call_next(request)
84 response.headers["Server-Timing"] = f"total;dur={time.time() - start_time}"
85 return response