def test_flexx_in_thread4(): """ Test threading starting server in other thread where it is created. """ res = [] loop = IOLoop() loop.make_current() app.create_server() def try_start(): try: app.stop() app.start() except RuntimeError: res.append('start-fail') else: res.append('start-ok') def main(): app.create_server() try_start() # Try to start server that was created in other thread -> fail t = threading.Thread(target=try_start) t.start() t.join() # Try to start in same thread as created -> ok t = threading.Thread(target=main) t.start() t.join() assert res == ['start-fail', 'start-ok']
def test_flexx_in_thread1(): """ Test threading and ioloop selection. """ def main(): asyncio.set_event_loop(loop2) app.create_server() # Create 3 loops, nr 2 is made current in the thread loop1 = asyncio.new_event_loop() loop2 = asyncio.new_event_loop() loop3 = asyncio.new_event_loop() asyncio.set_event_loop(loop1) server1 = app.create_server() t = threading.Thread(target=main) t.start() t.join() server2 = app.current_server() # still current as set by the thread asyncio.set_event_loop(loop3) server3 = app.create_server() assert server1._loop is loop1 assert server2._loop is loop2 assert server3._loop is loop3
def test_flexx_in_thread1(): """ Test threading and ioloop selection. """ def main(): loop2.make_current() app.create_server() # Create 3 loops, nr 2 is made current in the thread loop1 = IOLoop() loop2 = IOLoop() loop3 = IOLoop() loop1.make_current() server1 = app.create_server() t = threading.Thread(target=main) t.start() t.join() server2 = app.current_server() # still current as set by the thread loop3.make_current() server3 = app.create_server() assert server1._loop is loop1 assert server2._loop is loop2 assert server3._loop is loop3
def test_rebinding_ioloop(): """ Test recreating server objects, and its binding to the current ioloop. """ res = [] def add_res(i): res.append(i) # Create new ioloop loop = IOLoop() loop.make_current() # Create new flexx server, which binds to that loop server1 = app.create_server() assert server1 is app.current_server() # assert loop is server1._loop # Create new ioloop loop = IOLoop() loop.make_current() # This is a new loop assert loop is not server1._loop # Create new flexx server, which binds to that loop server2 = app.create_server() assert server2 is app.current_server() assert server1 is not server2 # assert loop is server2._loop
def main(): # Create fresh ioloop and make flexx use it loop = IOLoop() loop.make_current() app.create_server() # Create model and manipulate prop model = MyModel1() model.foo = 3 model.foo = 4 # Run mainloop for one iterartion app.call_later(0, app.stop) app.start()
def test_flexx_in_thread3(): """ Test starting and creating server when a server is currently running. """ res = [] def main(): # Create fresh ioloop and make flexx use it loop = IOLoop() loop.make_current() app.create_server() app.start() def try_start(): try: app.start() except RuntimeError: res.append('start-fail') def try_create(): try: main() except RuntimeError: res.append('create-fail') t = threading.Thread(target=main) t.start() # With that thread running ... while not app.current_server()._running: time.sleep(0.01) with raises(RuntimeError): app.start() with raises(RuntimeError): app.create_server() t1 = threading.Thread(target=try_start) t1.start() t1.join() t2 = threading.Thread(target=try_create) t2.start() t2.join() # Stop app.stop() # Start does not work, but we can stop it! t.join() # Otherwise it would never join # Note that we cannot start it right after calling stop, because it wont # stop *at once*. We need to join first. assert res == ['start-fail', 'create-fail']
def main(): # Create fresh ioloop and make flexx use it # event.loop.reset() loop = asyncio.new_event_loop() asyncio.set_event_loop(loop) app.create_server() # Create component and manipulate prop comp = MyComponent1() comp.set_foo(3) comp.set_foo(4) # Run mainloop for one iterartion loop.call_later(0.2, app.stop) app.start()
def test_flexx_in_thread5(): """ Test using loop arg for easier use. """ res = [] server = app.create_server(loop=asyncio.new_event_loop()) assert server.serving # note: mmmm, I don't particularly like this, but need it to get Tornado working assert server._loop is asyncio.get_event_loop() def main(): # likewise, we cannot do this atm # app.stop() # app.start() try: curloop = asyncio.get_event_loop() except RuntimeError: res.append(4) else: assert server._loop is curloop res.append(3) t = threading.Thread(target=main) t.start() t.join() assert res == [4]
def runner(cls): # Run with a fresh server server = app.create_server(port=0, new_loop=True) t = app.launch(cls, 'firefox-app') t.test_init() t.test_set_result() # Install failsafe. Use a closure so failsafe wont spoil a future test isrunning = True def stop(): if isrunning: app.stop() app.call_later(TIMEOUT1, stop) # Enter main loop until we get out t0 = time.time() app.start() print('ran %f seconds' % (time.time() - t0)) isrunning = False # Check result if True: # not (ON_TRAVIS and ON_PYPY): # has intermittent fails on pypy3 t.test_check() # Shut down t.session.close()
def test_serving_apps_at_output_message(): """ Test for 'Serving apps at' ready signal. """ with capture_log('info') as log: server = app.create_server() app.stop() # triggers event to stop app.start() assert 'Serving apps at' in ''.join(log)
def runner(): # Run with a fresh server and loop loop.reset() #asyncio_loop = asyncio.get_event_loop() asyncio_loop = asyncio.new_event_loop() app.create_server(port=0, loop=asyncio_loop) print('running', func.__name__, '...', end='') orig_stdout = sys.stdout orig_stderr = sys.stderr fake_stdout = FakeStream() sys.stdout = sys.stderr = fake_stdout t0 = time.time() try: # Call function - it could be a co-routine cr = func() if asyncio.iscoroutine(cr): asyncio_loop.run_until_complete(cr) gc.collect() finally: sys.stdout = orig_stdout sys.stderr = orig_stderr # Clean up / shut down print('done in %f seconds' % (time.time()-t0)) for appname in app.manager.get_app_names(): if 'default' not in appname: sessions = app.manager.get_connections(appname) for session in sessions: if session.app is not None: session.app.dispose() session.close() loop.reset() # Get reference text pyresult, jsresult = filter_stdout(fake_stdout.getvalue()) reference = '\n'.join(line[4:] for line in func.__doc__.splitlines()) parts = reference.split('-'*10) pyref = parts[0].strip(' \n') jsref = parts[-1].strip(' \n-') # Compare smart_compare(func, ('Python', pyresult, pyref), ('JavaScript', jsresult, jsref))
def test_more_stopping(): """ Test calling stop multiple times. """ # This is why you want to create new IOLoop instances for each test # Create new ioloop and make Flexx use it loop = IOLoop() loop.make_current() server = app.create_server() app.stop() # triggers event to stop app.start() app.stop() # Extra stop - pending stop event # Which means the next stop does hardly block t0 = time.time() app.call_later(0.2, app.stop) app.start() assert time.time() - t0 < 0.1 loop = IOLoop() loop.make_current() server = app.create_server() # But stops dont stack app.stop() app.stop() app.stop() app.stop() # Flush all stops ... app.stop() app.start() # ... so that we now have an expected loop t0 = time.time() app.call_later(0.2, app.stop) app.start() assert time.time() - t0 >= 0.1
def test_more_stopping(): """ Test calling stop multiple times. """ # This is why you want to create new IOLoop instances for each test # Create new ioloop and make Flexx use it loop = asyncio.new_event_loop() asyncio.set_event_loop(loop) server = app.create_server() app.stop() # triggers event to stop app.start() app.stop() # Extra stop - pending stop event # Which means the next stop does hardly block t0 = time.time() loop.call_later(0.2, app.stop) app.start() assert time.time() - t0 < 0.1 loop = asyncio.new_event_loop() asyncio.set_event_loop(loop) server = app.create_server() # But stops dont stack app.stop() app.stop() app.stop() app.stop() # Flush all stops ... app.stop() app.start() # ... so that we now have an expected loop t0 = time.time() loop.call_later(0.2, app.stop) app.start() assert time.time() - t0 >= 0.1
def test_restarting(): """ Test stopping and starting the ioloop. """ res = [] def add_res(i): res.append(i) def try_start(): try: app.start() except RuntimeError: res.append('RTE') # Create new ioloop always loop = IOLoop() loop.make_current() # Make Flexx use it server = app.create_server() app.call_later(0, add_res, 1) app.call_later(0, add_res, 2) app.call_later( 0, app.stop) # actually, just calling stop() would work as well app.start() assert server._running == False app.call_later(0, try_start) # test that cannot start twice app.call_later(0, add_res, 3) app.call_later(0, add_res, 4) app.call_later(0, app.stop) app.start() assert server._running == False app.call_later(0, try_start) # test that cannot start twice app.call_later(0, add_res, 5) app.call_later(0, add_res, 6) app.call_later(0, app.stop) app.start() assert server._running == False assert res == [1, 2, 'RTE', 3, 4, 'RTE', 5, 6]
def test_restarting(): """ Test stopping and starting the ioloop. """ res = [] def add_res(i): res.append(i) def try_start(): try: app.start() except RuntimeError: res.append('RTE') # Create new ioloop always loop = asyncio.new_event_loop() asyncio.set_event_loop(loop) # Make Flexx use it server = app.create_server() loop.call_soon(add_res, 1) loop.call_soon(add_res, 2) loop.call_soon( app.stop) # actually, just calling stop() would work as well app.start() assert server._running == False loop.call_soon(try_start) # test that cannot start twice loop.call_soon(add_res, 3) loop.call_soon(add_res, 4) loop.call_soon(app.stop) app.start() assert server._running == False loop.call_soon(try_start) # test that cannot start twice loop.call_soon(add_res, 5) loop.call_soon(add_res, 6) loop.call_soon(app.stop) app.start() assert server._running == False assert res == [1, 2, 'RTE', 3, 4, 'RTE', 5, 6]
def test_flexx_in_thread5(): """ Test using new_loop for easier use. """ res = [] server = app.create_server(new_loop=True) assert server.serving assert server.loop is not IOLoop.current() def main(): app.stop() app.start() assert server.loop is IOLoop.current() res.append(3) t = threading.Thread(target=main) t.start() t.join() assert res == [3]
def test_restarting(): """ Test stopping and starting the ioloop. """ res = [] def add_res(i): res.append(i) def try_start(): try: app.start() except RuntimeError: res.append('RTE') # Create new ioloop always loop = IOLoop() loop.make_current() # Make Flexx use it server = app.create_server() app.call_later(0, add_res, 1) app.call_later(0, add_res, 2) app.call_later(0, app.stop) # actually, just calling stop() would work as well app.start() assert server._running == False app.call_later(0, try_start) # test that cannot start twice app.call_later(0, add_res, 3) app.call_later(0, add_res, 4) app.call_later(0, app.stop) app.start() assert server._running == False app.call_later(0, try_start) # test that cannot start twice app.call_later(0, add_res, 5) app.call_later(0, add_res, 6) app.call_later(0, app.stop) app.start() assert server._running == False assert res == [1, 2, 'RTE', 3, 4, 'RTE', 5, 6]
def test_restarting(): """ Test stopping and starting the ioloop. """ res = [] def add_res(i): res.append(i) def try_start(): try: app.start() except RuntimeError: res.append('RTE') # Create new ioloop always loop = asyncio.new_event_loop() asyncio.set_event_loop(loop) # Make Flexx use it server = app.create_server() loop.call_soon(add_res, 1) loop.call_soon(add_res, 2) loop.call_soon(app.stop) # actually, just calling stop() would work as well app.start() assert server._running == False loop.call_soon(try_start) # test that cannot start twice loop.call_soon(add_res, 3) loop.call_soon(add_res, 4) loop.call_soon(app.stop) app.start() assert server._running == False loop.call_soon(try_start) # test that cannot start twice loop.call_soon(add_res, 5) loop.call_soon(add_res, 6) loop.call_soon(app.stop) app.start() assert server._running == False assert res == [1, 2, 'RTE', 3, 4, 'RTE', 5, 6]
def test_active_models(): ioloop = app.create_server(port=0, new_loop=True).loop # This test needs a default session session = app.manager.get_default_session() if session is None: app.manager.create_default_session() # Test that by default there are no active models m = Model() assert not _get_active_models() # Test that model is active in its context with m: assert _get_active_models() == [m] # Can do this ioloop.run_sync(lambda x=None: None) class PMHandler(logging.Handler): def emit(self, record): if record.exc_info: self.last_type, self.last_value, self.last_traceback = record.exc_info return record handler = PMHandler() root_logger = logging.getLogger() root_logger.addHandler(handler) # Test that we prevent going back to Tornado in context handler.last_type = None with m: assert _get_active_models() == [m] # This raises error, but gets caught by Tornado ioloop.run_sync(lambda x=None: None) assert handler.last_type is RuntimeError assert 'risk on race conditions' in str(handler.last_value)
def test_active_models(): ioloop = app.create_server(port=0, new_loop=True).loop # This test needs a default session session = app.manager.get_default_session() if session is None: app.manager.create_default_session() # Test that by default there are no active models m = Model() assert not _get_active_models() # Test that model is active in its context with m: assert _get_active_models() == [m] # Can do this ioloop.run_sync(lambda x=None: None) class PMHandler(logging.Handler): def emit(self, record): if record.exc_info: self.last_type, self.last_value, self.last_traceback = record.exc_info return record handler = PMHandler() app.logger.addHandler(handler) # Test that we prevent going back to Tornado in context handler.last_type = None with m: assert _get_active_models() == [m] # This raises error, but gets caught by Tornado ioloop.run_sync(lambda x=None: None) assert handler.last_type is RuntimeError assert 'risk on race conditions' in str(handler.last_value)
def runner(cls): # Run with a fresh server server = app.create_server(port=0, new_loop=True) t = app.launch(cls, 'firefox-app') t.test_init() t.test_set_result() # Install failsafe. Use a closure so failsafe wont spoil a future test isrunning = True def stop(): if isrunning: app.stop() app.call_later(TIMEOUT1, stop) # Enter main loop until we get out t0 = time.time() app.start() print('ran %f seconds' % (time.time()-t0)) isrunning = False # Check result if True: # not (ON_TRAVIS and ON_PYPY): # has intermittent fails on pypy3 t.test_check() # Shut down t.session.close()
def start_flexx(): app.create_server(loop=asyncio.new_event_loop()) app.start()
def main(): # Create fresh ioloop and make flexx use it loop = asyncio.new_event_loop() asyncio.set_event_loop(loop) app.create_server() # calls event.loop.integrate() app.start()
from flexx import app, event class MyModel1(event.HasEvents): @event.prop def foo(self, v=0): return v @event.connect('foo') def on_foo(self, *events): for ev in events: print('foo changed to', ev.new_value) # Create model in main thread model = MyModel1() # Start server in its own thread app.create_server(new_loop=True) t = threading.Thread(target=app.start) t.start() # Manipulate model from main thread (the model's on_foo() gets called from other thread) for i in range(5, 9): time.sleep(1) model.foo = i # Stop event loop (this is thread-safe) and wait for thread to end app.stop() t.join()
def multiprocessing_func(): import flexx app.create_server(port=0) # Explicitly ask for unused port app.call_later(0.1, app.stop) app.start()
def main(): app.create_server(loop=asyncio.new_event_loop()) try_start()
for fir in [(fir2_file, "fir2"), (fir1_file, "fir1")]: with open(fir[0], "r") as fil: filedata = fil.read() data = [ min(2**23 - 1, (max(-2**23, int(float(f.replace("\r", "")) * 2**23)))) for f in filedata.split("\n") if len(f) > 0 ] mapper.fir_update(data, fir[1]) if __name__ == "__main__": import_defaults_active = True lock_settings = [("Mixing, Serial Data and Automute Configuration", "*")] mappers = [DAC_9038Q2M_Control(0x48), DAC_9038Q2M_Control(0x49)] defaults = os.path.join(os.path.dirname(__file__), "configs", "default") for m in mappers: m.i2c_init() if import_defaults_active: import_defaults(defaults, m) # m.importYaml( # r"C:\Users\webco\Documents\Projects\SABRE_I2C_Controller\configs\device_0x48_config_std.yml" # ) pass flx_app = flx.App(ControlApp, mappers, lock_settings) # app.launch("app", title="ES9038Control") # to run as a desktop app app.create_server(host="", port=5000, backend="tornado") flx_app.launch("browser") # to open in the browser flx.start() # mainloop will exit when the
def main(): loop2.make_current() app.create_server()
import flexx import io import os, sys import threading class TheApp(ui.PyWidget): def init(self): content = open("instructions.md", encoding='utf-8').read() myui.Markdown(title='Instructions', style='background:#EAECFF;overflow-y: scroll;', content=content) if __name__ == '__main__': import platform, sys, os from tornado.web import StaticFileHandler flexx.config.debug = True tornado_app = app.create_server(host="localhost", port=8081).app # Make use of Tornado's static file handler tornado_app.add_handlers(r".*", [ (r"/theapp/img/(.*)", StaticFileHandler, { "path": "static/img" }), ]) comp = flx.App(TheApp) comp.serve('theapp') app.start()
def main(): # Create fresh ioloop and make flexx use it loop = IOLoop() loop.make_current() app.create_server() app.start()
dirname = os.path.expanduser('~/Videos') # Collect videos that look like they can be read in html5 videos = {} for fname in os.listdir(dirname): if fname.endswith('.mp4'): videos[fname] = '/videos/' + fname # Add some online videos too, for fun videos['bbb.mp4 (online)'] = 'http://www.w3schools.com/tags/mov_bbb.mp4' videos['ice-age.mp4 (online)'] = ( 'https://dl.dropboxusercontent.com/u/1463853/' 'ice%20age%204%20trailer.mp4') # Make use of Tornado's static file handler tornado_app = app.create_server().app tornado_app.add_handlers(r".*", [ (r"/videos/(.*)", StaticFileHandler, { "path": dirname }), ]) class VideoViewer(ui.Widget): """ A simple videoviewer that displays a list of videos found on the server's computer, plus a few online videos. Note that not all videos may be playable in HTML5. """ def init(self): with ui.HSplit():
def main(): asyncio.set_event_loop(loop2) app.create_server()
def main(): app.create_server() try_start()
# The directory to load video's from dirname = os.path.expanduser('~/Videos') # Collect videos that look like they can be read in html5 videos = {} for fname in os.listdir(dirname): if fname.endswith('.mp4'): videos[fname] = '/videos/' + fname # Add some online videos too, for fun videos['bbb.mp4 (online)'] = 'http://www.w3schools.com/tags/mov_bbb.mp4' videos['ice-age.mp4 (online)'] = ('https://dl.dropboxusercontent.com/u/1463853/' 'ice%20age%204%20trailer.mp4') # Make use of Tornado's static file handler tornado_app = app.create_server().app tornado_app.add_handlers(r".*", [ (r"/videos/(.*)", StaticFileHandler, {"path": dirname}), ]) class VideoViewer(ui.Widget): """ A simple videoviewer that displays a list of videos found on the server's computer, plus a few online videos. Note that not all videos may be playable in HTML5. """ def init(self): with ui.BoxPanel(): with ui.TreeWidget(max_selected=1, flex=1) as self.videolist:
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2018/1/3 15:59 # @Author : yc # @Site : # @File : 16_group.py # @Software: PyCharm from flexx import app, ui, event class Example(ui.GroupWidget): def init(self): self.title = 'A silly panel' with ui.VBox(): self.progress = ui.ProgressBar(value=0.001) self.but = ui.Button(text='click me') class JS: @event.connect('but.mouse_down') def _change_group_title(self, *events): self.progress.value += 0.05 app.init_interactive(Example) app.create_server(host="127.0.0.1", port=8009, new_loop=False, backend='tornado') app.start()