async def _app(config): app = Quart(__name__) app.config.update(config) app.config.update( { "DB_KWARGS": dict( max_inactive_connection_lifetime=_MAX_INACTIVE_CONNECTION_LIFETIME, ), } ) db = Gino(app) class User(db.Model): __tablename__ = "gino_users" id = db.Column(db.BigInteger(), primary_key=True) nickname = db.Column(db.Unicode(), default="noname") @app.route("/") async def root(): conn = await request.connection.get_raw_connection() # noinspection PyProtectedMember assert conn._holder._max_inactive_time == _MAX_INACTIVE_CONNECTION_LIFETIME return "Hello, world!" async def _get_user(ctx, uid: int, method: str) -> dict: q = User.query.where(User.id == uid) if method == "1": return (await q.gino.first_or_404()).to_dict() elif method == "2" and ctx: return (await ctx.connection.first_or_404(q)).to_dict() elif method == "3": return (await db.bind.first_or_404(q)).to_dict() elif method == "4": return (await db.first_or_404(q)).to_dict() else: return (await User.get_or_404(uid)).to_dict() @app.route("/users/<int:uid>") async def get_user(uid): method = request.args.get("method") return jsonify(await _get_user(request, uid, method)) async def _add_user(ctx, nickname: str) -> dict: u = await User.create(nickname=nickname) await u.query.gino.first_or_404() await db.first_or_404(u.query) await db.bind.first_or_404(u.query) if ctx: await ctx.connection.first_or_404(u.query) return u.to_dict() @app.route("/users", methods=["POST"]) async def add_user(): return jsonify(await _add_user(request, (await request.form).get("name"))) @app.websocket("/ws") async def ws(): while True: data = json.loads(await websocket.receive()) action = data.get("action") if action == "add": new_user = await _add_user(None, data.get("name")) await websocket.send(json.dumps(new_user)) elif action == "get": try: user = await _get_user( None, int(data.get("id")), data.get("method") ) except NotFound: await websocket.send(json.dumps({"error": "not found"})) else: await websocket.send(json.dumps(user)) else: await websocket.send(json.dumps({"error": "Invalid JSON"})) e = await gino.create_engine(PG_URL) try: try: await db.gino.create_all(e) yield app finally: await db.gino.drop_all(e) finally: await e.close()
def create_app(mode: str = None): mode = mode or os.environ.get('FLASK_CONFIG', 'sbx') app = Quart(__name__) # app.config.from_object(config[mode]) app.register_blueprint(api, '/api') return app
from quart import Quart, websocket, request, jsonify, render_template, redirect, url_for from flightparser import getFlights import datetime app = Quart(__name__, template_folder='templates') async def result(flights): return await render_template('result.html', flights=flights, len=len, datetime=datetime) @app.route('/', methods = ['GET', 'POST', 'PATCH', 'PUT', 'DELETE']) async def search(): if request.method == 'GET': return await render_template('search.html') elif request.method == 'POST': form = await request.form fields = [k for k in form] values = [form[k] for k in form] data = dict(zip(fields, values)) flights = await getFlights(data) return await result(flights) if __name__ == "__main__": app.run()
def setUp(self): eve_app = Quart(__name__) eve_app.config['BCRYPT_LOG_ROUNDS'] = 6 eve_app.config['BCRYPT_HASH_IDENT'] = '2b' eve_app.config['BCRYPT_HANDLE_LONG_PASSWORDS'] = True self.eve_bcrypt = Bcrypt(eve_app)
class HTTPServer: # Main server object server = Quart(__name__) @staticmethod def run(): HTTPServer.setup_router() HTTPServer.server.run(host=HTTPConsts.MAIN_HTTP_SERVER_HOST, port=HTTPConsts.MAIN_HTTP_SERVER_PORT) @staticmethod def setup_router(): # /accounts/ routes @HTTPServer.server.route('/api/v1/accounts/auth/basic', methods=["GET"]) async def qrt_acc_auth_basic(): return jsonify(Answers.templates["NOT_IMPLEMENTED"]) @HTTPServer.server.route('/api/v1/accounts/auth/token', methods=["GET"]) async def qrt_acc_auth_token(): return jsonify(Answers.templates["NOT_IMPLEMENTED"]) @HTTPServer.server.route('/api/v1/accounts/reg/byEmail', methods=["GET"]) async def qrt_acc_reg_by_email(): return jsonify(Answers.templates["NOT_IMPLEMENTED"]) @HTTPServer.server.route('/api/v1/mail/inbox', methods=["GET"]) async def qrt_get_all_msgs(): input_data = None try: input_data = await request.get_json( ) # {"messages": {"delete_after_receiving": true}} except: # TODO pass delete_in_final = False # Get value of this parameter from input_data variable if HTTPConsts.NEED_CHECK_AUTH: auth_token = None try: auth_token = str(request.headers['auth_token']) except: return jsonify(Answers.templates["INVALID_AUTH_TOKEN"]) if auth_token == None or auth_token.replace( " ", "") == "": # Uncomment if you need authorization return jsonify(Answers.templates["INVALID_AUTH_TOKEN"]) if not AccountsAuthEntity.is_authed(auth_token): return jsonify(Answers.templates["AUTH_ERR"]) else: pass entityAnswer, data = MBoxParsers.get_all_msgs( MBoxSettings.USING_MBOX_FILE_PATH, delete_in_final) answer = Answers.render(Answers.codes["server"]["OK"], Answers.codes["request"]["OK"], entityAnswer, data, "ru") return jsonify(answer) @HTTPServer.server.route('/api/v1/mail/parser/oneMsg', methods=["GET"]) async def qrt_parse_one_msg(): if not AccountsAuthEntity.is_authed("uuid_token"): return jsonify(Answers.templates["AUTH_ERR"]) """ Input data example: { "raw_msg": "From xxxxx 2019\nSubject: Hello!\n" } """ input_data = await request.get_json() entityAnswer, data = MBoxParsers.parse_one_msg( input_data["raw_msg"]) answer = Answers.render(Answers.codes["server"]["OK"], Answers.codes["request"]["OK"], entityAnswer, data, "ru") return jsonify(answer) @HTTPServer.server.route('/api/v1/mail/attachments/oneMsg', methods=["GET"]) async def qrt_get_one_msg_attachments(): if not AccountsAuthEntity.is_authed("uuid_token"): return jsonify(Answers.templates["AUTH_ERR"]) """ Input data example: { "message_id": "AC1DBC0115" [PRIORITY SEARCH VARIANT] or "sent_at": "Fri 20 Oct 2019 ..." } """ input_data = await request.get_json() entityAnswer, data = MBoxParsers.get_one_msg_attachments( sent_at=-1, message_id=input_data["message_id"]) answer = Answers.render(Answers.codes["server"]["OK"], Answers.codes["request"]["OK"], entityAnswer, data, "ru") return jsonify(answer)
async def test_send_file_no_mimetype() -> None: app = Quart(__name__) async with app.app_context(): with pytest.raises(ValueError): await send_file(BytesIO(b"something"))
from time import sleep from models import Issuer import logging from utils import file_ext from vcx.api.connection import Connection from vcx.api.credential_def import CredentialDef from vcx.api.issuer_credential import IssuerCredential from vcx.api.proof import Proof from vcx.api.schema import Schema from vcx.api.utils import vcx_agent_provision from vcx.api.vcx_init import vcx_init_with_config from vcx.state import State, ProofState app = Quart(__name__, static_url_path='/static') """ Global variables that are going to be used throughout all the proces of verification """ name = "" sre_connections = {} credentials = [] payment_plugin = cdll.LoadLibrary('libnullpay' + file_ext()) payment_plugin.nullpay_init() """ This is the privisional configuration for the SRE entity It is mainly for initialization purposes. """
mp_conn = multiprocessing.connection.Client('/tmp/nachobot', 'AF_UNIX') logging.error('maybe send?') while mp_queue: mp_conn.send(mp_queue[0]) mp_queue = mp_queue[1:] except: mp_conn = None # probably this is bad logging.error('no connection to bot yet') logging.error(sys.exc_info()[0]) # logging.error(str(serr)) traceback.print_exc() # from config import Config as c APP = Quart(__name__) MULTIWORLDS = {} @APP.route('/game', methods=['POST']) async def create_game(): global MULTIWORLDS data = await request.get_json() if not 'multidata_url' in data and not 'token' in data: abort(400, description=f'Missing multidata_url or token in data') port = int(data.get('port', random.randint(30000, 35000))) if port < 30000 or port > 35000:
def run_server(port, bind_address, handler=None, asynchronous=True, ssl_creds=None): ensure_event_loop() app = Quart(__name__) app.config[ "MAX_CONTENT_LENGTH"] = 256 * 1024 * 1024 # 256 MB request payload limit @app.route("/", methods=HTTP_METHODS, defaults={"path": ""}) @app.route("/<path:path>", methods=HTTP_METHODS) async def index(path=None): response = await make_response("{}") if handler: data = await request.get_data() try: result = await run_sync(handler, request, data) if isinstance(result, Exception): raise result except Exception as e: LOG.warning( "Error in proxy handler for request %s %s: %s %s", request.method, request.url, e, traceback.format_exc(), ) response.status_code = 500 if isinstance(e, HTTPErrorResponse): response.status_code = e.code or response.status_code return response if result is not None: # check if this is an async generator (for HTTP2 push event responses) async_gen = get_async_generator_result(result) if async_gen: return async_gen # prepare and return regular response is_chunked = uses_chunked_encoding(result) result_content = result.content or "" response = await make_response(result_content) response.status_code = result.status_code if is_chunked: response.headers.pop("Content-Length", None) result.headers.pop("Server", None) result.headers.pop("Date", None) headers = { k: str(v).replace("\n", r"\n") for k, v in result.headers.items() } response.headers.update(headers) # set multi-value headers multi_value_headers = getattr(result, "multi_value_headers", {}) for key, values in multi_value_headers.items(): for value in values: response.headers.add_header(key, value) # set default headers, if required if not is_chunked and request.method not in [ "OPTIONS", "HEAD" ]: response_data = await response.get_data() response.headers["Content-Length"] = str( len(response_data or "")) if "Connection" not in response.headers: response.headers["Connection"] = "close" # fix headers for OPTIONS requests (possible fix for Firefox requests) if request.method == "OPTIONS": response.headers.pop("Content-Type", None) if not response.headers.get("Cache-Control"): response.headers["Cache-Control"] = "no-cache" return response def run_app_sync(*args, loop=None, shutdown_event=None): kwargs = {} config = Config() cert_file_name, key_file_name = ssl_creds or (None, None) if cert_file_name: kwargs["certfile"] = cert_file_name config.certfile = cert_file_name if key_file_name: kwargs["keyfile"] = key_file_name config.keyfile = key_file_name setup_quart_logging() config.bind = ["%s:%s" % (bind_address, port)] loop = loop or ensure_event_loop() run_kwargs = {} if shutdown_event: run_kwargs["shutdown_trigger"] = shutdown_event.wait try: try: return loop.run_until_complete(serve(app, config, **run_kwargs)) except Exception as e: LOG.info( "Error running server event loop on port %s: %s %s", port, e, traceback.format_exc(), ) if "SSL" in str(e): c_exists = os.path.exists(cert_file_name) k_exists = os.path.exists(key_file_name) c_size = len(load_file(cert_file_name)) if c_exists else 0 k_size = len(load_file(key_file_name)) if k_exists else 0 LOG.warning( "Unable to create SSL context. Cert files exist: %s %s (%sB), %s %s (%sB)", cert_file_name, c_exists, c_size, key_file_name, k_exists, k_size, ) raise finally: try: _cancel_all_tasks(loop) loop.run_until_complete(loop.shutdown_asyncgens()) finally: asyncio.set_event_loop(None) loop.close() class ProxyThread(FuncThread): def __init__(self): FuncThread.__init__(self, self.run_proxy, None) self.shutdown_event = None self.loop = None def run_proxy(self, *args): self.loop = ensure_event_loop() self.shutdown_event = asyncio.Event() run_app_sync(loop=self.loop, shutdown_event=self.shutdown_event) def stop(self, quiet=None): event = self.shutdown_event async def set_event(): event.set() run_coroutine(set_event(), self.loop) super().stop(quiet) def run_in_thread(): thread = ProxyThread() thread.start() TMP_THREADS.append(thread) return thread if asynchronous: return run_in_thread() return run_app_sync()
from quart import Quart, render_template from quart import websocket import json from sense_hat import SenseHat from robot import Robot import cv2 import base64 import asyncio app = Quart(__name__, template_folder="../react-display/build", static_folder="../react-display/build/static") def encode(cap): _, frame = cap.read() frame = cv2.resize(frame, (int(1280 / 2), int(720 / 2))) _, buffer = cv2.imencode(".jpg", frame) string_data = base64.b64encode(buffer) return str(string_data, encoding="utf-8") @app.route('/') def home(): return render_template('index.html') @app.websocket("/control") async def control(): robot = Robot() while True:
def app() -> Quart: app = Quart(__name__) return app
def create_app(test_config=None): # create and configure the app app = Quart(__name__) cors(app, allow_origin="*") parser = argparse.ArgumentParser( description="Runs a Coordinator demo agent.") parser.add_argument( "-p", "--port", type=int, default=8020, metavar=("<port>"), help="Choose the starting port number to listen on", ) parser.add_argument("--timing", action="store_true", help="Enable timing information") args = parser.parse_args() require_indy() agent = None try: agent = asyncio.get_event_loop().run_until_complete( create_agent(args.port, args.timing)) except KeyboardInterrupt: os._exit(1) log_msg("Agent created", agent.active_connection_id) if test_config is None: # load the instance config, if it exists, when not testing app.config.from_pyfile('config.py', silent=True) else: # load the test config if passed in app.config.from_mapping(test_config) # a simple page that says hello @app.route('/hello') def hello(): return 'Hello, World!' @app.route('/connect') async def connect(): # Generate an invitation log_status( "#5 Create a connection to alice and print out the invite details") connection = await agent.admin_POST("/connections/create-invitation") agent.active_connection_id = connection["connection_id"] agent.connection_list.append(connection["connection_id"]) log_msg("all connections :", agent.connection_list) log_json(connection, label="Invitation response:") log_msg("*****************") log_msg(json.dumps(connection["invitation"]), label="Invitation:", color=None) log_msg("*****************") agent._connection_ready = asyncio.Future() return json.dumps(connection["invitation"]) @app.route('/trustedconnections') def connections(): # Generate an invitation log_msg(agent.connection_list) return json.dumps(agent.trusted_connection_ids) return app
from relay_sdk import Interface, WebhookServer from quart import Quart, request, jsonify, make_response import logging import json relay = Interface() app = Quart('github-event') logging.getLogger().setLevel(logging.INFO) @app.route('/', methods=['POST']) async def handler(): github_event = request.headers.get('X-GitHub-Event') if github_event is None: return {'message': 'not a valid GitHub event'}, 400, {} if github_event == 'ping': return {'message': 'success'}, 200, {} logging.info("Received event from GitHub: {}".format(github_event)) event_payload = await request.get_json() logging.info("Received the following webhook payload: \n%s", json.dumps(event_payload, indent=4)) if event_payload is None: return {'message': 'not a valid GitHub event'}, 400, {} relay.events.emit({
def __init__(self, name: str) -> None: self._setup_logger(name) self.api = Quart(name) self.shutdown_event = asyncio.Event() self.loop = asyncio.get_event_loop()
async def _app(config): app = Quart(__name__) app.config.update(config) db = Gino(app) class User(db.Model): __tablename__ = 'gino_users' id = db.Column(db.BigInteger(), primary_key=True) nickname = db.Column(db.Unicode(), default='noname') @app.route('/') async def root(): return 'Hello, world!' async def _get_user(ctx, uid: int, method: str) -> dict: q = User.query.where(User.id == uid) if method == '1': return (await q.gino.first_or_404()).to_dict() elif method == '2' and ctx: return (await ctx.connection.first_or_404(q)).to_dict() elif method == '3': return (await db.bind.first_or_404(q)).to_dict() elif method == '4': return (await db.first_or_404(q)).to_dict() else: return (await User.get_or_404(uid)).to_dict() @app.route('/users/<int:uid>') async def get_user(uid): method = request.args.get('method') return jsonify(await _get_user(request, uid, method)) async def _add_user(ctx, nickname: str) -> dict: u = await User.create(nickname=nickname) await u.query.gino.first_or_404() await db.first_or_404(u.query) await db.bind.first_or_404(u.query) if ctx: await ctx.connection.first_or_404(u.query) return u.to_dict() @app.route('/users', methods=['POST']) async def add_user(): return jsonify(await _add_user(request, (await request.form).get('name'))) @app.websocket('/ws') async def ws(): while True: data = json.loads(await websocket.receive()) action = data.get('action') if action == 'add': new_user = await _add_user(None, data.get('name')) await websocket.send(json.dumps(new_user)) elif action == 'get': try: user = await _get_user(None, int(data.get('id')), data.get('method')) except NotFound: await websocket.send(json.dumps({'error': 'not found'})) else: await websocket.send(json.dumps(user)) else: await websocket.send(json.dumps({'error': 'Invalid JSON'})) e = await gino.create_engine(PG_URL) try: try: await db.gino.create_all(e) await yield_(app) finally: await db.gino.drop_all(e) finally: await e.close()
def run_server(port, handler=None, asynchronous=True, ssl_creds=None): ensure_event_loop() app = Quart(__name__) app.config[ 'MAX_CONTENT_LENGTH'] = 256 * 1024 * 1024 # 256 MB request payload limit @app.route('/', methods=HTTP_METHODS, defaults={'path': ''}) @app.route('/<path:path>', methods=HTTP_METHODS) async def index(path=None): response = await make_response('{}') if handler: data = await request.get_data() try: result = await run_sync(handler, request, data) except Exception as e: LOG.warning( 'Error in proxy handler for request %s %s: %s %s' % (request.method, request.url, e, traceback.format_exc())) response.status_code = 500 return response if result is not None: is_chunked = uses_chunked_encoding(result) result_content = result.content or '' response = await make_response(result_content) response.status_code = result.status_code if is_chunked: response.headers.pop('Content-Length', None) result.headers.pop('Server', None) result.headers.pop('Date', None) response.headers.update(dict(result.headers)) # set multi-value headers multi_value_headers = getattr(result, 'multi_value_headers', {}) for key, values in multi_value_headers.items(): for value in values: response.headers.add_header(key, value) # set default headers, if required if 'Content-Length' not in response.headers and not is_chunked: response.headers['Content-Length'] = str( len(result_content) if result_content else 0) if 'Connection' not in response.headers: response.headers['Connection'] = 'close' return response def run_app_sync(*args, loop=None, shutdown_event=None): kwargs = {} config = Config() cert_file_name, key_file_name = ssl_creds or (None, None) if cert_file_name: kwargs['certfile'] = cert_file_name config.certfile = cert_file_name if key_file_name: kwargs['keyfile'] = key_file_name config.keyfile = key_file_name setup_quart_logging() config.bind = ['0.0.0.0:%s' % port] loop = loop or ensure_event_loop() run_kwargs = {} if shutdown_event: run_kwargs['shutdown_trigger'] = shutdown_event.wait try: try: return loop.run_until_complete(serve(app, config, **run_kwargs)) except Exception as e: LOG.info('Error running server event loop on port %s: %s %s' % (port, e, traceback.format_exc())) if 'SSL' in str(e): c_exists = os.path.exists(cert_file_name) k_exists = os.path.exists(key_file_name) c_size = len(load_file(cert_file_name)) if c_exists else 0 k_size = len(load_file(key_file_name)) if k_exists else 0 LOG.warning( 'Unable to create SSL context. Cert files exist: %s %s (%sB), %s %s (%sB)' % (cert_file_name, c_exists, c_size, key_file_name, k_exists, k_size)) raise finally: try: _cancel_all_tasks(loop) loop.run_until_complete(loop.shutdown_asyncgens()) finally: asyncio.set_event_loop(None) loop.close() class ProxyThread(FuncThread): def __init__(self): FuncThread.__init__(self, self.run_proxy, None) def run_proxy(self, *args): loop = ensure_event_loop() self.shutdown_event = asyncio.Event() run_app_sync(loop=loop, shutdown_event=self.shutdown_event) def stop(self, quiet=None): self.shutdown_event.set() def run_in_thread(): thread = ProxyThread() thread.start() TMP_THREADS.append(thread) return thread if asynchronous: return run_in_thread() return run_app_sync()
async def test_send_file_bytes_io() -> None: app = Quart(__name__) io_stream = BytesIO(b"something") async with app.app_context(): response = await send_file(io_stream, mimetype="text/plain") assert (await response.get_data(raw=True)) == b"something" # type: ignore
# Copyright (c) 2020 Xiaozhe Yao & AICAMP.CO.,LTD # # This software is released under the MIT License. # https://opensource.org/licenses/MIT #coding:utf-8 from quart import Quart aidserver = Quart(__name__) # Explicitly declare solver in the aidserver aidserver.solver = None
buffer_to_wav, get_wav_duration, load_phoneme_examples, read_dict, recursive_remove, ) # ----------------------------------------------------------------------------- # Quart Web App Setup # ----------------------------------------------------------------------------- logger = logging.getLogger(__name__) loop = asyncio.get_event_loop() app = Quart("rhasspy") app.secret_key = str(uuid4()) app = cors(app) # ----------------------------------------------------------------------------- # Parse Arguments # ----------------------------------------------------------------------------- parser = argparse.ArgumentParser("Rhasspy") parser.add_argument("--profile", "-p", required=True, type=str, help="Name of profile to load") parser.add_argument("--host", type=str,
from comics import ComicScraper from constants import ( ALT_DATE_FMT, DB_TIMEOUT, FETCH_TIMEOUT, FIRST_COMIC, MAX_DB_CONN, MAX_FETCH_CONN, REPO, SRC_PREFIX, ) from latest import LatestDateScraper from utils import curr_date, date_to_str, str_to_date app = Quart("Dilbert Viewer") @app.before_serving async def create_aux() -> None: """Initialize and store auxiliary items. The auxiliary items are: * The database connection pool for caching data * The aiohttp session for scraping comics * The scrapers for the comics and the latest comic date """ # Heroku needs SSL for its PostgreSQL DB, but has issues with verifying # the certificate. So simply disable verification while keeping SSL. ctx = ssl.create_default_context(cafile="")
def setUp(self): quart_app = Quart(__name__) quart_app.config['BCRYPT_LOG_ROUNDS'] = 6 quart_app.config['BCRYPT_HASH_IDENT'] = '2b' quart_app.config['BCRYPT_HANDLE_LONG_PASSWORDS'] = True self.quart_bcrypt = Bcrypt(quart_app)
from relay_sdk import Interface, WebhookServer from quart import Quart, request, jsonify, make_response import logging import json relay = Interface() app = Quart('azure-event') logging.getLogger().setLevel(logging.INFO) @app.route('/', methods=['POST']) async def handler(): subscription_validation = request.headers.get('aeg-event-type') # Perform the subscription validation of the webhook - Details here: https://docs.microsoft.com/en-us/azure/event-grid/webhook-event-delivery if subscription_validation == 'SubscriptionValidation': payload = await request.get_json() logging.info("Received the following webhook payload: \n%s", json.dumps(payload, indent=4)) logging.info("Validating webhook subscription with Azure") return {'validationResponse': payload[0]['data']['validationCode']}, 200, {} # If webhook subscription is validated, start receiving events. event_payload = await request.get_json() logging.info("Received the following webhook payload: \n%s", json.dumps(event_payload, indent=4)) if event_payload is None: return{'message': 'not a valid Azure EventGrid event'}, 400, {} # Emit the event payload to Relay
def create_http_app(storage, http_server_input_message_queue, get_compilation_errors_for_json, is_program_running, run_program, stop_program, device_names, set_motor_power, reset_motors): from quart import Quart, websocket, request, jsonify, Response app = Quart('boost') @app.route('/') async def hello_world(): return 'Home' @app.route('/whole_state') async def whole_state(): motors_constants = storage.get_motors_constants() return jsonify({ 'programs': storage.get_programs(), 'compilation_errors': get_compilation_errors_for_json()['errors'], 'program_running': is_program_running(), 'auto_run': storage.get_auto_run(), 'device_names': device_names, 'constants': { 'power_definitions': motors_constants.power_definitions, 'ramp_up_time_from_zero_to_max_in_sec': motors_constants.ramp_up_time_from_zero_to_max_in_sec, }, }) @app.route('/command/savePrograms', methods=['POST']) async def command_save_programs(): programs = await request.json ok = storage.set_programs(programs) if ok: return Response('Ok', mimetype='text/plain') else: return Response('Compilation errors', status=400, mimetype='text/plain') @app.route('/command/runProgram', methods=['POST']) async def command_run_program(): ok = run_program() if ok: return Response('Ok', mimetype='text/plain') else: return Response('Compilation errors', status=400, mimetype='text/plain') @app.route('/command/stopProgram', methods=['POST']) async def command_stop_program(): stop_program() return Response('Ok', mimetype='text/plain') @app.route('/command/setAutoRun', methods=['POST']) async def command_set_auto_run(): data = await request.json result = storage.set_auto_run(data) return jsonify(result) @app.route('/command/setMotorPower', methods=['POST']) async def command_set_motor_power(): data = await request.json set_motor_power(data['device'], data['power']) return Response('Ok', mimetype='text/plain') @app.route('/command/resetMotors', methods=['POST']) async def command_reset_motors(): reset_motors() return Response('Ok', mimetype='text/plain') @app.route('/command/saveConstants', methods=['POST']) async def command_save_constants(): data = await request.json storage.set_constants(data) return Response('Ok', mimetype='text/plain') async def ws_sending(): while True: msg = await http_server_input_message_queue.get_next_message() await websocket.send(json.dumps(msg)) async def ws_receiving(): while True: data = await websocket.receive() print(f'received: {data}') @app.websocket('/websocket') async def ws(): producer = asyncio.create_task(ws_sending()) consumer = asyncio.create_task(ws_receiving()) await asyncio.gather(producer, consumer) return app
import subprocess import threading import shutil import os from quart import Quart, request, jsonify, render_template from static_bp import static app = Quart(__name__, "/static", static_folder=None) app.register_blueprint(static, url_prefix='/static') @app.route("/api/download", methods=['POST']) async def download(): request_json = await request.get_json() print(request_json) try: if request_json["download_audio"]: type_flag = " -x " else: type_flag = "" except TypeError: return jsonify({ "error": "bad_request" }), 400 if os.name != 'nt': ytdl = subprocess.run(f"./youtube-dl -o static/%(id)s.%(ext)s {type_flag} {request_json['video_url']}", capture_output=True) else: ytdl = subprocess.run(f"youtube-dl.exe -o static/%(id)s.%(ext)s {type_flag} {request_json['video_url']}", capture_output=True) stdout_lines = ytdl.stdout.split(b"\n") print(stdout_lines)
def test_build_headers_path_and_query_string_with_query_string_error() -> None: with pytest.raises(ValueError): make_test_headers_path_and_query_string(Quart(__name__), "/?a=b", None, {"c": "d"})
# Copyright (C) 2018 - 2020 MrYacha. All rights reserved. Source code available under the AGPL. # Copyright (C) 2019 Aiogram # # This file is part of MisakiBot. # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. from quart import Quart # Quart quart = Quart(__name__)
from __future__ import annotations from quart import (Quart, request) from collections import namedtuple from enum import IntEnum from random import randint from typing import Union import asyncio global Packet global edbpool Packet = namedtuple("Packet", ["requestID", "errorCode", "result"]) edbpool = Quart(__name__) class Mode(IntEnum): create = 3 read = 5 update = 7 delete = 11 async def crud(packet: Packet, mode: Mode) -> Packet: """crud(packet: Packet, mode: Mode) -> Packet: This coroutine accepts arguments of the form `namedtuple("Packet", ["requestID", "errorCode", "result"])` and citizens of the `Mode` type, i.e. `Mode.create` and `Mode.delete`. Since this coroutine remembers its state, it is useful for storing and retrieving data. """ def mapper(packet, mode): cache = {}
async def test_app(): return Quart(__name__)
from quart import Quart, websocket app = Quart(__name__) @app.route('/') async def hello(): return 'hello' @app.websocket('/ws') async def ws(): while True: await websocket.send('hello') app.run()
import logging import uuid import click from confluent_kafka import Producer, Consumer from quart import Quart, jsonify from .ticket_manager import TicketRequester, TicketResultWatcher from .. import kafka app = Quart('no-seat-ticker') ticket_office: TicketRequester = None ticket_result_watcher: TicketResultWatcher = None poll_task = None @app.route('/ticket', methods=['POST']) async def reserve_ticker(): ticket_id = str(uuid.uuid4()) future_result = ticket_result_watcher.wait_for_response(ticket_id) await ticket_office.send_ticket_request(ticket_id) success = await future_result if success: return jsonify({'ticketId': ticket_id}) else: return jsonify({'error': 'Out of ticket.'}), 410