"Fossies" - the Fresh Open Source Software Archive

Member "monasca-api-3.1.0/monasca_api/common/rest/utils.py" (27 Sep 2019, 3240 Bytes) of package /linux/misc/openstack/monasca-api-3.1.0.tar.gz:


As a special service "Fossies" has tried to format the requested source page into HTML format using (guessed) Python source code syntax highlighting (style: standard) with prefixed line numbers. Alternatively you can here view or download the uninterpreted source code file. For more information about "utils.py" see the Fossies "Dox" file reference documentation and the last Fossies "Diffs" side-by-side code changes report: 3.1.0_vs_4.0.0.

    1 # Copyright 2015 FUJITSU LIMITED
    2 #
    3 # Licensed under the Apache License, Version 2.0 (the "License"); you may
    4 # not use this file except in compliance with the License. You may obtain
    5 # a copy of the License at
    6 #
    7 #      http://www.apache.org/licenses/LICENSE-2.0
    8 #
    9 # Unless required by applicable law or agreed to in writing, software
   10 # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
   11 # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
   12 # License for the specific language governing permissions and limitations
   13 # under the License.
   14 
   15 import six
   16 import ujson as json
   17 
   18 from monasca_api.common.rest import exceptions
   19 
   20 ENCODING = 'utf8'
   21 
   22 TEXT_CONTENT_TYPE = 'text/plain'
   23 JSON_CONTENT_TYPE = 'application/json'
   24 
   25 
   26 def _try_catch(fun):
   27 
   28     @six.wraps(fun)
   29     def wrapper(*args, **kwargs):
   30         try:
   31             return fun(*args, **kwargs)
   32         except Exception as ex:
   33             raise exceptions.DataConversionException(str(ex))
   34 
   35     return wrapper
   36 
   37 
   38 @_try_catch
   39 def as_json(data, **kwargs):
   40     """Writes data as json.
   41 
   42     :param dict data: data to convert to json
   43     :param kwargs kwargs: kwargs for json dumps
   44     :return: json string
   45     :rtype: str
   46     """
   47 
   48     if 'sort_keys' not in kwargs:
   49         kwargs['sort_keys'] = False
   50     if 'ensure_ascii' not in kwargs:
   51         kwargs['ensure_ascii'] = False
   52 
   53     data = json.dumps(data, **kwargs)
   54 
   55     return data
   56 
   57 
   58 @_try_catch
   59 def from_json(data, **kwargs):
   60     """Reads data from json str.
   61 
   62     :param str data: data to read
   63     :param kwargs kwargs: kwargs for json loads
   64     :return: read data
   65     :rtype: dict
   66     """
   67     return json.loads(data, **kwargs)
   68 
   69 
   70 _READABLE_CONTENT_TYPES = {
   71     TEXT_CONTENT_TYPE: lambda content: content,
   72     JSON_CONTENT_TYPE: from_json
   73 }
   74 
   75 
   76 def read_body(payload, content_type=JSON_CONTENT_TYPE):
   77     """Reads HTTP payload according to given content_type.
   78 
   79     Function is capable of reading from payload stream.
   80     Read data is then processed according to content_type.
   81 
   82     Note:
   83         Content-Type is validated. It means that if read_body
   84         body is not capable of reading data in requested type,
   85         it will throw an exception.
   86 
   87     If read data was empty method will return false boolean
   88     value to indicate that.
   89 
   90     Note:
   91         There is no transformation if content type is equal to
   92         'text/plain'. What has been read is returned.
   93 
   94     :param stream payload: payload to read, payload should have read method
   95     :param str content_type: payload content type, default to application/json
   96     :return: read data, returned type depends on content_type or False
   97              if empty
   98 
   99     :exception: :py:class:`.UnreadableBody` - in case of any failure when
  100                                               reading data
  101 
  102     """
  103     if content_type not in _READABLE_CONTENT_TYPES:
  104         msg = ('Cannot read %s, not in %s' %
  105                (content_type, _READABLE_CONTENT_TYPES))
  106         raise exceptions.UnsupportedContentTypeException(msg)
  107 
  108     try:
  109         content = payload.read()
  110         if not content:
  111             return None
  112     except Exception as ex:
  113         raise exceptions.UnreadableContentError(str(ex))
  114 
  115     return _READABLE_CONTENT_TYPES[content_type](content)