config.py 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. from pydantic import BaseModel
  2. import inspect
  3. import ast
  4. import os
  5. from . import globals
  6. class Config(BaseModel):
  7. # NOTE: should be in sync with ui.run arguments
  8. host: str = '0.0.0.0'
  9. port: int = 8080
  10. title: str = 'NiceGUI'
  11. favicon: str = 'favicon.ico'
  12. reload: bool = True
  13. show: bool = True
  14. uvicorn_logging_level: str = 'warning'
  15. interactive: bool = False
  16. main_page_classes: str = 'q-ma-md column items-start'
  17. excluded_endings = (
  18. '<string>',
  19. 'spawn.py',
  20. 'runpy.py',
  21. os.path.join('debugpy', 'server', 'cli.py'),
  22. os.path.join('debugpy', '__main__.py'),
  23. )
  24. for f in reversed(inspect.stack()):
  25. if not any(f.filename.endswith(ending) for ending in excluded_endings):
  26. filepath = f.filename
  27. break
  28. else:
  29. raise Exception("Could not find main script in stacktrace")
  30. try:
  31. with open(filepath) as f:
  32. source = f.read()
  33. except FileNotFoundError:
  34. print('Could not find main script. Starting with interactive mode.', flush=True)
  35. config = Config(interactive=True)
  36. else:
  37. for node in ast.walk(ast.parse(source)):
  38. try:
  39. func = node.value.func
  40. if func.value.id == 'ui' and func.attr == 'run':
  41. args = {
  42. keyword.arg:
  43. keyword.value.n if isinstance(keyword.value, ast.Num) else
  44. keyword.value.s if isinstance(keyword.value, ast.Str) else
  45. keyword.value.value
  46. for keyword in node.value.keywords
  47. }
  48. config = Config(**args)
  49. break
  50. except AttributeError:
  51. continue
  52. else:
  53. raise Exception('Could not find ui.run() command')
  54. os.environ['HOST'] = config.host
  55. os.environ['PORT'] = str(config.port)
  56. os.environ["STATIC_DIRECTORY"] = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'static')
  57. #os.environ["TEMPLATES_DIRECTORY"] = os.path.join(os.environ["STATIC_DIRECTORY"], 'templates')
  58. globals.config = config