-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
108 lines (80 loc) · 2.5 KB
/
main.py
File metadata and controls
108 lines (80 loc) · 2.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
import sys
import argparse
import importlib
from textwrap import dedent
from src.server import HTTPServer
from src.cli import log
from src.config import VERSION, DEFAULT_HOST, DEFAULT_PORT, DEFAULT_WORKERS
version = VERSION
def load_app(app_path: str):
if ":" not in app_path:
raise ValueError("App must be in format module:callable")
module_name, app_name = app_path.split(":", 1)
module = importlib.import_module(module_name)
app = getattr(module, app_name)
if not callable(app):
log(f"App {app_name} is not callable", level="ERROR")
raise TypeError(f"{app_name} is not callable")
return app
def main():
description = dedent(
"""
Mini Gunicorn-like Custom WSGI Server
The app should be provided as:
module:callable
Example:
examples.flask_app:app
"""
)
epilog = dedent(
"""
Examples:
Run with default settings:
python main.py examples.flask_app:app
Run on all interfaces:
python main.py examples.flask_app:app --host 0.0.0.0
Run on custom port:
python main.py examples.flask_app:app --port 9000
Run with 4 workers:
python main.py examples.flask_app:app --workers 4
"""
)
parser = argparse.ArgumentParser(
prog="mini-gunicorn",
description=description,
epilog=epilog,
formatter_class=argparse.RawDescriptionHelpFormatter,
)
parser.add_argument("app", help="WSGI app in format module:callable")
parser.add_argument(
"--host", default=DEFAULT_HOST, help="Bind host (default: 127.0.0.1)"
)
parser.add_argument(
"--port", type=int, default=DEFAULT_PORT, help="Bind port (default: 8000)"
)
parser.add_argument(
"--workers",
type=int,
default=DEFAULT_WORKERS,
help="Number of worker processes (default: 1)",
)
parser.add_argument(
"--version",
action="version",
version=f"%(prog)s {VERSION}",
)
args = parser.parse_args()
try:
app = load_app(args.app)
except Exception as e:
print(f"Error loading app: {e}")
sys.exit(1)
server = HTTPServer(
host=args.host,
port=args.port,
app=app,
workers=args.workers,
)
server.serve_forever()
if __name__ == "__main__":
main()