Skip to content

Commit

Permalink
Add API tools
Browse files Browse the repository at this point in the history
  • Loading branch information
ejohb committed Sep 18, 2024
1 parent 3de4aba commit 3998ccd
Show file tree
Hide file tree
Showing 4 changed files with 82 additions and 2 deletions.
5 changes: 5 additions & 0 deletions fmtr/tools/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -91,6 +91,11 @@
except ImportError as exception:
merging = merge = MissingExtraMockModule('merge', exception)

try:
from fmtr.tools import api_tools as api
except ImportError as exception:
api = MissingExtraMockModule('api', exception)


__all__ = [
'config',
Expand Down
74 changes: 74 additions & 0 deletions fmtr/tools/api_tools.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
import uvicorn
from dataclasses import dataclass
from fastapi import FastAPI
from typing import Callable, List, Optional, Union

from fmtr.tools.iterator_tools import enlist
from fmtr.tools.logging_tools import logger


@dataclass
class Endpoint:
"""
Endpoint-as-method config
"""
method: Callable
path: str
tags: Optional[Union[str, List[str]]] = None
method_http: Optional[Callable] = None

def __post_init__(self):
self.tags = enlist(self.tags)


class ApiBase:
"""
Simple API base class, generalising endpoint-as-method config.
"""
TITLE = 'Base API'
HOST = '0.0.0.0'
PORT = 8080

def add_endpoint(self, endpoint: Endpoint):
"""
Add endpoints from definitions using a single dataclass instance.
"""
method_http = endpoint.method_http or self.app.post
doc = (endpoint.method.__doc__ or '').strip() or None

method_http(
endpoint.path,
tags=endpoint.tags,
description=doc,
summary=doc
)(endpoint.method)

def __init__(self):
self.app = FastAPI(title=self.TITLE)

for endpoint in self.get_endpoints():
self.add_endpoint(endpoint)

def get_endpoints(self) -> List[Endpoint]:
"""
Define endpoints using a dataclass instance.
"""
endpoints = [

]

return endpoints

@classmethod
def launch(cls):
self = cls()
logger.info(f'Launching API {cls.TITLE}...')
uvicorn.run(self.app, host=self.HOST, port=self.PORT)
2 changes: 1 addition & 1 deletion fmtr/tools/version
Original file line number Diff line number Diff line change
@@ -1 +1 @@
0.8.18
0.8.19
3 changes: 2 additions & 1 deletion requirements.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,8 @@
'spaces': ['netrc'],
'netrc': ['tinynetrc'],
'hfh': ['huggingface_hub'],
'merging': ['deepmerge']
'merging': ['deepmerge'],
'api': ['fastapi', 'uvicorn', 'logging']
}

CONSOLE_SCRIPTS = [
Expand Down

0 comments on commit 3998ccd

Please sign in to comment.