mirror of
https://github.com/trustgraph-ai/trustgraph.git
synced 2026-06-03 03:45:13 +02:00
82 lines
2 KiB
Python
82 lines
2 KiB
Python
|
|
import asyncio
|
|
from aiohttp import web
|
|
import logging
|
|
|
|
logger = logging.getLogger("endpoint")
|
|
logger.setLevel(logging.INFO)
|
|
|
|
class StreamEndpoint:
|
|
|
|
def __init__(self, endpoint_path, auth, dispatcher, method="POST"):
|
|
|
|
self.path = endpoint_path
|
|
|
|
self.auth = auth
|
|
self.operation = "service"
|
|
self.method = method
|
|
|
|
self.dispatcher = dispatcher
|
|
|
|
async def start(self):
|
|
pass
|
|
|
|
def add_routes(self, app):
|
|
|
|
if self.method == "POST":
|
|
app.add_routes([
|
|
web.post(self.path, self.handle),
|
|
])
|
|
elif self.method == "GET":
|
|
app.add_routes([
|
|
web.get(self.path, self.handle),
|
|
])
|
|
else:
|
|
raise RuntimeError("Bad method" + self.method)
|
|
|
|
async def handle(self, request):
|
|
|
|
logger.debug(f"Processing request: {request.path}")
|
|
|
|
try:
|
|
ht = request.headers["Authorization"]
|
|
tokens = ht.split(" ", 2)
|
|
if tokens[0] != "Bearer":
|
|
return web.HTTPUnauthorized()
|
|
token = tokens[1]
|
|
except:
|
|
token = ""
|
|
|
|
if not self.auth.permitted(token, self.operation):
|
|
return web.HTTPUnauthorized()
|
|
|
|
try:
|
|
|
|
data = request.content
|
|
|
|
async def error(err):
|
|
return web.HTTPInternalServerError(text = err)
|
|
|
|
async def ok(
|
|
status=200, reason="OK", type="application/octet-stream"
|
|
):
|
|
response = web.StreamResponse(
|
|
status = status, reason = reason,
|
|
headers = {"Content-Type": type}
|
|
)
|
|
await response.prepare(request)
|
|
return response
|
|
|
|
resp = await self.dispatcher.process(
|
|
data, error, ok, request
|
|
)
|
|
|
|
return resp
|
|
|
|
except Exception as e:
|
|
logging.error(f"Exception: {e}")
|
|
|
|
return web.json_response(
|
|
{ "error": str(e) }
|
|
)
|
|
|