config.py 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. from pydantic import BaseModel
  2. import inspect
  3. import ast
  4. import os
  5. class Config(BaseModel):
  6. # NOTE: should be in sync with ui.run arguments
  7. host: str = '0.0.0.0'
  8. port: int = 80
  9. title: str = 'NiceGUI'
  10. favicon: str = 'favicon.png'
  11. reload: bool = True
  12. show: bool = True
  13. for f in reversed(inspect.stack()):
  14. if os.path.basename(f.filename) not in ('<string>', 'spawn.py', 'runpy.py'):
  15. filepath = f.filename
  16. break
  17. else:
  18. raise Exception("Could not find main script in stacktrace")
  19. with open(filepath) as f:
  20. source = f.read()
  21. for node in ast.parse(source).body:
  22. try:
  23. func = node.value.func
  24. if func.value.id == 'ui' and func.attr == 'run':
  25. args = {
  26. keyword.arg: keyword.value.value
  27. for keyword in node.value.keywords
  28. }
  29. config = Config(**args)
  30. break
  31. except AttributeError:
  32. continue
  33. else:
  34. raise Exception('Could not find ui.run() command')
  35. os.environ['HOST'] = config.host
  36. os.environ['PORT'] = str(config.port)