def process_request(self, req, resp):
        if not req.client_accepts_json:
            raise falcon.HTTPNotAcceptable(
                'This API only supports responses encoded as JSON.',
                href='http://docs.examples.com/api/json')

        '''if req.method in ('POST', 'PUT'):
示例#2
0
def require_json(req, resp, resource, params):
    """Falcon hook to require client to accept JSON.

    Raise HTTPNotAcceptable if client does not accept JSON.
    """
    if not req.client_accepts_json:
        raise falcon.HTTPNotAcceptable('HTTP client not accepting JSON.')
示例#3
0
    def on_post(self, req, resp):

        req_json = json.loads(req.bounded_stream.read(), encoding='utf-8')
        # check json key
        for key in req_json.keys():
            if key not in ['username', 'password']:
                # return status code 406  not acceptable
                raise falcon.HTTPNotAcceptable(falcon.HTTP_NOT_ACCEPTABLE)

        if req_json['username'] != config.NEWS_ADMIN_ACCOUNT and req_json[
                'password'] != config.NEWS_ADMIN_PASSWORD:
            raise falcon.HTTPUnauthorized()

        token = util.randStr(32)
        req_json['token'] = token
        red_auth_token.set(name="{username}_{token}".format(
            username=req_json['username'], token=token),
                           value='',
                           ex=config.ADMIN_JWT_EXPIRE_TIME)
        JWT_token = jwt_auth.get_auth_token(user_payload=req_json)
        resp.media = {
            'token':
            JWT_token,
            'expireTime':
            (datetime.datetime.utcnow() +
             datetime.timedelta(seconds=config.ADMIN_JWT_EXPIRE_TIME)
             ).isoformat(timespec='seconds') + "Z"
        }
        resp.media['isAdmin'] = True

        resp.status = falcon.HTTP_200
        return True
示例#4
0
    def process_request(self, request, response):
        if not request.client_accepts_json:
            raise falcon.HTTPNotAcceptable('Response encoded as JSON')

        if request.method in ('POST'):
            if 'application/json' not in request.content_type:
                raise falcon.HTTPUnsupportedMediaType('Requests encoded as JSON')
示例#5
0
    def on_post(self, req, resp):
        if not req.client_accepts_json:
            raise falcon.HTTPNotAcceptable(
                'This API only supports responses encoded as JSON.')

        if 'application/json' not in req.content_type:
            raise falcon.HTTPUnsupportedMediaType(
                'This API only supports requests encoded as JSON.')

        data = json.loads(req.stream.read().decode('utf-8'))
        print(data)
        action = data['action']
        result = {'action': action, 'result': 0}

        if action == 'add':
            add_result = self.contacts.insert_one(data['data'])
            result['result'] = str(add_result.inserted_id)

        elif action == 'delete':
            delete_result = self.contacts.delete_one(
                {'_id': ObjectId(data['id'])})
            if (delete_result.deleted_count):
                result['result'] = data['id']

        elif action == 'update':
            update_result = self.contacts.replace_one(
                {'_id': ObjectId(data['id'])}, data['data'])
            if (update_result.modified_count):
                result['result'] = data['id']

        resp.content_type = 'application/json'
        resp.body = json_util.dumps(result)
示例#6
0
    def on_get(self, req, resp):
        if not req.client_accepts_json:
            raise falcon.HTTPNotAcceptable(
                'This API only supports responses encoded as JSON.',
                href='http://docs.examples.com/api/json')

        if req.method in ('POST', 'PUT'):
            if 'application/json' not in req.content_type:
                raise falcon.HTTPUnsupportedMediaType(
                    'This API only supports requests encoded as JSON.',
                    href='http://docs.examples.com/api/json')

        #id = req.get_param('id')
        #profiles = RetrieveProfile().ExtractUsersData()
        #for profile in profiles:
        #    profile.addTag()

        #recommendations = Recommendation.RetrieveProfileAndCalculate(profiles)

        #resp.content_type = falcon.MEDIA_JSON

        #simples = []
        #for recommendation in recommendations:
        #    simple = Simple(recommendation.profile.id, recommendation.recommendations)
        #    simples.append(simple)

        url = "https://8yibsgfqyb.execute-api.us-east-1.amazonaws.com/default/testConnectionMongoDB"
        payload = {}
        headers = {}
        response = requests.request("GET", url, headers=headers, data=payload)
        print(response.text.encode('utf8'))
        resp.body = response.text.encode('utf8')
        resp.status = falcon.HTTP_200
示例#7
0
    def process_request(self, req, resp):
        logger.info('Incoming request ' + req.path)

        enforce = False
        if self.paths is None:
            enforce = True
        else:
            for path in self.paths:
                if req.path.startswith(path):
                    enforce = True

        if enforce:
            if not req.client_accepts_json:
                logger.info(
                    'Client does not accept an JSON answer for {path}'.format(
                        path=req.path))
                raise falcon.HTTPNotAcceptable(
                    'This API only supports responses encoded as JSON.',
                    href='http://docs.examples.com/api/json')

            if req.method in ('POST', 'PUT'):
                logger.info(
                    'For path {method}: {path} only JSON requests are accepted'
                    .format(method=req.method, path=req.path))
                if 'application/json' not in req.content_type:
                    raise falcon.HTTPUnsupportedMediaType(
                        'This API only supports requests encoded as JSON.',
                        href='http://docs.examples.com/api/json')
示例#8
0
文件: hocks.py 项目: qoneci/notify
def require_json(req, resp, resource, params):
    if not req.client_accepts_json:
        raise falcon.HTTPNotAcceptable(
            'This API only supports responses encoded as JSON.')

    if req.method in ('POST', 'PUT'):
        if 'application/json' not in req.content_type:
            raise falcon.HTTPUnsupportedMediaType(
                'This API only supports requests encoded as JSON.')
示例#9
0
def RequireJson(**request_handler_args):
    req = request_handler_args['req']
    if not req.client_accepts_json:
        raise falcon.HTTPNotAcceptable(
            'This API only supports responses encoded as JSON.')
    if req.method in ('POST', 'PUT', 'GET'):
        if 'application/json' not in req.content_type:
            raise falcon.HTTPUnsupportedMediaType(
                'This API only supports requests encoded as JSON.')
示例#10
0
    def process_request(self, req, resp):
        if not req.client_accepts('application/python-pickle'):
            raise falcon.HTTPNotAcceptable(
                'This API only supports responses encoded as pickle.')

        if req.method in ('POST', 'PUT'):
            if 'application/python-pickle' not in req.content_type:
                raise falcon.HTTPUnsupportedMediaType(
                    'This API only supports requests encoded as pickle.')
示例#11
0
    def process_request(self, req, resp):
        if not req.client_accepts_json:
            raise falcon.HTTPNotAcceptable(
                description='JSON is the only supported response format')

        if req.method in ('POST', 'PUT'):
            if req.content_type and 'application/json' not in req.content_type:
                raise falcon.HTTPUnsupportedMediaType(
                    description='JSON is the only supported request format')
示例#12
0
 def process_request(self, req, resp):
     if not req.client_accepts_json:
         falcon_log.exception('Error handling request with wrong format')
         raise falcon.HTTPNotAcceptable(
             'This API only supports responses encoded as JSON.')
     if req.method in ('POST',):
         if 'application/json' not in req.content_type:
             falcon_log.exception('Error handling request with wrong format')
             raise falcon.HTTPUnsupportedMediaType(
                 'This API only supports requests encoded as JSON.')
示例#13
0
    def process_request(self, req, resp):
        auth = req.get_header('Authorization')
        if auth:
            method, _, auth = auth.partition(' ')
            if method != 'Bearer':
                raise falcon.HTTPNotAcceptable('This API only supports Bearer Authorization')

            t = TokenController(req.session)
            req.user = t.get_user_from_token(auth)Q
            req.token = auth
示例#14
0
    def handle(ex, req, resp, params):
        """

        :param ex:
        :param req:
        :param resp:
        :param params:
        :return:
        """
        description = 'Unable to parse uploaded file. Please check and retry'
        raise falcon.HTTPNotAcceptable(description)
示例#15
0
    def handle(ex, req, resp, params):
        """

        :param ex:
        :param req:
        :param resp:
        :param params:
        :return:
        """
        description = 'Not enough data to build the model.'
        raise falcon.HTTPNotAcceptable(description)
示例#16
0
    def convert_file(self, original_path, converted_path, new, org):
        try:
            f = self._conversions["{org}{new}".format(org=org, new=new)]

        except KeyError:
            raise falcon.HTTPNotAcceptable(
                "Please contact the provider for list of acceptable file names",
                "File Name"
            )

        return f(original_path=original_path, converted_path=converted_path)
示例#17
0
def decode_jwt_header(jwt_token):
    try:
        if JWT_SETTINGS["PUBLIC_KEY"] is not None:
            decode = jwt.decode(jwt_token, JWT_SETTINGS["PUBLIC_KEY"], algorithms='RS256')
            return decode, "Success decode"
        elif JWT_SETTINGS["JWT_KEY"] is not None:
            decode = jwt.decode(jwt_token, JWT_SETTINGS["JWT_KEY"], algorithms='HS256')
            return decode, "Success decode"
        else:
            raise falcon.HTTPNotAcceptable(description='No JWT_KEY or PUBLICK_KEY provided')
    except Exception as error:
        return None, str(error)