本文整理汇总了Python中utils.jsonify函数的典型用法代码示例。如果您正苦于以下问题:Python jsonify函数的具体用法?Python jsonify怎么用?Python jsonify使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了jsonify函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: get_receipts
def get_receipts():
receipts = mongo.db.receipts
if request.method == 'POST':
'''Create new receipt'''
receipt = request.json
receipt['user'] = request.authorization['username']
# TODO Validate input, add date if missing etc
db_operation = receipts.insert(receipt)
ac_add_new_words(receipt)
return jsonify({'savedReceipt': receipt, 'dbOperation': db_operation})
# 201 Created
# 403 Forbidden
if request.method == 'GET':
''' List all receipts for request user.
Pagination is set by limit and offset variables.
'''
limit = request.args.get('limit') or 1000
offset = request.args.get('offset') or 0
receipts = mongo.db.receipts
user_receipts_cursor = receipts.find(
{"user": request.authorization['username']})
user_receipts = []
for receipt in user_receipts_cursor:
user_receipts.append(receipt)
# Sort by date
user_receipts.sort(key=lambda x: x['date'])
return jsonify({'receipts':
user_receipts[offset:offset+limit],
'pagination': {
'total': len(user_receipts),
'from': offset,
'to': offset + limit}})
示例2: on_failed
def on_failed(self, host, results, ignore_errors=False):
results2 = results.copy()
results2.pop('invocation', None)
item = results2.get('item', None)
parsed = results2.get('parsed', True)
module_msg = ''
if not parsed:
module_msg = results2.pop('msg', None)
stderr = results2.pop('stderr', None)
stdout = results2.pop('stdout', None)
returned_msg = results2.pop('msg', None)
if item:
msg = "failed: [%s] => (item=%s) => %s" % (host, item, utils.jsonify(results2))
else:
msg = "failed: [%s] => %s" % (host, utils.jsonify(results2))
print stringc(msg, 'red')
if stderr:
print stringc("stderr: %s" % stderr, 'red')
if stdout:
print stringc("stdout: %s" % stdout, 'red')
if returned_msg:
print stringc("msg: %s" % returned_msg, 'red')
if not parsed and module_msg:
print stringc("invalid output was: %s" % module_msg, 'red')
if ignore_errors:
print stringc("...ignoring", 'cyan')
super(PlaybookRunnerCallbacks, self).on_failed(host, results, ignore_errors=ignore_errors)
示例3: on_ok
def on_ok(self, host, host_result):
item = host_result.get('item', None)
host_result2 = host_result.copy()
host_result2.pop('invocation', None)
verbose_always = host_result2.pop('verbose_always', None)
changed = host_result.get('changed', False)
ok_or_changed = 'ok'
if changed:
ok_or_changed = 'changed'
# show verbose output for non-setup module results if --verbose is used
msg = ''
if (not self.verbose or host_result2.get("verbose_override",None) is not
None) and verbose_always is None:
if item:
msg = "%s: [%s] => (item=%s)" % (ok_or_changed, host, item)
else:
if 'ansible_job_id' not in host_result or 'finished' in host_result:
msg = "%s: [%s]" % (ok_or_changed, host)
else:
# verbose ...
if item:
msg = "%s: [%s] => (item=%s) => %s" % (ok_or_changed, host, item, utils.jsonify(host_result2))
else:
if 'ansible_job_id' not in host_result or 'finished' in host_result2:
msg = "%s: [%s] => %s" % (ok_or_changed, host, utils.jsonify(host_result2))
if msg != '':
if not changed:
display(msg, color='green', runner=self.runner)
else:
display(msg, color='yellow', runner=self.runner)
super(PlaybookRunnerCallbacks, self).on_ok(host, host_result)
示例4: on_failed
def on_failed(self, host, results, ignore_errors=False):
if self.runner.delegate_to:
host = '%s -> %s' % (host, self.runner.delegate_to)
results2 = results.copy()
results2.pop('invocation', None)
item = results2.get('item', None)
parsed = results2.get('parsed', True)
module_msg = ''
if not parsed:
module_msg = results2.pop('msg', None)
stderr = results2.pop('stderr', None)
stdout = results2.pop('stdout', None)
returned_msg = results2.pop('msg', None)
if item:
msg = "failed: [%s] => (item=%s) => %s" % (host, item, utils.jsonify(results2))
else:
msg = "failed: [%s] => %s" % (host, utils.jsonify(results2))
display(msg, color='red', runner=self.runner)
if stderr:
display("stderr: %s" % stderr, color='red', runner=self.runner)
if stdout:
display("stdout: %s" % stdout, color='red', runner=self.runner)
if returned_msg:
display("msg: %s" % returned_msg, color='red', runner=self.runner)
if not parsed and module_msg:
display(module_msg, color='red', runner=self.runner)
if ignore_errors:
display("...ignoring", color='cyan', runner=self.runner)
super(PlaybookRunnerCallbacks, self).on_failed(host, results, ignore_errors=ignore_errors)
示例5: regular_generic_msg
def regular_generic_msg(hostname, result, oneline, caption):
''' output on the result of a module run that is not command '''
if not oneline:
return "%s | %s >> %s\n" % (hostname, caption, utils.jsonify(result,format=True))
else:
return "%s | %s >> %s\n" % (hostname, caption, utils.jsonify(result))
示例6: receipt
def receipt(id):
receipts = mongo.db.receipts
if request.method == 'GET':
'''Get receipt specified by ID''' # TODO
return {'id': id, 'data': 'GET mocked'}
if request.method == 'PUT':
'''Update receipt data'''
receipt = request.get_json()
receipt['_id'] = ObjectId(receipt['_id'])
query = receipts.save(receipt)
# TODO A save receipt product names to autocomplete database
ac_add_new_words(receipt)
# add if not exists
return jsonify(receipt)
if request.method == 'DELETE':
'''Delete receipt'''
# TODO: other users receipts can now be removed by ID
try:
query = receipts.remove(ObjectId(id))
if query[u'n'] is 0:
abort(404, "Problem with Mongo remove function")
except:
abort(404)
return jsonify({"query": str(query)}), 200
示例7: on_failed
def on_failed(self, host, results, ignore_errors=False):
results2 = results.copy()
results2.pop("invocation", None)
item = results2.get("item", None)
parsed = results2.get("parsed", True)
module_msg = ""
if not parsed:
module_msg = results2.pop("msg", None)
stderr = results2.pop("stderr", None)
stdout = results2.pop("stdout", None)
returned_msg = results2.pop("msg", None)
if item:
msg = "failed: [%s] => (item=%s) => %s" % (host, item, utils.jsonify(results2))
else:
msg = "failed: [%s] => %s" % (host, utils.jsonify(results2))
display(msg, color="red", runner=self.runner)
if stderr:
display("stderr: %s" % stderr, color="red", runner=self.runner)
if stdout:
display("stdout: %s" % stdout, color="red", runner=self.runner)
if returned_msg:
display("msg: %s" % returned_msg, color="red", runner=self.runner)
if not parsed and module_msg:
display("invalid output was: %s" % module_msg, color="red", runner=self.runner)
if ignore_errors:
display("...ignoring", color="cyan", runner=self.runner)
super(PlaybookRunnerCallbacks, self).on_failed(host, results, ignore_errors=ignore_errors)
示例8: on_ok
def on_ok(self, host, host_result):
item = host_result.get("item", None)
host_result2 = host_result.copy()
host_result2.pop("invocation", None)
verbose_always = host_result2.pop("verbose_always", None)
changed = host_result.get("changed", False)
ok_or_changed = "ok"
if changed:
ok_or_changed = "changed"
# show verbose output for non-setup module results if --verbose is used
msg = ""
if (not self.verbose or host_result2.get("verbose_override", None) is not None) and verbose_always is None:
if item:
msg = "%s: [%s] => (item=%s)" % (ok_or_changed, host, item)
else:
if "ansible_job_id" not in host_result or "finished" in host_result:
msg = "%s: [%s]" % (ok_or_changed, host)
else:
# verbose ...
if item:
msg = "%s: [%s] => (item=%s) => %s" % (ok_or_changed, host, item, utils.jsonify(host_result2))
else:
if "ansible_job_id" not in host_result or "finished" in host_result2:
msg = "%s: [%s] => %s" % (ok_or_changed, host, utils.jsonify(host_result2))
if msg != "":
if not changed:
display(msg, color="green", runner=self.runner)
else:
display(msg, color="yellow", runner=self.runner)
super(PlaybookRunnerCallbacks, self).on_ok(host, host_result)
示例9: delete
def delete(self, lab_id=None):
try:
db.delete_admin_lab(self.application.db, lab_id)
utils.jsonify(self, True)
except Exception as e:
LOGGER.error(e)
self.set_status(400)
utils.jsonify(self, {'code': 'delete-failed', 'err': ''})
示例10: post
def post(self, lab_id=None):
postdata = json.loads(self.request.body)
lab, err = db.save_admin_lab(self.application.db, postdata)
if lab:
utils.jsonify(self, lab)
else:
self.set_status(400)
utils.jsonify(self, {'code': 'save-failed', 'err': err})
示例11: put
def put(self):
print 'Downloading File FooFile.txt [%d%%]\r'
putdata = json.loads(self.request.body)
print putdata
try:
db.edit_admin_lab(self.application.db, putdata)
utils.jsonify(self, True)
except Exception:
LOGGER.error('error', exc_info=True)
self.set_status(400)
utils.jsonify(self, {'code': 'delete-failed', 'err': ''})
示例12: api_module_field_status
def api_module_field_status(module_name, field_name):
if not packaging.is_installed(module_name):
abort(404)
try:
mod = use_module(module_name)
except RuntimeError as e:
app.logger.exception(e)
abort(404)
else:
# field exists ?
if not field_name in mod.fields_info:
abort(400)
# field is readable ?
f = mod.fields_info[field_name]
if 'readable' not in f or not f['readable']:
abort(403)
# field returns value ?
value = getattr(mod, f['name'])()
if value is None:
abort(404)
return jsonify(dict(zip(('time', 'value'), value)))
示例13: upload_receipt
def upload_receipt():
''' Receipt upload handler
Save image file to folder, process with OCR,
create receipt to DB and return data to client.
Time is passed as isoformatted time string in json,
eg. '2014-09-26T13:09:19.730800'
'''
image_file = request.files['file']
if image_file and allowed_file(image_file.filename):
filename = secure_filename(image_file.filename)
if not os.path.exists(app.config['UPLOAD_FOLDER']):
os.mkdir(app.config['UPLOAD_FOLDER'])
imagepath = os.path.join(app.root_path + '/' +
app.config['UPLOAD_FOLDER'], filename)
image_file.save(imagepath)
app.logger.debug("Upload OK, saved file " + imagepath)
ocr_readings = optical_character_recognition(imagepath)[2]
time_now = datetime.now()
ocr_readings['date'] = time_now.isoformat()
# TODO create a new receipt object to db and return it
return jsonify(ocr_readings)
示例14: api_uninstall_module
def api_uninstall_module(module_name):
try:
success = packaging.uninstall(module_name)
pass
except ValueError:
abort(403)
return jsonify({ 'success': success })
示例15: upload_receipt
def upload_receipt():
''' Receipt upload handler
Save image file to folder, process with OCR,
create receipt to DB and return data to client. '''
image_file = request.files['file']
if image_file and allowed_file(image_file.filename):
filename = secure_filename(image_file.filename)
if not os.path.exists(app.config['UPLOAD_FOLDER']):
os.mkdir(app.config['UPLOAD_FOLDER'])
imagepath = os.path.join(app.root_path + '/' +
app.config['UPLOAD_FOLDER'], filename)
image_file.save(imagepath)
app.logger.debug("Upload OK, saved file " + imagepath)
ocr_readings = dict({'credit_card': True, 'total_sum': 4.68,
'shop_name': "Mock Market", 'products':
[{'price': 1.59, 'name': 'Elonen ruisevas 540g'},
{'price': 0.75, 'name': 'Pirkka hanaani'},
{'price': 1.59, 'name': 'Elonen ruisevas 540g'},
{'price': 0.75, 'name': 'Pirkka hanaani'}],
'date': 2014-10-12})
# TODO create a new receipt object to db and return it
return jsonify(ocr_readings)