created a type model for the config file

This commit is contained in:
Kristian Krsnik 2024-08-03 01:05:22 +02:00
parent 3f8323d297
commit 3063bc0167
Signed by: Kristian
GPG Key ID: FD1330AC9F909E85
3 changed files with 19 additions and 30 deletions

View File

@ -10,7 +10,7 @@
"log": "-", "log": "-",
"buffer-size": "4KiB", "buffer-size": "4KiB",
"max-size": "2GB", "max-size": "2GB",
"keys": [ "api-keys": [
"TESTKEY" "TESTKEY"
], ],
"max-data": "10GB", "max-data": "10GB",

View File

@ -1,27 +1,24 @@
from pydantic import BaseModel, ConfigDict, field_validator from pydantic import BaseModel, Field, ConfigDict, field_validator
from .utils import convert_to_bytes from .utils import convert_to_bytes
# class Config(BaseModel):
# host: str
# port: int
# buffer_size: int = 4 * 1024 # 4KB
# max_size: int = 2 * 1024 * 1024 * 1024 # 2GB
# max_data: int = 0 # unlimited
# api_keys = set[str]
# database = str
# model_config = ConfigDict(extra='allow') class Config(BaseModel):
host: str
port: int
buffer_size: int = Field(alias='buffer-size', default=4 * 1024) # 4KB
max_size: int = Field(alias='max-size', default=2 * 1024 ** 3) # 2GB
max_data: int = Field(alias='max-data', default=0) # unlimited
api_keys: set[str] = Field(alias='api-keys')
database: str
log: str = '-'
# @field_validator('buffer_size', 'max_size', 'max_data') model_config = ConfigDict(extra='forbid')
# @classmethod
# def convert_size(cls, value: int | str) -> int:
# return convert_to_bytes(value)
@field_validator('buffer_size', 'max_size', 'max_data', mode='before')
# TODO @classmethod
# class DataBase(BaseModel): def convert_size(cls, value: int | str) -> int:
# model_config = ConfigDict(extra='forbid') return convert_to_bytes(value)
class TestDataBody(BaseModel): class TestDataBody(BaseModel):

14
testdata/main.py vendored
View File

@ -8,6 +8,7 @@ import uvicorn
from .utils import convert_to_bytes, save_database from .utils import convert_to_bytes, save_database
from .api import create_api from .api import create_api
from .custom_types import Config
# Setup Parser # Setup Parser
@ -35,14 +36,5 @@ def run(host: str, port: int, api_keys: set[str], max_size: int, max_data: int,
def main(): def main():
args = parse_cli_arguments(sys.argv[1:]) args = parse_cli_arguments(sys.argv[1:])
config = json.load(args.config) config = Config.model_validate_json(args.config.read())
run(**config.model_dump(exclude={'log'}))
host = config['host']
port = config['port']
buffer_size = convert_to_bytes(config['buffer-size'])
max_size = convert_to_bytes(config['max-size'])
max_data = convert_to_bytes(config['max-data'])
api_keys = config['keys']
database = config['database']
run(host, port, api_keys, max_size, max_data, database, buffer_size)