77from aiohttp import web
88import asyncio
99import nest_asyncio
10+ from watchfiles import awatch
1011
1112from lambda_gateway .event_proxy import EventProxy
1213from lambda_gateway .request_handler import LambdaRequestHandler
@@ -64,14 +65,20 @@ def get_opts():
6465 default = '2.0' ,
6566 help = 'API Gateway payload version [default: 2.0]' ,
6667 )
68+ parser .add_argument (
69+ '-w' , '--watch' ,
70+ dest = 'watch' ,
71+ help = 'Watch the base python path and exit if files change.' ,
72+ action = "store_true"
73+ )
6774 parser .add_argument (
6875 'SAM_TEMPLATE' ,
6976 help = 'Path to SAM YAML template' ,
7077 )
7178 return parser .parse_args ()
7279
7380
74- async def run_server (app , bind , port ):
81+ async def run_server (app , bind , port , path , quit_on_change = True ):
7582 """
7683 Run Lambda Gateway server.
7784 """
@@ -80,8 +87,19 @@ async def run_server(app, bind, port):
8087 site = web .TCPSite (runner , bind , port )
8188 await site .start ()
8289
83- while True :
84- await asyncio .sleep (3600 ) # sleep forever
90+ stop_event = asyncio .Event ()
91+
92+ # Wait for a source file to change, then quit
93+ async for changes in awatch (path , stop_event = stop_event ):
94+ print (f"Source file changed: { changes } " )
95+ if quit_on_change :
96+ print ('Exiting so you can reload' )
97+ stop_event .set () # `break` would probably be enough BTW
98+ else :
99+ print ("No reload or quit - try -w flag" )
100+
101+ await runner .cleanup ()
102+ return True
85103
86104
87105def main ():
@@ -108,12 +126,9 @@ def main():
108126
109127 app .add_routes (routes )
110128
111- # Start server
112- #web.run_app(app, host=opts.bind, port=opts.port)
113-
114- asyncio .run (run_server (app , opts .bind , opts .port ))
115-
129+ asyncio .run (run_server (app , opts .bind , opts .port , base_python_path , opts .watch ))
116130
131+ os ._exit (0 ) # OS exit because awatch thread seems to still be locked; without this it hangs
117132
118133
119134if __name__ == '__main__' : # pragma: no cover
0 commit comments