Example #1
0
 def check_response(self, resp_json):
     if resp_json['status'] != 'OK':
         # 当创建/更新条目错误,且仅有一个错误时,返回内部错误信息
         if isinstance(resp_json.get('data', None), list) and len(
                 resp_json['data']) == 1:
             if 'message' in resp_json['data'][0]:
                 raise exceptions.PluginError(
                     message=resp_json['data'][0]['message'])
         raise exceptions.PluginError(message=resp_json['message'])
def expr_seg_parse(expr):
    '''
    parse a segment of expression to dict, eg. "(attr)[plugin:]ci[{key op value}*][.attr]" into
    {
        'backref_attribute': '',
        'plugin': '',
        'ci': '',
        'filters': '',
        'attribute': ''
    }
    :param expr_filter: expression
    '''
    res = R_SEG_EXPRESSION.match(expr)
    if res:
        result = {
            'expr': expr,
            'backref_attribute': res.groups()[0] or '',
            'plugin': res.groups()[1] or '',
            'ci': res.groups()[2] or '',
            'filters': res.groups()[3] or '',
            'attribute': res.groups()[4] or ''
        }
        result['filters'] = expr_filter_parse(result['filters'])
        return result
    raise exceptions.PluginError('invalid expression: ' + expr)
 def on_patch(self, req, resp, **kwargs):
     self._validate_method(req)
     self._validate_data(req)
     datas = req.json
     if not utils.is_list_type(datas):
         raise exceptions.PluginError(_('data must be list type'))
     rets = []
     ex_rets = []
     for idx, data in enumerate(datas):
         try:
             res_instance = self.make_resource(req)
             if res_instance.primary_keys not in data:
                 raise exceptions.FieldRequired(
                     attribute=res_instance.primary_keys)
             rid = data.pop(res_instance.primary_keys)
             before_update, after_update = self.update(req, data, rid=rid)
             if after_update is None:
                 raise exceptions.NotFoundError(
                     resource='%s[%s]' % (self.resource.__name__, rid))
             rets.append(after_update)
         except base_ex.Error as e:
             ex_rets.append({'index': idx + 1, 'message': str(e)})
     if len(ex_rets):
         raise exceptions.BatchPartialError(
             num=len(ex_rets),
             action='update',
             exception_data={'data': ex_rets})
     resp.json = {
         'code': 200,
         'status': 'OK',
         'data': rets,
         'message': 'success'
     }
     resp.status = falcon.HTTP_200
 def on_post(self, req, resp, **kwargs):
     self._validate_method(req)
     self._validate_data(req)
     datas = req.json
     if not utils.is_list_type(datas):
         raise exceptions.PluginError(_('data must be list type'))
     rets = []
     ex_rets = []
     for idx, data in enumerate(datas):
         try:
             rets.append(self.create(req, data, **kwargs))
         except base_ex.Error as e:
             ex_rets.append({'index': idx + 1, 'message': str(e)})
     if len(ex_rets):
         raise exceptions.BatchPartialError(
             num=len(ex_rets),
             action='create',
             exception_data={'data': ex_rets})
     resp.json = {
         'code': 200,
         'status': 'OK',
         'data': rets,
         'message': 'success'
     }
     resp.status = falcon.HTTP_200
Example #5
0
 def download_file(self, filepath, access_key, secret_key):
     secure = True if self.schema == 'https' else False
     ca_certs = os.environ.get('SSL_CERT_FILE') or certifi.where()
     http_client = urllib3.PoolManager(timeout=3,
                                       maxsize=10,
                                       cert_reqs='CERT_REQUIRED',
                                       ca_certs=ca_certs,
                                       retries=urllib3.Retry(total=1,
                                                             backoff_factor=0.2,
                                                             status_forcelist=[500, 502, 503, 504]))
     client = minio.Minio(self.host, access_key, secret_key, secure=secure, http_client=http_client)
     try:
         return client.fget_object(self.bucket, self.object_key, filepath)
     except Exception as e:
         raise exceptions.PluginError(message=_('failed to download file[%(filepath)s] from s3: %(reason)s') % {
             'filepath': self.object_key,
             'reason': str(e)
         })
 def on_patch(self, req, resp, **kwargs):
     self._validate_method(req)
     self._validate_data(req)
     data = req.json
     if data is not None and not isinstance(data, dict):
         raise exceptions.PluginError(_('data must be dict type'))
     ref_before, ref_after = self.update(req, data, **kwargs)
     if ref_after is not None:
         resp.json = {
             'code': 200,
             'status': 'OK',
             'data': ref_after,
             'message': 'success'
         }
     else:
         raise exceptions.NotFoundError(
             resource='%s[%s]' %
             (self.resource.__name__, kwargs.get('rid', '-')))
 def _json_or_error(url, **kwargs):
     try:
         try:
             return func(url, **kwargs)
         except requests.ConnectionError as e:
             LOG.error('http error: %s %s, reason: %s',
                       func.__name__.upper(), url, str(e))
             raise base_ex.CallBackError(
                 message={
                     'code': 50002,
                     'title': _('Connection Error'),
                     'description': _(
                         'Failed to establish a new connection')
                 })
         except requests.Timeout as e:
             LOG.error('http error: %s %s, reason: %s',
                       func.__name__.upper(), url, str(e))
             raise base_ex.CallBackError(
                 message={
                     'code': 50004,
                     'title': _('Timeout Error'),
                     'description': _('Server do not respond')
                 })
         except requests.HTTPError as e:
             LOG.error('http error: %s %s, reason: %s',
                       func.__name__.upper(), url, str(e))
             code = int(e.response.status_code)
             message = RestfulJson.get_response_json(e.response,
                                                     default={'code': code})
             if code == 401:
                 raise base_ex.AuthError()
             if code == 404:
                 message['title'] = _('Not Found')
                 message['description'] = _(
                     'The resource you request not exist')
             # 如果后台返回的数据不符合要求,强行修正
             if 'code' not in message:
                 message['code'] = code
             if 'title' not in message:
                 message['title'] = message.get('title', e.response.reason)
             if 'description' not in message:
                 message['description'] = message.get('message', str(e))
             raise base_ex.CallBackError(message=message)
         except Exception as e:
             LOG.error('http error: %s %s, reason: %s',
                       func.__name__.upper(), url, str(e))
             message = RestfulJson.get_response_json(e.response,
                                                     default={
                                                         'code':
                                                         500,
                                                         'title':
                                                         _('Server Error'),
                                                         'description':
                                                         str(e)
                                                     })
             if 'code' not in message:
                 message['code'] = 500
             if 'title' not in message:
                 message['title'] = message.get('title', str(e))
             if 'description' not in message:
                 message['description'] = message.get('message', str(e))
             raise base_ex.CallBackError(message=message)
     except base_ex.CallBackError as e:
         raise exceptions.PluginError(message=e.message, error_code=e.code)