本文整理汇总了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),
})
示例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)
示例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)
示例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)
示例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))
示例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))
示例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)
示例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)
示例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)}
示例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)}
示例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
示例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
示例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
示例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
示例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