How to use the quart.request.method function in Quart

To help you get started, we’ve selected a few Quart examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github pgjones / quart / tests / test_helpers.py View on Github external
async def generator() -> AsyncGenerator[bytes, None]:
            yield request.method.encode()
            yield b" "
            yield request.path.encode()
github pgjones / quart / tests / test_views.py View on Github external
async def dispatch_request(self, *args: Any, **kwargs: Any) -> ResponseReturnValue:
            return request.method
github synesthesiam / voice2json / mqtt / app_noprofile.py View on Github external
async def index():
    if request.method == "POST":
        form = await request.form
        for key in form:
            if key.startswith("download-"):
                profile_name = key.split("-", maxsplit=1)[1]
                await flash(f"Downloading {profile_name}", "info")
                break
            elif key.startswith("install-"):
                profile_name = key.split("-", maxsplit=1)[1]
                await install_profile(profile_name)
                await flash(f"Installed {profile_name}", "success")
                break

    return await render_template(
        "index_noprofile.html",
        profile_path=profile_path,
        download_dir=download_dir,
github dnknth / ldap-ui / app.py View on Github external
'Edit directory entries'
    
    if request.is_json:
        json = await request.get_json()
        # Copy JSON payload into a dictionary of non-empty byte strings
        req  = { k: [ s.encode() for s in filter( None, v) ]
                    for k,v in json.items()
                    if k != PHOTO}
        
    if request.method == 'GET':
        try:
            return _entry( await unique( request.ldap.search( dn, ldap.SCOPE_BASE)))
        except ValueError:
            return None

    elif request.method == 'POST':
        # Get previous values from directory
        res = await unique( request.ldap.search( dn, ldap.SCOPE_BASE))
        
        mods = { k: v for k, v in res[1].items() if k in req }
        modlist = modifyModlist( mods, req)
        
        if modlist: # Apply changes and send changed keys back
            await empty( request.ldap.modify( dn, modlist))
        return { 'changed' : sorted( set( m[1] for m in modlist)) }
    
    elif request.method == 'PUT':
        # Create new object
        modlist = addModlist( req)
        if modlist:
            await empty( request.ldap.add( dn, modlist))
        return { 'changed' : ['dn'] } # Dummy
github synesthesiam / voice2json / mqtt / app.py View on Github external
async def api_slots():
    """Get or overwrite slots"""
    slots_dir = Path(pydash.get(profile, "training.slots-directory"))
    if request.method == "POST":
        slots_dict = await request.json
        slots_dir.mkdir(parents=True, exist_ok=True)

        # Write slots
        total_length = 0
        for slot_name, slot_values in slots_dict.items():
            slot_file_path = slots_dir / slot_name
            with open(slot_file_path, "w") as slot_file:
                for value in slot_values:
                    value = value.strip()
                    print(value, file=slot_file)
                    total_length += len(value)

        # Return length of written text
        return str(total_length)
    else:
github synesthesiam / voice2json / web / app.py View on Github external
async def words():
    """Speaks words, guesses pronunciations, and reads/writes custom_words.txt.
    Re-trains when custom words are saved."""

    custom_words_path = Path(pydash.get(profile, "training.custom-words-file"))
    word = ""

    if request.method == "POST":
        form = await request.form
        action = form["action"]

        if action == "custom words":
            # Save custom words
            custom_words_text = form["custom_words"]
            custom_words_path.write_text(custom_words_text)
            do_retrain()
        elif action == "pronounce":
            # Speak or guess pronunciation
            word = form["word"]
            is_speak = "speak" in form
            if len(word) > 0:
                if is_speak:
                    # Speak pronunciation
                    result = voice2json("pronounce-word", "--nbest", "1", word)
github pgjones / quart / examples / flask_ext / flask_ext.py View on Github external
async def login():
    if request.method == 'GET':
        return '''
               <form method="POST">
                <input placeholder="username" id="username" name="username" type="text">
                <input placeholder="password" id="password" name="password" type="password">
                <input type="submit">
               </form>
               '''

    username = (await request.form)['username']
    password = (await request.form)['password']
    if username in users and compare_digest(password, users[username]['password']):
        user = User()
        user.id = username
        flask_login.login_user(user)
        return redirect(url_for('protected'))
github factset / quart-openapi / quart_openapi / resource.py View on Github external
async def dispatch_request(self, *args: Any, **kwargs: Any) -> ResponseReturnValue:
        """Can be overridden instead of creating verb functions

        This will be called with the request view_args, i.e. any url parameters
        """
        handler = getattr(self, request.method.lower(), None)
        if handler is None and request.method == 'HEAD' or request.method == 'OPTIONS':
            handler = getattr(self, 'get', None)

        await self.validate_payload(handler)
        return await handler(*args, **kwargs)
github factset / quart-openapi / quart_openapi / resource.py View on Github external
async def dispatch_request(self, *args: Any, **kwargs: Any) -> ResponseReturnValue:
        """Can be overridden instead of creating verb functions

        This will be called with the request view_args, i.e. any url parameters
        """
        handler = getattr(self, request.method.lower(), None)
        if handler is None and request.method == 'HEAD' or request.method == 'OPTIONS':
            handler = getattr(self, 'get', None)

        await self.validate_payload(handler)
        return await handler(*args, **kwargs)
github factset / quart-openapi / quart_openapi / cors.py View on Github external
async def wrapped_function(*args, **kwargs):
            if automatic_options and request.method == 'OPTIONS':
                resp = await current_app.make_default_options_response()
            else:
                resp = await make_response(await func(*args, **kwargs))
            if not attach_to_all and request.method != 'OPTIONS':
                return resp

            hdrs = resp.headers

            hdrs['Access-Control-Allow-Origin'] = origin
            hdrs['Access-Control-Allow-Methods'] = await get_methods()
            hdrs['Access-Control-Max-Age'] = str(max_age)
            if credentials:
                hdrs['Access-Control-Allow-Credentials'] = 'true'
            if headers is not None:
                hdrs['Access-Control-Allow-Headers'] = headers
            if expose_headers is not None: