Python flask_restful.marshal() Examples
The following are 29
code examples of flask_restful.marshal().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
flask_restful
, or try the search function
.
Example #1
Source File: server.py From captcha22 with MIT License | 6 votes |
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)}
Example #2
Source File: application.py From floranet with MIT License | 6 votes |
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))
Example #3
Source File: azure_iot_mqtt.py From floranet with MIT License | 6 votes |
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)
Example #4
Source File: appproperty.py From floranet with MIT License | 6 votes |
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))
Example #5
Source File: helpers.py From github-stats with MIT License | 6 votes |
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), })
Example #6
Source File: azure_iot_https.py From floranet with MIT License | 6 votes |
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)
Example #7
Source File: appinterface.py From floranet with MIT License | 6 votes |
def get(self): """Method to get all application interfaces""" try: interfaces = interfaceManager.getAllInterfaces() if interfaces is None: returnValue({}) marshal_fields = { 'type': fields.String(attribute='__class__.__name__'), 'id': fields.Integer(attribute='appinterface.id'), 'name': fields.String } data = {} for i,interface in enumerate(interfaces): data[i] = marshal(interface, marshal_fields) returnValue(data) yield except TimeoutError: log.error("REST API timeout retrieving application interfaces")
Example #8
Source File: appinterface.py From floranet with MIT License | 6 votes |
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)
Example #9
Source File: resource.py From flask-restful-api-template with MIT License | 6 votes |
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)
Example #10
Source File: resource.py From flask-restful-api-template with MIT License | 6 votes |
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)
Example #11
Source File: server.py From captcha22 with MIT License | 6 votes |
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)}
Example #12
Source File: server.py From captcha22 with MIT License | 5 votes |
def get(self): if (not self.auth_source.get_and_verify()): return make_response(jsonify({'message': 'Unauthorized access'}), 403) # Build the captchas for the user user_captchas = [] self.data_source.update_all_captchas() username = self.auth_source.get_username() for captcha in self.data_source.captchas: if captcha['username'] == username: user_captchas.append(captcha) return {'captchas': [marshal(captcha, self.data_source.captcha_fields) for captcha in user_captchas]}
Example #13
Source File: appproperty.py From floranet with MIT License | 5 votes |
def get(self, appeui): """Method to handle application property GET requests Args: appeui (int): Application EUI port (int): Application property port """ try: app = yield Application.find(where=['appeui = ?', appeui], limit=1) # Return a 404 if not found. if app is None: abort(404, message={'error': "Application {} doesn't exist." .format(euiString(appeui))}) port = self.args['port'] p = yield AppProperty.find(where=['application_id = ? AND port = ?', app.id, port]) if p is None: abort(404, message={'error': "Application property doesn't exist."}) data = marshal(p, self.fields) returnValue(data) except TimeoutError: log.error("REST API timeout get request for application {appeui} " "property {port}", appeui=euiString(appeui), port=port)
Example #14
Source File: file_text_store.py From floranet with MIT License | 5 votes |
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, 'file': fields.String, 'started': fields.Boolean } return marshal(self, marshal_fields)
Example #15
Source File: server.py From captcha22 with MIT License | 5 votes |
def post(self): if (not self.auth_source.get_and_verify()): return make_response(jsonify({'message': 'Unauthorized access'}), 403) args = self.reqparse.parse_args() buf = request.files['captcha'].read() stuff = buf.decode('utf-8') posted_data = json.loads(stuff) posted_file = request.files['document'].read() count = self.build_filename(posted_data['title'], self.auth_source.get_username()) # auth.username()) filename = self.data_source.FILE_DROP_LOCATION + self.auth_source.get_username().replace(" ", "") + "_" + posted_data['title'].replace(" ", "") + "_" + str(count) + ".zip" tempFile = open(filename, 'wb') tempFile.write(posted_file) tempFile.close() uid = str(uuid.uuid1()) id_str = self.data_source.captchas[-1]['id'] + \ 1 if len(self.data_source.captchas) > 0 else 1 captcha = { 'id': id_str, 'title': posted_data['title'], 'username': self.auth_source.get_username(), # auth.username(), 'modelNumber': count, 'dataToken': uid, 'busyTraining': False, 'hasModel': False, 'modelActive': False } self.data_source.captchas.append(captcha) return {'captcha': marshal(captcha, self.data_source.captcha_fields)}, 201
Example #16
Source File: server.py From captcha22 with MIT License | 5 votes |
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: abort(404) if not self.validate_user(captcha[0]): abort(403) # Get the update update = self.data_source.get_process_update(captcha[0]) training_progress = { 'id': captcha[0]['id'], 'title': captcha[0]['title'], 'username': captcha[0]['username'], 'modelNumber': captcha[0]['modelNumber'], 'dataToken': captcha[0]['dataToken'], 'busyTraining': captcha[0]['busyTraining'], 'hasModel': captcha[0]['hasModel'], 'modelActive': captcha[0]['modelActive'], 'currentTrainingLevel': update['currentTrainingLevel'], 'last_step': update['last_step'], 'loss': update['loss'], 'perplexity': update['perplexity'], 'checkpoint': update['checkpoint'] } return {'update': marshal(training_progress, self.data_source.training_progress_fields)}
Example #17
Source File: server.py From captcha22 with MIT License | 5 votes |
def get(self, id): 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['id'] == id] if len(captcha) == 0: abort(404) if not self.validate_user(captcha[0]): abort(403) return {'captcha': marshal(captcha[0], self.data_source.captcha_fields)}
Example #18
Source File: server.py From captcha22 with MIT License | 5 votes |
def put(self, id): if (not self.auth_source.get_and_verify()): return make_response(jsonify({'message': 'Unauthorized access'}), 403) captcha = [ captcha for captcha in self.data_source.captchas if captcha['id'] == id] if len(captcha) == 0: abort(404) if not self.validate_user(captcha[0]): abort(403) captcha = captcha[0] args = self.reqparse.parse_args() for k, v in args.items(): if v is not None: captcha[k] = v return {'captcha': marshal(captcha, self.data_source.captcha_fields)}
Example #19
Source File: reflector.py From floranet with MIT License | 5 votes |
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, 'started': fields.Boolean } return marshal(self, marshal_fields)
Example #20
Source File: application.py From floranet with MIT License | 5 votes |
def getProperties(self, app): """Get and marshal the application properties""" # Get the properties props = yield app.properties.get() # Marshal data = {} for i,p in enumerate(props): data[i] = marshal(p, self.pfields) returnValue(data)
Example #21
Source File: device.py From floranet with MIT License | 5 votes |
def get(self): """Method to get all devices""" try: devices = yield Device.all() if devices is None: returnValue({}) data = {} for i,d in enumerate(devices): data[i] = marshal(d, self.fields) returnValue(data) except TimeoutError: # Exception returns 500 to client log.error("REST API timeout retrieving all devices")
Example #22
Source File: gateway.py From floranet with MIT License | 5 votes |
def get(self): """Method to get all gateways""" try: gateways = yield Gateway.all() if gateways is None: returnValue({}) data = {} for i,g in enumerate(gateways): data[i] = marshal(g, self.fields) returnValue(data) except TimeoutError: # Exception returns 500 to client log.error("REST API timeout retrieving all gateways")
Example #23
Source File: gateway.py From floranet with MIT License | 5 votes |
def get(self, host): """Method to handle gateway GET requests""" try: g = yield Gateway.find(where=['host = ?', host], limit=1) # Return a 404 if not found. if g is None: abort(404, message={'error': "Gateway {} doesn't exist.".format(host)}) returnValue(marshal(g, self.fields)) except TimeoutError: log.error("REST API timeout retrieving gateway {host}", host=host)
Example #24
Source File: system.py From floranet with MIT License | 5 votes |
def get(self): """Method to handle system configuration GET requests""" try: config = yield Config.find(limit=1) # Return a 404 if not found. if config is None: abort(404, message={'error': "Could not get the system configuration"}) returnValue(marshal(config, self.fields)) except TimeoutError: log.error("REST API timeout retrieving application {appeui}", appeui=euiString(appeui))
Example #25
Source File: __init__.py From timesketch with Apache License 2.0 | 5 votes |
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
Example #26
Source File: tag.py From amundsenmetadatalibrary with Apache License 2.0 | 5 votes |
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
Example #27
Source File: rest_decorators.py From cloudify-manager with Apache License 2.0 | 5 votes |
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
Example #28
Source File: rest_decorators.py From cloudify-manager with Apache License 2.0 | 5 votes |
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
Example #29
Source File: rest_decorators.py From cloudify-manager with Apache License 2.0 | 5 votes |
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