Beispiel #1
0
 async def post(self, request):
     if "id" in request.json:
         raise exceptions.SanicException(
             "ID should not be specified with POST", status_code=409)
     with db_session:
         if Community.exists(slug=request.json['slug']):
             raise exceptions.SanicException("Slug already exists",
                                             status_code=409)
         c = Community(slug=request.json['slug'],
                       name=request.json.get('name', ""),
                       description=request.json.get('description', ""),
                       icon=request.json.get('icon', ""),
                       owner=request.json['owner'])
         for tag_name in request.json.get('tags', []):
             try:
                 tag = Tag[tag_name]
             except ObjectNotFound:
                 tag = Tag(tag=tag_name)
             c.tags.add(tag)
         commit()
         return response.json(c.to_dict(),
                              status=201,
                              headers={
                                  "Location":
                                  request.app.url_for(
                                      "communities_v1.CommunityDetailView",
                                      id=c.id)
                              })
Beispiel #2
0
async def authenticate(request, *args, **kwargs):
    username = (request.json and request.json.get(
        "username", None)) or (request.args and request.args.get('username'))
    password = (request.json and request.json.get(
        "password", None)) or (request.args and request.args.get('password'))

    if not (username and password):
        raise exceptions.SanicException("Missing username or password.")

    auth = await Users(username, password).authenticate()

    if not auth.get('valid'):
        raise exceptions.SanicException("Wrong username or password.")

    return auth
Beispiel #3
0
    def make_response(self, request, data, *args, **kwargs):
        """
        Looks up the representation transformer for the requested media
        type, invoking the transformer to create a response object. This
        defaults to default_mediatype if no transformer is found for the
        requested mediatype. If default_mediatype is None, a 406 Not
        Acceptable response will be sent as per RFC 2616 section 14.1

        :param data: Python object containing response data to be transformed
        """
        default_mediatype = kwargs.pop('fallback_mediatype',
                                       None) or self.default_mediatype
        mediatype = best_match_accept_mimetype(
            request,
            self.representations,
            default=default_mediatype,
        )
        if mediatype is None:
            raise exceptions.SanicException("Not Acceptable", 406)
        if mediatype in self.representations:
            resp = self.representations[mediatype](request, data, *args,
                                                   **kwargs)
            resp.headers['Content-Type'] = mediatype
            return resp
        elif mediatype == 'text/plain':
            resp = text(str(data), *args, **kwargs)
            resp.headers['Content-Type'] = 'text/plain'
            return resp
        else:
            raise exceptions.ServerError(None)
Beispiel #4
0
    def parse_args(self, req, strict=False):
        '''
        Parse all arguments from the provided request and return the results as a ParseResult

        :param bool strict: if req includes args not in parser, throw 400 BadRequest exception
        :return: the parsed results as :class:`ParseResult` (or any class defined as :attr:`result_class`)
        :rtype: ParseResult
        '''
        result = self.result_class()

        # A record of arguments not yet parsed; as each is found
        # among self.args, it will be popped out
        req.unparsed_arguments = dict(
            self.argument_class('').source(req)) if strict else {}
        errors = {}
        for arg in self.args:
            value, found = arg.parse(req, self.bundle_errors)
            if isinstance(value, ValueError):
                errors.update(found)
                found = None
            if found or arg.store_missing:
                result[arg.dest or arg.name] = value
        if errors:
            abort(HTTPStatus.BAD_REQUEST,
                  'Input payload validation failed',
                  errors=errors)

        if strict and req.unparsed_arguments:
            arguments = ', '.join(req.unparsed_arguments.keys())
            msg = 'Unknown arguments: {0}'.format(arguments)
            raise exceptions.SanicException("Bad Request", status_code=405)

        return result
Beispiel #5
0
def abort(code=HTTPStatus.INTERNAL_SERVER_ERROR, message=None, **kwargs):
    '''
    Properly abort the current request.

    Raise a `HTTPException` for the given status `code`.
    Attach any keyword arguments to the exception for later processing.

    :param int code: The associated HTTP status code
    :param str message: An optional details message
    :param kwargs: Any additional data to pass to the error payload
    :raise HTTPException:
    '''
    raise exceptions.SanicException(message=message, status_code=code)
Beispiel #6
0
async def retrieve_user(request, *args, **kwargs):
    """
    获取用户信息
    :param request:
    :param args:
    :param kwargs:
    :return:
    """

    payload = await request.app.auth.extract_payload(request)
    if not payload:
        raise exceptions.SanicException("No user_id extracted from the token.")

    user_id = payload.get('user_id')

    return payload if user_id else None