def setUp(self): self.token = uuid.uuid4().hex self.doof = DoofSpoof() self.loop = asyncio.get_event_loop() self.app = make_app(self.token, self.doof, self.loop) super().setUp()
def setUp(self): self.secret = uuid.uuid4().hex self.loop = asyncio.get_event_loop() self.doof = DoofSpoof(loop=self.loop) self.app = make_app(secret=self.secret, bot=self.doof) super().setUp()
def running_app_base_url(request): port = 8888 web.make_app().listen(port) def run_server(): tornado.ioloop.IOLoop.instance().start() def fin(): tornado.ioloop.IOLoop.instance().stop() request.addfinalizer(fin) threading.Thread(target=run_server).start() return "http://localhost:{}/".format(port)
def get_app(self): self.db = motor.MotorClient(host='db').test_gallery self.sync_db = pymongo.MongoClient(host='db').test_gallery self.UPLOAD_PATH = '/data/test_uploads/' if os._exists(self.UPLOAD_PATH): print 'UPLOAD PATH {} exists.. removing'.format(self.UPLOAD_PATH) shutil.rmtree(self.UPLOAD_PATH) self.settings = web.SETTINGS self.settings.update(autoreload=False, UPLOAD_PATH=self.UPLOAD_PATH, db=self.db) self.app = web.make_app(self.settings) return self.app
def server_run(args): app = make_app(args.debug) wait_for_db: bool = args.wait_for_database connection_string = get_connection_string() connection = try_create_connection(connection_string, wait_for_db, app.logger) state = AlembicHelper(connection) strategy = SchemaStrategist(state).determine_schema_strategy() strategy() @app.before_request def get_time(): g.request_time = time.time() @app.teardown_request def time_response(exception=None): request_time = g.pop('request_time', None) if request_time: time_taken = time.time() - request_time if time_taken > 0.5: app.logger.warn( "Response took {duration} seconds for request {path}". format(path=request.full_path, duration=time_taken)) engine = create_engine(connection_string, echo=args.profile) set_scoped_session( scoped_session(sessionmaker(bind=engine), scopefunc=lambda: _request_ctx_stack.top)) def lookup_translation(): ctx = _request_ctx_stack.top if ctx is None: return None translations = getattr(ctx, 'pycroft_translations', None) if translations is None: translations = Translations() for module in (pycroft, web): os.path.dirname(module.__file__) dirname = os.path.join(ctx.app.root_path, 'translations') translations.merge(Translations.load(dirname, [get_locale()])) ctx.pycroft_translations = translations return translations set_translation_lookup(lookup_translation) app.config.from_pyfile('flask.cfg') if args.profile: app.config['PROFILE'] = True app.wsgi_app = ProfilerMiddleware(app.wsgi_app, restrictions=[30]) app.run(debug=args.debug, port=args.port, host=args.host, threaded=True)
def create_app(self): """ Create your Flask app here, with any configuration you need """ from web import make_app app = make_app(connection_string="sqlite://") app.testing = True app.debug = True # Disable the CSRF in testing mode app.config["WTF_CSRF_ENABLED"] = False return app
async def connect_to_message_server(loop): """Setup connection with websocket server""" async with websockets.connect(resp.json()['url']) as websocket: bot = Bot( websocket=websocket, slack_access_token=envs['SLACK_ACCESS_TOKEN'], github_access_token=envs['GITHUB_ACCESS_TOKEN'], timezone=pytz.timezone(envs['TIMEZONE']), repos_info=repos_info, ) app = make_app(token=envs['SLACK_WEBHOOK_TOKEN'], bot=bot, loop=loop) app.listen(port) try: while True: message = await websocket.recv() print(message) message = json.loads(message) if message.get('type') != 'message': continue if message.get('subtype') == 'message_changed': # A user edits their message # content = message.get('message', {}).get('text') content = None else: content = message.get('text') if content is None: continue channel_id = message.get('channel') all_words = content.strip().split() if len(all_words) > 0: message_handle, *words = all_words if message_handle in ("<@{}>".format(doof_id), "@doof"): print("handling...", words, channel_id) loop.create_task( bot.handle_message( manager=message['user'], channel_id=channel_id, words=words, loop=loop, )) finally: app.stop()
def create_app(self): """ Create your Flask app here, with any configuration you need """ from web import make_app app = make_app() app.testing = True app.debug = True # Disable the CSRF in testing mode app.config["WTF_CSRF_ENABLED"] = False app.config["SECRET_KEY"] = ''.join(random.choice(string.ascii_letters) for _ in range(20)) return app
def create_app(self): """ Create your Flask app here, with any configuration you need """ from web import make_app app = make_app() app.testing = True app.debug = True # Disable the CSRF in testing mode app.config["WTF_CSRF_ENABLED"] = False app.config["SECRET_KEY"] = ''.join( random.choice(string.ascii_letters) for _ in range(20)) return app
def zoe_web_apps_main() -> int: """ This is the entry point for the Zoe Web Apps script. :return: int """ load_configuration() args = get_conf() if args.debug: logging.basicConfig(level=logging.DEBUG) else: logging.basicConfig(level=logging.INFO) logging.getLogger("requests").setLevel(logging.WARNING) logging.getLogger("tornado").setLevel(logging.DEBUG) log.info("Starting HTTP server...") ioloop = IOLoop.instance() app = make_app() app.listen(args.listen_port, args.listen_address) try: ioloop.start() except KeyboardInterrupt: print("CTRL-C detected, terminating")
def serve(): from web import make_app import waitress waitress.serve(make_app())
def prepare_server(args) -> tuple[PycroftFlask, Callable]: """returns both the prepared app and a callback executing `app.run`""" if args.echo: logging.basicConfig(stream=sys.stdout, level=logging.DEBUG) logging.getLogger('sqlalchemy.engine').setLevel(logging.INFO) logging.getLogger('sqlalchemy.pool').setLevel(logging.DEBUG) app = make_app(args.debug) logging.getLogger('pycroft').addHandler(default_handler) wait_for_db: bool = args.wait_for_database connection_string = get_connection_string() connection, engine = try_create_connection(connection_string, wait_for_db, app.logger, reflections=False) state = AlembicHelper(connection) if args.force_schema_create: strategy = SchemaStrategist(state).create_then_stamp else: strategy = SchemaStrategist(state).determine_schema_strategy() strategy() @app.before_request def get_time(): g.request_time = time.time() @app.teardown_request def time_response(exception=None): request_time = g.pop('request_time', None) if request_time: time_taken = time.time() - request_time if time_taken > 0.5: app.logger.warning( "Response took %s seconds for request %s", time_taken, request.full_path, ) connection, engine = try_create_connection(connection_string, wait_for_db, app.logger, args.profile) set_scoped_session(scoped_session(sessionmaker(bind=engine), scopefunc=lambda: _request_ctx_stack.top)) def lookup_translation(): ctx = _request_ctx_stack.top if ctx is None: return None translations = getattr(ctx, 'pycroft_translations', None) if translations is None: translations = Translations() for module in (pycroft, web): os.path.dirname(module.__file__) dirname = os.path.join(ctx.app.root_path, 'translations') translations.merge(Translations.load(dirname, [get_locale()])) ctx.pycroft_translations = translations return translations set_translation_lookup(lookup_translation) app.config.from_pyfile('flask.cfg') if args.profile: app.config['PROFILE'] = True app.wsgi_app = ProfilerMiddleware(app.wsgi_app, restrictions=[30]) return app, lambda: app.run(debug=args.debug, port=args.port, host=args.host, threaded=True)
def server_run(args): app = make_app(args.debug) try: connection_string = os.environ['PYCROFT_DB_URI'] except KeyError: raise RuntimeError("Environment variable PYCROFT_DB_URI must be " "set to an SQLAlchemy connection string.") engine = create_engine(connection_string) if args.wait_for_database == 0: max_wait = float('inf') else: max_wait = time.clock_gettime(time.CLOCK_MONOTONIC) + args.wait_for_database for timeout in chain([1, 2, 5, 10, 30], repeat(60)): try: connection = engine.connect() break except OperationalError: # Important: Use %r to print the URL, passwords are hidden by the # __repr__ of sqlalchemy.engine.URL app.logger.warn("Could not connect to database %r", engine.url) timeout = min(timeout, max_wait - time.clock_gettime(time.CLOCK_MONOTONIC)) if timeout > 0: app.logger.info("Waiting for %d seconds", timeout) time.sleep(timeout) else: raise state = AlembicHelper(connection) strategy = SchemaStrategist(state).determine_schema_strategy() strategy() print("If you're running in a docker setup, the port may differ" " from what is given below." " It is probably http://0.0.0.0:5001") @app.before_request def get_time(): g.request_time = time.time() @app.teardown_request def time_response(exception=None): time_taken = time.time() - g.request_time if time_taken > 0.5: app.logger.warn( "Response took {duration} seconds for request {path}".format( path=request.full_path, duration=time_taken)) engine = create_engine(connection_string, echo=args.profile) set_scoped_session(scoped_session(sessionmaker(bind=engine), scopefunc=lambda: _request_ctx_stack.top)) def lookup_translation(): ctx = _request_ctx_stack.top if ctx is None: return None translations = getattr(ctx, 'pycroft_translations', None) if translations is None: translations = Translations() for module in (pycroft, web): os.path.dirname(module.__file__) dirname = os.path.join(ctx.app.root_path, 'translations') translations.merge(Translations.load(dirname, [get_locale()])) ctx.pycroft_translations = translations return translations set_translation_lookup(lookup_translation) app.config.from_pyfile('flask.cfg') if args.profile: app.config['PROFILE'] = True app.wsgi_app = ProfilerMiddleware(app.wsgi_app, restrictions=[30]) app.run(debug=args.debug, port=args.port, host=args.host, threaded=True)
import tornado.ioloop import config from doors import ConsoleDoorController, PiDoorController from messagers import GroupMeMessager, ConsoleMessager from handlers import GroupMeMessageHandler from web import make_app if config.PI_PIN: controller = PiDoorController(config.PI_PIN, config.UNLOCK_TIME) else: controller = ConsoleDoorController(config.UNLOCK_TIME) if config.GROUPME_BOT_ID: messager = GroupMeMessager(config.GROUPME_BOT_ID) else: messager = ConsoleMessager() message_handler = GroupMeMessageHandler(messager, controller) app = make_app(message_handler, controller, config.CALLBACK_URL, config.BACKDOOR_URL) if __name__ == "__main__": app.listen(config.PORT) tornado.ioloop.IOLoop.current().start()
# Copyright (c) 2014 The Pycroft Authors. See the AUTHORS file. # This file is part of the Pycroft project and licensed under the terms of # the Apache License, Version 2.0. See the LICENSE file for details. from web import make_app from pycroft.lib.config import config if __name__ == "__main__": app = make_app() app.debug = True app.config['MAX_CONTENT_LENGTH'] = \ int(config["file_upload"]["max_file_size"]) app.config['UPLOAD_FOLDER'] = config["file_upload"]["temp_dir"] app.run(debug=True)
def app(): return make_app()
def cmd_server_start(port): app = make_app(port) app.run(host='0.0.0.0', port=port, debug=True)