5
5
from asyncio import Queue as AsyncQueue
6
6
from threading import Event as ThreadEvent , Thread
7
7
from queue import Queue as ThreadQueue
8
- from typing import Union , Tuple , Dict , Any , Optional , Callable , NamedTuple
8
+ from typing import Union , Tuple , Dict , Any , Optional , Callable , NamedTuple , Type , cast
9
9
10
10
from typing_extensions import TypedDict
11
11
from flask import Flask , Blueprint , send_from_directory , redirect , url_for
17
17
18
18
import idom
19
19
from idom .client .manage import BUILD_DIR
20
- from idom .core .layout import LayoutEvent , Layout
20
+ from idom .core .layout import LayoutEvent , Layout , LayoutUpdate
21
21
from idom .core .dispatcher import AbstractDispatcher , SingleViewDispatcher
22
22
23
23
from .base import AbstractRenderServer
@@ -36,7 +36,7 @@ class Config(TypedDict, total=False):
36
36
class FlaskRenderServer (AbstractRenderServer [Flask , Config ]):
37
37
"""Base class for render servers which use Flask"""
38
38
39
- _dispatcher_type : AbstractDispatcher
39
+ _dispatcher_type : Type [ AbstractDispatcher ]
40
40
_wsgi_server : pywsgi .WSGIServer
41
41
42
42
def stop (self , timeout : Optional [float ] = None ) -> None :
@@ -56,10 +56,8 @@ def _create_config(self, config: Optional[Config]) -> Config:
56
56
"cors" : False ,
57
57
"serve_static_files" : True ,
58
58
"redirect_root_to_index" : True ,
59
+ ** (config or {}), # type: ignore
59
60
}
60
- if config is not None :
61
- # BUG: https://github.com/python/mypy/issues/6462
62
- new_config .update (config ) # type: ignore
63
61
return new_config
64
62
65
63
def _default_application (self , config : Config ) -> Flask :
@@ -79,12 +77,12 @@ def _setup_application(self, config: Config, app: Flask) -> None:
79
77
80
78
sockets = Sockets (app )
81
79
82
- @sockets .route (urljoin (config ["url_prefix" ], "/stream" ))
80
+ @sockets .route (urljoin (config ["url_prefix" ], "/stream" )) # type: ignore
83
81
def model_stream (ws : WebSocket ) -> None :
84
82
def send (value : Any ) -> None :
85
83
ws .send (json .dumps (value ))
86
84
87
- def recv () -> LayoutEvent :
85
+ def recv () -> Optional [ LayoutEvent ] :
88
86
event = ws .receive ()
89
87
if event is not None :
90
88
return LayoutEvent (** json .loads (event ))
@@ -104,20 +102,20 @@ def _setup_blueprint_routes(self, config: Config, blueprint: Blueprint) -> None:
104
102
if config ["serve_static_files" ]:
105
103
106
104
@blueprint .route ("/client/<path:path>" )
107
- def send_build_dir (path ) :
105
+ def send_build_dir (path : str ) -> Any :
108
106
return send_from_directory (str (BUILD_DIR ), path )
109
107
110
108
if config ["redirect_root_to_index" ]:
111
109
112
110
@blueprint .route ("/" )
113
- def redirect_to_index ():
111
+ def redirect_to_index () -> Any :
114
112
return redirect (url_for ("idom.send_build_dir" , path = "index.html" ))
115
113
116
114
def _setup_application_did_start_event (
117
115
self , config : Config , app : Flask , event : ThreadEvent
118
116
) -> None :
119
117
@app .before_first_request
120
- def server_did_start ():
118
+ def server_did_start () -> None :
121
119
event .set ()
122
120
123
121
def _run_application (
@@ -149,8 +147,8 @@ def _generic_run_application(
149
147
port : int = 5000 ,
150
148
debug : bool = False ,
151
149
* args : Any ,
152
- ** kwargs ,
153
- ):
150
+ ** kwargs : Any ,
151
+ ) -> None :
154
152
if debug :
155
153
logging .basicConfig (level = logging .DEBUG ) # pragma: no cover
156
154
logging .debug ("Starting server..." )
@@ -180,20 +178,20 @@ def run_dispatcher_in_thread(
180
178
dispatch_thread_info_created = ThreadEvent ()
181
179
dispatch_thread_info_ref : idom .Ref [Optional [_DispatcherThreadInfo ]] = idom .Ref (None )
182
180
183
- def run_dispatcher ():
181
+ def run_dispatcher () -> None :
184
182
loop = asyncio .new_event_loop ()
185
183
asyncio .set_event_loop (loop )
186
184
187
- thread_send_queue = ThreadQueue ()
188
- async_recv_queue = AsyncQueue ()
185
+ thread_send_queue : "ThreadQueue[LayoutUpdate]" = ThreadQueue ()
186
+ async_recv_queue : "AsyncQueue[LayoutEvent]" = AsyncQueue ()
189
187
190
188
async def send_coro (value : Any ) -> None :
191
189
thread_send_queue .put (value )
192
190
193
191
async def recv_coro () -> Any :
194
192
return await async_recv_queue .get ()
195
193
196
- async def main ():
194
+ async def main () -> None :
197
195
async with make_dispatcher () as dispatcher :
198
196
await dispatcher .run (send_coro , recv_coro , context )
199
197
@@ -212,12 +210,12 @@ async def main():
212
210
Thread (target = run_dispatcher , daemon = True ).start ()
213
211
214
212
dispatch_thread_info_created .wait ()
215
- dispatch_thread_info = dispatch_thread_info_ref .current
213
+ dispatch_thread_info = cast ( _DispatcherThreadInfo , dispatch_thread_info_ref .current )
216
214
assert dispatch_thread_info is not None
217
215
218
216
stop = ThreadEvent ()
219
217
220
- def run_send ():
218
+ def run_send () -> None :
221
219
while not stop .is_set ():
222
220
send (dispatch_thread_info .thread_send_queue .get ())
223
221
@@ -242,17 +240,19 @@ def run_send():
242
240
243
241
class _DispatcherThreadInfo (NamedTuple ):
244
242
dispatch_loop : asyncio .AbstractEventLoop
245
- dispatch_future : asyncio .Future
246
- thread_send_queue : ThreadQueue
247
- async_recv_queue : AsyncQueue
243
+ dispatch_future : " asyncio.Future[Any]"
244
+ thread_send_queue : " ThreadQueue[LayoutUpdate]"
245
+ async_recv_queue : " AsyncQueue[LayoutEvent]"
248
246
249
247
250
- class _StartCallbackWSGIServer (pywsgi .WSGIServer ):
251
- def __init__ (self , before_first_request : Callable [[], None ], * args , ** kwargs ):
248
+ class _StartCallbackWSGIServer (pywsgi .WSGIServer ): # type: ignore
249
+ def __init__ (
250
+ self , before_first_request : Callable [[], None ], * args : Any , ** kwargs : Any
251
+ ) -> None :
252
252
self ._before_first_request_callback = before_first_request
253
253
super ().__init__ (* args , ** kwargs )
254
254
255
- def update_environ (self ):
255
+ def update_environ (self ) -> None :
256
256
"""
257
257
Called before the first request is handled to fill in WSGI environment values.
258
258
0 commit comments