def main() -> None: app = quart.Quart(__name__, static_url_path='/', static_folder='./webBox/static', template_folder='./webBox/pages') serverMix.enableTool('InnerSession', 'WsHouse') router = serverMix.Router(app, 'webBox.controller') router.add('GET', '/', 'home.get') webBox.controller.ws.init('webBox/app/wsChannel') router.websocket('/ws', 'ws.entry') app.run(host='0.0.0.0', port=5000, debug=True)
def __init__(self, sys_descr: str, sess_descr: str) -> None: self._api_prefix = '/api/v1' self._sys_descr = sys_descr self._sess_descr = sess_descr self._app = quart.Quart(__name__, static_folder='../../../frontend/static/', template_folder='../../../frontend/') self._app = quart_cors.cors(self._app) self._session_timer_start = time.time() self._session_scheduler = sched.scheduler(time.time, time.sleep) self._event = ServerSentEvent() # Commented for now as the logs are showing doubled # coloredlogs.install(level='DEBUG', logger=logging.getLogger('quart.app')) # coloredlogs.install(level='DEBUG', logger=logging.getLogger('quart.serving')) self.load_mock_system_description() self.load_mock_session_description()
async def serve(self, title, host, port, *, task_status=anyio.TASK_STATUS_IGNORED): """Web view server task.""" # (quart and hypercorn should have a common API for asyncio and trio...) async_lib = sniffio.current_async_library() if async_lib == 'trio': from quart_trio import QuartTrio # pylint: disable=import-outside-toplevel,import-error web_app = QuartTrio('pura') web_app.register_blueprint(self.get_blueprint(title)) async with anyio.create_task_group() as tg: urls = await tg.start( hypercorn.trio.serve, web_app, hypercorn.Config.from_mapping( bind=[f'{host}:{port}'], loglevel='WARNING', )) _logger.info(f'listening on {urls[0]}') task_status.started() elif async_lib == 'asyncio': web_app = quart.Quart('pura') web_app.register_blueprint(self.get_blueprint(title)) task_status.started() await hypercorn.asyncio.serve( web_app, hypercorn.Config.from_mapping( bind=[f'{host}:{port}'], loglevel='INFO', graceful_timeout=.2, )) raise CancelledError else: raise RuntimeError('unsupported async library:', async_lib)
import quart from views import city_api from views import home from config import settings import services.weather_service import services.sun_service import services.location_service app = quart.Quart(__name__) is_debug = False app.register_blueprint(home.blueprint) app.register_blueprint(city_api.blueprint) def configure_app(): mode = 'dev' if is_debug else 'prod' data = settings.load(mode) services.weather_service.global_init(data.get('weather_key')) services.sun_service.use_cached_data = data.get('use_cached_data') services.location_service.use_cached_data = data.get('use_cached_data') print("Using cached data? {}".format(data.get('use_cached_data'))) def run_web_app(): app.run(debug=is_debug, port=5001) configure_app()
import aiohttp import asyncio import asyncpg import quart import json import async_db app = quart.Quart("python-web-perf") pool = None #only for asyncpg @app.before_serving async def startup(): app.pool = await asyncpg.create_pool(max_size=10, min_size=10, database='test', user='******', password='******', port='5432', host='db') @app.route("/test") async def test(): a, b = await async_db.get_row() return json.dumps({"a": str(a).zfill(10), "b": b}) @app.route("/long-query-test")
import sys import tempfile from typing import Any, Awaitable, Dict, List, MutableMapping, Optional import attr from hypercorn.asyncio import serve from hypercorn.config import Config import jsonschema import toml import quart import yaml from .target_config import TargetConfig from .target_config_schema import TARGETS_LIST_SCHEMA REST_APP = quart.Quart(__name__) LOGGER = logging.getLogger(__name__) SHUTDOWN_EVENT = asyncio.Event() def run_rest_api(config_file: str) -> None: """Setup and run the quart web-app that provides the REST API based on the config file passed in. If config_file is not a valid file-path it is expected that all the arguments will come from environment variables. """ def get_file_sd_directory() -> str: """Use environment variables or the config dict to find the directory for file-based service discovery""" file_sd_dir = os.getenv("FILE_SD_DIRECTORY")
from quart import request from ldap.modlist import addModlist, modifyModlist import asyncio, base64, quart, functools, io, ldap, ldif, sys, types from typing import * app = quart.Quart(__name__, static_folder='dist') app.config.from_object('settings') # Constant to add technical attributes in LDAP search results WITH_OPERATIONAL_ATTRS = ('*','+') # HTTP 401 headers UNAUTHORIZED = { 'WWW-Authenticate': 'Basic realm="Login Required"' } # Special fields PHOTO = 'jpegPhoto' PASSWORDS = ('userPassword',) # Special syntaxes OCTET_STRING = '1.3.6.1.4.1.1466.115.121.1.40' def authenticated(view: Callable): ''' Require authentication for a view, set up the LDAP connection and authenticate against the directory with a simple_bind ''' @functools.wraps(view)
"""App setup module. """ import os import traceback import auth import bot import quart import quart_cors import quart_jwt_extended as jwt import util app = quart.Quart("app") app.response_class = util.JSONResponse app = quart_cors.cors(app) app.config["JWT_SECRET_KEY"] = os.getenv("JWT_SECRET") app.config["JWT_ERROR_MESSAGE_KEY"] = "error" app.register_blueprint(bot.app, url_prefix="/bot/") app.register_blueprint(auth.app, url_prefix="/auth/") jwt_manager = jwt.JWTManager(app) @app.errorhandler(Exception) async def handle_exception(exception): """Handles all exceptions.
import quart app = quart.Quart("{{name}}") @app.route("/") async def index(): return "Hello Satan\n"
def __init__(self): self.client = discord.Client() if isfile('settings.json'): self.settings = json.loads(open('settings.json').read()) else: self.settings = dict() self.__original_settings = copy.deepcopy(self.settings) self.class_list = list() # (fullname, class) self.server_instances = dict() self.whitelist = dict() self.webapp = quart.Quart(__name__) self.settings.setdefault('command prefix', {}).setdefault('default', '.') self.settings.setdefault( 'auto join', { 'note': 'This doesn\'t seem to work for bots, they don\'t have permission to just join servers. But this will work if the bot uses a normal user account instead.', 'invite urls': [] }) self.load_classlist() async def __message_processor(message): # disallow direct messages if not message.server: return () # Apparently on_server_available doesn't get called for all servers somehow if message.server.id not in self.server_instances: await on_server_available(message.server) try: await self.server_instances[message.server.id ].process_message(message) except Exception as e: for member in self.client.get_all_members(): if member.id == self.settings['permissions']['bot owner']: bot_owner = member strings = [ '**An exception occurred while processing a message:**' ] strings += traceback.format_exc().split('\n') msgs = [ '```' + x + '```' for x in Module.pack_into_messages(strings) ] msgs.append( '**Message by {}:**: ```{}```\n'.format( message.author.name, message.content) + '**Server:**: ```{}```\n'.format( message.server.name) + '**Feel free to submit this info to the issue tracker:** ' + 'https://github.com/TheComet/GLaDOS2/issues') for msg in msgs: await self.client.send_message(bot_owner, msg) if not message.author == bot_owner: await self.client.send_message( message.author, msg) break # Write settings dict to disc (and print a diff) if a command changed it in any way self.__check_if_settings_changed() @self.client.event async def on_message(message): await __message_processor(message) @self.client.event async def on_message_edit(before, after): await __message_processor(after) @self.client.event async def on_ready(): await self.__auto_join_channels() log('Running as {}'.format(self.client.user.name)) self.__check_if_settings_changed() @self.client.event async def on_server_available(server): if server.id in self.server_instances: return () log('Server {} became available'.format(server.name)) s = ServerInstance(self.client, self.settings, server, self.webapp) s.instantiate_modules(self.class_list, self.whitelist) self.server_instances[server.id] = s @self.client.event async def on_server_unavailable(server): log('Server {} became unavailable, cleaning up instances'.format( server.name)) self.server_instances.pop(server.id, None)
import asyncio import json import quart import upnpy import heos import heos.manager app = quart.Quart("HEOS Communication Server", static_url_path='') app.secret_key = "HeosCommunication_ChangeThisKeyForInstallation" found_heos_devices = list() heos_manager: heos.manager.HeosDeviceManager = None @app.before_serving async def _start_server(): global heos_manager heos_manager = heos.manager.HeosDeviceManager() loop = asyncio.get_event_loop() loop.create_task(scan_for_devices(1)) await asyncio.sleep(1) @app.after_serving async def _shut_down(): global heos_manager await heos_manager.stop_watch_events()
import pandas as pd import plotly import plotly.express as px import plotly.graph_objects as go from plotly.subplots import make_subplots import quart import requests import yaml ROOT_DIR = os.path.abspath(os.path.dirname(__file__)) COUNTIES = yaml.safe_load( open(os.path.join(ROOT_DIR, "config", "counties.yaml"))) app = quart.Quart(__name__, template_folder=os.path.join(ROOT_DIR, "templates")) @app.route("/") async def index_page(): return await quart.render_template("index.html", counties=COUNTIES) @app.route("/death-chart") async def death_chart(): county = quart.request.args.get("county") if not county or county not in COUNTIES: return quart.abort(404) county_death_data, county_cases_data = await asyncio.gather( get_county_data(county), get_county_data(county, "cases")) # county_data_df = pd.DataFrame([convert_ts_in_obj(x["attributes"]) for x in county_death_data["features"]])
def create_app() -> quart.Quart: try: env_init = os.environ["SNIKKET_WEB_PYENV"] except KeyError: pass else: import runpy init_vars = runpy.run_path(env_init) # type:ignore for name, value in init_vars.items(): if not name: continue if name[0] not in _UPPER_CASE: continue os.environ[name] = value config = environ.to_config(AppConfig) app = quart.Quart(__name__) app.config["LANGUAGES"] = config.languages app.config["SECRET_KEY"] = config.secret_key app.config["PROSODY_ENDPOINT"] = config.prosody_endpoint app.config["SNIKKET_DOMAIN"] = config.domain app.config["SITE_NAME"] = config.site_name or config.domain app.config["AVATAR_CACHE_TTL"] = config.avatar_cache_ttl app.config["APPLE_STORE_URL"] = config.apple_store_url app.context_processor(proc) app.register_error_handler( aiohttp.ClientConnectorError, backend_error_handler, # type:ignore ) app.register_error_handler( quart.exceptions.HTTPException, generic_http_error, # type:ignore ) app.register_error_handler( Exception, generic_error_handler, # type:ignore ) @app.route("/") async def index() -> quart.Response: if infra.client.has_session: return redirect(url_for('user.index')) return redirect(url_for('main.login')) @app.route("/site.webmanifest") def site_manifest() -> quart.Response: # this is needed for icons return jsonify({ "name": "Snikket", "short_name": "Snikket", "icons": [ { "src": url_for( "static", filename="img/android-chrome-192x192.png", ), "sizes": "192x192", "type": "image/png" }, { "src": url_for( "static", filename="img/android-chrome-256x256.png", ), "sizes": "256x256", "type": "image/png" }, { "src": url_for( "static", filename="img/android-chrome-512x512.png", ), "sizes": "512x512", "type": "image/png" }, ], "theme_color": "#fbfdff", "background_color": "#fbfdff", }) logging_config = app.config.get("LOGGING_CONFIG") if logging_config is not None: if isinstance(logging_config, dict): logging.config.dictConfig(logging_config) elif isinstance(logging_config, (bytes, str, pathlib.Path)): import toml with open(logging_config, "r") as f: logging_config = toml.load(f) logging.config.dictConfig(logging_config) else: logging.basicConfig(level=logging.WARNING) if app.debug: logging.getLogger("snikket_web").setLevel(logging.DEBUG) infra.babel.init_app(app) infra.client.init_app(app) infra.init_templating(app) from .main import bp as main_bp from .user import bp as user_bp from .admin import bp as admin_bp from .invite import bp as invite_bp app.register_blueprint(main_bp) app.register_blueprint(user_bp, url_prefix="/user") app.register_blueprint(admin_bp, url_prefix="/admin") app.register_blueprint(invite_bp, url_prefix="/invite") return app
def app(): yield quart.Quart(__name__)