Python flask.request.mimetype() Examples

The following are 7 code examples of flask.request.mimetype(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module flask.request , or try the search function .
Example #1
Source File: __init__.py    From graphene-file-upload with MIT License 8 votes vote down vote up
def parse_body(self):
        """Handle multipart request spec for multipart/form-data"""
        content_type = request.mimetype
        if content_type == 'multipart/form-data':
            operations = load_json_body(request.form.get('operations', '{}'))
            files_map = load_json_body(request.form.get('map', '{}'))
            return place_files_in_operations(
                operations,
                files_map,
                request.files
            )
        return super(FileUploadGraphQLView, self).parse_body() 
Example #2
Source File: graphqlview.py    From graphql-server-core with MIT License 6 votes vote down vote up
def parse_body(self):
        # We use mimetype here since we don't need the other
        # information provided by content_type
        content_type = request.mimetype
        if content_type == "application/graphql":
            return {"query": request.data.decode("utf8")}

        elif content_type == "application/json":
            return load_json_body(request.data.decode("utf8"))

        elif content_type in (
            "application/x-www-form-urlencoded",
            "multipart/form-data",
        ):
            return request.form

        return {} 
Example #3
Source File: validator.py    From git-webhook with MIT License 6 votes vote down vote up
def get_data(self):
        """
        Get request data based on request.method and request.mimetype

        Returns:
            A regular dict which can be modified(scheme will modify data
            on validating)
        """
        if request.method in ['GET', 'DELETE']:
            return request.args.to_dict()
        else:
            if request.mimetype == 'application/json':
                data = request.get_json()
                if not isinstance(data, collections.Mapping):
                    self.handle_error('JSON content must be object')
                return data
            else:
                return request.form.to_dict() 
Example #4
Source File: execution.py    From cauldron with MIT License 1 votes vote down vote up
def parse_command_args(response: 'Response') -> typing.Tuple[str, str]:
    """

    :param response:
        The response object to modify with status or error data
    :return:
        A tuple where the first element if the name of the command
        to execute, and the second is a string representing the arguments
        to apply to that command.
    """

    cmd = None
    parts = None
    name = None
    args = None
    request_args = arguments.from_request()

    try:
        cmd = request_args.get('command', '')
        parts = [x.strip() for x in cmd.split(' ', 1)]
        name = parts[0].lower()

        args = request_args.get('args', '')
        if not isinstance(args, str):
            args = ' '.join(args)
        args += ' {}'.format(parts[1] if len(parts) > 1 else '').strip()
    except Exception as err:
        response.fail(
            code='INVALID_COMMAND',
            message='Unable to parse command',
            cmd=cmd if cmd else '',
            parts=parts,
            name=name,
            args=args,
            error=err,
            mime_type='{}'.format(request.mimetype),
            request_data='{}'.format(request.data),
            request_args=request_args
        )

    return name, args 
Example #5
Source File: api.py    From build-relengapi with Mozilla Public License 2.0 1 votes vote down vote up
def apimethod(return_type, *arg_types, **options):
    def wrap(wrapped):
        # adapted from wsmeext.flask (MIT-licensed)
        wsme.signature(return_type, *arg_types, **options)(wrapped)
        funcdef = wsme.api.FunctionDefinition.get(wrapped)
        funcdef.resolve_types(wsme.types.registry)

        @functools.wraps(wrapped)
        def replacement(*args, **kwargs):
            data_only = kwargs.pop('_data_only_', False)
            if data_only:
                return wrapped(*args, **kwargs)

            try:
                args, kwargs = wsme.rest.args.get_args(
                    funcdef, args, kwargs,
                    request.args, request.form,
                    request.data, request.mimetype)
            except wsme.exc.ClientSideError as e:
                raise BadRequest(e.faultstring)
            result = wrapped(*args, **kwargs)
            # if this is a Response (e.g., a redirect), just return it
            if isinstance(result, werkzeug.Response):
                return result

            # parse the result, if it was a tuple
            code = 200
            headers = {}
            if isinstance(result, tuple):
                if len(result) == 2:
                    if isinstance(result[1], dict):
                        result, headers = result
                    else:
                        result, code = result
                else:
                    result, code, headers = result
                assert 200 <= code < 299

            # convert the objects into jsonable simple types, also checking
            # the type at the same time
            result = wsme.rest.json.tojson(funcdef.return_type, result)

            # and hand to render_response, which will actually
            # generate the appropriate string form
            h = _get_handler()
            return h.render_response(result, code, headers)
        replacement.__apidoc__ = wrapped.__doc__
        return replacement
    return wrap 
Example #6
Source File: oauth2.py    From zimfarm with GNU General Public License v3.0 1 votes vote down vote up
def __call__(self):
        """Handles OAuth2 authentication"""

        # get grant_type
        if request.is_json:
            grant_type = request.json.get("grant_type")
        elif request.mimetype == "application/x-www-form-urlencoded":
            grant_type = request.form.get("grant_type")
        else:
            grant_type = request.headers.get("grant_type")

        if grant_type == "password":
            # password grant
            if request.is_json:
                username = request.json.get("username")
                password = request.json.get("password")
            elif request.mimetype == "application/x-www-form-urlencoded":
                username = request.form.get("username")
                password = request.form.get("password")
            else:
                username = request.headers.get("username")
                password = request.headers.get("password")

            if username is None:
                raise InvalidRequest('Request was missing the "username" parameter.')
            if password is None:
                raise InvalidRequest('Request was missing the "password" parameter.')

            return self.password_grant(username, password)

        if grant_type == "refresh_token":
            # refresh token grant
            if request.is_json:
                refresh_token = request.json.get("refresh_token")
            elif request.mimetype == "application/x-www-form-urlencoded":
                refresh_token = request.form.get("refresh_token")
            else:
                refresh_token = request.headers.get("refresh_token")

            if refresh_token is None:
                raise InvalidRequest(
                    'Request was missing the "refresh_token" parameter.'
                )

            try:
                refresh_token = UUID(refresh_token)
            except ValueError:
                raise InvalidGrant("Refresh token is invalid.")

            return self.refresh_token_grant(refresh_token)
        # unknown grant
        raise UnsupportedGrantType(
            "{} is not a supported grant type.".format(grant_type)
        ) 
Example #7
Source File: graphqlview.py    From flask-graphql with MIT License 1 votes vote down vote up
def parse_body(self):
        # We use mimetype here since we don't need the other
        # information provided by content_type
        content_type = request.mimetype
        if content_type == 'application/graphql':
            return {'query': request.data.decode('utf8')}

        elif content_type == 'application/json':
            return load_json_body(request.data.decode('utf8'))

        elif content_type in ('application/x-www-form-urlencoded', 'multipart/form-data'):
            return request.form

        return {}