當前位置: 首頁>>代碼示例>>Python>>正文


Python flask_restful.marshal方法代碼示例

本文整理匯總了Python中flask_restful.marshal方法的典型用法代碼示例。如果您正苦於以下問題:Python flask_restful.marshal方法的具體用法?Python flask_restful.marshal怎麽用?Python flask_restful.marshal使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在flask_restful的用法示例。


在下文中一共展示了flask_restful.marshal方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: make_response

# 需要導入模塊: import flask_restful [as 別名]
# 或者: from flask_restful import marshal [as 別名]
def make_response(data, marshal_table, cursors=None):
  if util.is_iterable(data):
    response = {
      'status': 'success',
      'count': len(data),
      'now': datetime.utcnow().isoformat(),
      'result': [flask_restful.marshal(d, marshal_table) for d in data],
    }
    if cursors:
      if isinstance(cursors, dict):
        if cursors.get('next'):
          response['next_cursor'] = cursors['next']
          response['next_url'] = util.generate_next_url(cursors['next'])
        if cursors.get('prev'):
          response['prev_cursor'] = cursors['prev']
          response['prev_url'] = util.generate_next_url(cursors['prev'])
      else:
        response['next_cursor'] = cursors
        response['next_url'] = util.generate_next_url(cursors)
    return util.jsonpify(response)
  return util.jsonpify({
    'status': 'success',
    'now': datetime.utcnow().isoformat(),
    'result': flask_restful.marshal(data, marshal_table),
  }) 
開發者ID:lipis,項目名稱:github-stats,代碼行數:27,代碼來源:helpers.py

示例2: get

# 需要導入模塊: import flask_restful [as 別名]
# 或者: from flask_restful import marshal [as 別名]
def get(self, todo_id=None):
        if todo_id:
            todo = Todo.query.filter_by(id=todo_id).first()
            return marshal(todo, todo_fields)
        else:
            args = request.args.to_dict()
            limit = args.get('limit', 0)
            offset = args.get('offset', 0)

            args.pop('limit', None)
            args.pop('offset', None)

            todo = Todo.query.filter_by(**args).order_by(Todo.id)
            if limit:
                todo = todo.limit(limit)

            if offset:
                todo = todo.offset(offset)

            todo = todo.all()

            return marshal({
                'count': len(todo),
                'todos': [marshal(t, todo_fields) for t in todo]
            }, todo_list_fields) 
開發者ID:tomasrasymas,項目名稱:flask-restful-api-template,代碼行數:27,代碼來源:resource.py

示例3: get

# 需要導入模塊: import flask_restful [as 別名]
# 或者: from flask_restful import marshal [as 別名]
def get(self, user_id=None):
        if user_id:
            user = User.query.filter_by(id=user_id).first()
            return marshal(user, user_fields)
        else:
            args = request.args.to_dict()
            limit = args.get('limit', 0)
            offset = args.get('offset', 0)

            args.pop('limit', None)
            args.pop('offset', None)

            user = User.query.filter_by(**args).order_by(User.id)
            if limit:
                user = user.limit(limit)

            if offset:
                user = user.offset(offset)

            user = user.all()

            return marshal({
                'count': len(user),
                'users': [marshal(u, user_fields) for u in user]
            }, user_list_fields) 
開發者ID:tomasrasymas,項目名稱:flask-restful-api-template,代碼行數:27,代碼來源:resource.py

示例4: get

# 需要導入模塊: import flask_restful [as 別名]
# 或者: from flask_restful import marshal [as 別名]
def get(self, appinterface_id):
        """Method to handle application GET requests
        
        Args:
            appinterface_id (int): Application Interface ID
        """
        try:
            interface = interfaceManager.getInterface(appinterface_id)
            # Return a 404 if not found.
            if interface is None:
                abort(404, message={'error': "Application interface id {} "
                            "doesn't exist.".format(str(appinterface_id))})
            
            # Return the interface's marshalled attributes
            returnValue(interface.marshal())
            yield
            
        except TimeoutError:
            log.error("REST API timeout retrieving application interface "
                      "{id}", id=appinterface_id) 
開發者ID:Fluent-networks,項目名稱:floranet,代碼行數:22,代碼來源:appinterface.py

示例5: get

# 需要導入模塊: import flask_restful [as 別名]
# 或者: from flask_restful import marshal [as 別名]
def get(self, appeui):
        """Method to get all app properties"""
        try:
            
            # Return a 404 if the application is not found.            
            app = yield Application.find(where=['appeui = ?', appeui], limit=1)
            if app is None:
                abort(404, message={'error': "Application {} doesn't exist."
                                    .format(euiString(appeui))})
                
            # Get the properties
            properties = yield app.properties.get()
            if properties is None:
                returnValue({})
            
            data = {}
            for i,p in enumerate(properties):
                data[i] = marshal(p, self.fields)
            returnValue(data)
            
        except TimeoutError:
            log.error("REST API timeout retrieving application {appeui} "
                      "properties", appeui=euiString(appeui)) 
開發者ID:Fluent-networks,項目名稱:floranet,代碼行數:25,代碼來源:appproperty.py

示例6: get

# 需要導入模塊: import flask_restful [as 別名]
# 或者: from flask_restful import marshal [as 別名]
def get(self, appeui):
        """Method to handle application GET requests
        
        Args:
            appeui (int): Application EUI
        """
        try:
            a = yield Application.find(where=['appeui = ?', appeui], limit=1)
            # Return a 404 if not found.
            if a is None:
                abort(404, message={'error': "Application {} doesn't exist."
                                    .format(euiString(appeui))})
            
            data = marshal(a, self.fields)
            data['properties'] = yield self.getProperties(a)
            returnValue(data)
            
        except TimeoutError:
            log.error("REST API timeout retrieving application {appeui}",
                      appeui=euiString(appeui)) 
開發者ID:Fluent-networks,項目名稱:floranet,代碼行數:22,代碼來源:application.py

示例7: marshal

# 需要導入模塊: import flask_restful [as 別名]
# 或者: from flask_restful import marshal [as 別名]
def marshal(self):
        """Get REST API marshalled fields as an orderedDict
        
        Returns:
            OrderedDict of fields defined by marshal_fields
        """
        marshal_fields = {
            'type': fields.String(attribute='__class__.__name__'),
            'id': fields.Integer(attribute='appinterface.id'),
            'name': fields.String,
            'iothost': fields.String,
            'keyname': fields.String,
            'keyvalue': fields.String,
            'started': fields.Boolean,
        }
        return marshal(self, marshal_fields) 
開發者ID:Fluent-networks,項目名稱:floranet,代碼行數:18,代碼來源:azure_iot_mqtt.py

示例8: marshal

# 需要導入模塊: import flask_restful [as 別名]
# 或者: from flask_restful import marshal [as 別名]
def marshal(self):
        """Get REST API marshalled fields as an orderedDict
        
        Returns:
            OrderedDict of fields defined by marshal_fields
        """
        marshal_fields = {
            'type': fields.String(attribute='__class__.__name__'),
            'id': fields.Integer(attribute='appinterface.id'),
            'name': fields.String,
            'iothost': fields.String,
            'keyname': fields.String,
            'keyvalue': fields.String,
            'poll_interval': fields.Integer,
            'started': fields.Boolean,
        }
        return marshal(self, marshal_fields) 
開發者ID:Fluent-networks,項目名稱:floranet,代碼行數:19,代碼來源:azure_iot_https.py

示例9: get

# 需要導入模塊: import flask_restful [as 別名]
# 或者: from flask_restful import marshal [as 別名]
def get(self, dataToken):
        if (not self.auth_source.get_and_verify()):
            return make_response(jsonify({'message': 'Unauthorized access'}), 403)

        self.data_source.update_all_captchas()
        captcha = [
            captcha for captcha in self.data_source.captchas if captcha['dataToken'] == dataToken]
        if len(captcha) == 0:
            # return make_response(jsonify({'message': 'Unauthorized access'}), 403)
            abort(404)
        if not self.validate_user(captcha[0]):
            # return make_response(jsonify({'message': 'Unauthorized access'}), 403)
            abort(404)

        # Get the results
        results = self.data_source.get_results(captcha[0])
        return {'results': marshal(results, self.data_source.results_fields)} 
開發者ID:FSecureLABS,項目名稱:captcha22,代碼行數:19,代碼來源:server.py

示例10: post

# 需要導入模塊: import flask_restful [as 別名]
# 或者: from flask_restful import marshal [as 別名]
def post(self):
        if (not self.auth_source.get_and_verify()):
            return make_response(jsonify({'message': 'Unauthorized access'}), 403)

        args = self.reqparse.parse_args()

        captcha = [
            captcha for captcha in self.data_source.captchas if captcha['dataToken'] == args['dataToken']]
        if len(captcha) == 0:
            abort(404)
        if not self.validate_user(captcha[0]):
            abort(403)

        # We should now find and modify the file
        self.data_source.change_model_status(captcha[0], args['active'])
        return {'captcha': marshal(captcha[0], self.data_source.captcha_fields)} 
開發者ID:FSecureLABS,項目名稱:captcha22,代碼行數:18,代碼來源:server.py

示例11: __init__

# 需要導入模塊: import flask_restful [as 別名]
# 或者: from flask_restful import marshal [as 別名]
def __init__(self, response_class):
        """
        :param response_class: response class to marshal result with.
         class must have a "resource_fields" class variable
        """
        if hasattr(response_class, 'response_fields'):
            self._fields = response_class.response_fields
        elif hasattr(response_class, 'resource_fields'):
            self._fields = response_class.resource_fields
        else:
            raise RuntimeError(
                'Response class {0} does not contain a "resource_fields" '
                'class variable'.format(type(response_class)))

        self.response_class = response_class 
開發者ID:cloudify-cosmo,項目名稱:cloudify-manager,代碼行數:17,代碼來源:rest_decorators.py

示例12: __call__

# 需要導入模塊: import flask_restful [as 別名]
# 或者: from flask_restful import marshal [as 別名]
def __call__(self, f):
        @wraps(f)
        def wrapper(*args, **kwargs):
            if hasattr(request, '__skip_marshalling'):
                return f(*args, **kwargs)

            fields_to_include = self._get_fields_to_include()
            if self._is_include_parameter_in_request():
                # only pushing "_include" into kwargs when the request
                # contained this parameter, to keep things cleaner (identical
                # behavior for passing "_include" which contains all fields)
                kwargs['_include'] = list(fields_to_include.keys())

            response = f(*args, **kwargs)

            def wrap_list_items(response):
                wrapped_items = self.wrap_with_response_object(response.items)
                response.items = marshal(wrapped_items, fields_to_include)
                return response

            if isinstance(response, ListResponse):
                return marshal(wrap_list_items(response),
                               ListResponse.resource_fields)
            # SQLAlchemy returns a class that subtypes tuple, but acts
            # differently (it's taken care of in `wrap_with_response_object`)
            if isinstance(response, tuple) and \
                    not isinstance(response, sql_alchemy_collection):
                data, code, headers = unpack(response)
                if isinstance(data, ListResponse):
                    data = wrap_list_items(data)
                    return (marshal(data, ListResponse.resource_fields),
                            code,
                            headers)
                else:
                    data = self.wrap_with_response_object(data)
                    return marshal(data, fields_to_include), code, headers
            else:
                response = self.wrap_with_response_object(response)
                return marshal(response, fields_to_include)

        return wrapper 
開發者ID:cloudify-cosmo,項目名稱:cloudify-manager,代碼行數:43,代碼來源:rest_decorators.py

示例13: marshal_events

# 需要導入模塊: import flask_restful [as 別名]
# 或者: from flask_restful import marshal [as 別名]
def marshal_events(func):
    """
    Decorator for marshalling raw event responses
    """
    @wraps(func)
    def marshal_response(*args, **kwargs):
        return marshal(func(*args, **kwargs), ListResponse.resource_fields)
    return marshal_response 
開發者ID:cloudify-cosmo,項目名稱:cloudify-manager,代碼行數:10,代碼來源:rest_decorators.py

示例14: get

# 需要導入模塊: import flask_restful [as 別名]
# 或者: from flask_restful import marshal [as 別名]
def get(self) -> Iterable[Union[Mapping, int, None]]:
        """
        API to fetch all the existing tags with usage.
        """
        tag_usages = self.client.get_tags()
        return marshal({'tag_usages': tag_usages}, tag_usage_fields), HTTPStatus.OK 
開發者ID:lyft,項目名稱:amundsenmetadatalibrary,代碼行數:8,代碼來源:tag.py

示例15: to_json

# 需要導入模塊: import flask_restful [as 別名]
# 或者: from flask_restful import marshal [as 別名]
def to_json(self,
                model,
                model_fields=None,
                meta=None,
                status_code=HTTP_STATUS_CODE_OK):
        """Create json response from a database models.

        Args:
            model: Instance of a timesketch database model
            model_fields: Dictionary describing the resulting schema
            meta: Dictionary holding any metadata for the result
            status_code: Integer used as status_code in the response

        Returns:
            Response in json format (instance of flask.wrappers.Response)
        """
        if not meta:
            meta = dict()

        schema = {'meta': meta, 'objects': []}

        if model:
            if not model_fields:
                try:
                    model_fields = self.fields_registry[model.__tablename__]
                except AttributeError:
                    model_fields = self.fields_registry[model[0].__tablename__]
            schema['objects'] = [marshal(model, model_fields)]

        response = jsonify(schema)
        response.status_code = status_code
        return response 
開發者ID:google,項目名稱:timesketch,代碼行數:34,代碼來源:__init__.py


注:本文中的flask_restful.marshal方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。