本文整理汇总了Python中flask.json方法的典型用法代码示例。如果您正苦于以下问题:Python flask.json方法的具体用法?Python flask.json怎么用?Python flask.json使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类flask
的用法示例。
在下文中一共展示了flask.json方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: open
# 需要导入模块: import flask [as 别名]
# 或者: from flask import json [as 别名]
def open(self, path, json=None, **kwargs):
""" Open an URL, optionally posting JSON data
:param path: URI to request
:type path: str
:param json: JSON data to post
:param method: HTTP Method to use. 'POST' by default if data is provided
:param data: Custom data to post, if required
"""
# Prepare request
if json:
kwargs['data'] = flask.json.dumps(json)
kwargs['content_type'] = 'application/json'
kwargs.setdefault('method', 'POST')
# Request
rv = super(FlaskJsonClient, self).open(path, **kwargs)
':type rv: flask.Response'
# Response: JSON?
if rv.mimetype == 'application/json':
response = flask.json.loads(rv.get_data())
return JsonResponse(response, rv.status_code, rv.headers)
return rv
示例2: dump_result
# 需要导入模块: import flask [as 别名]
# 或者: from flask import json [as 别名]
def dump_result(project, _format):
resultdb = app.config['resultdb']
# force update project list
resultdb.get(project, 'any')
if project not in resultdb.projects:
return "no such project.", 404
offset = int(request.args.get('offset', 0)) or None
limit = int(request.args.get('limit', 0)) or None
results = resultdb.select(project, offset=offset, limit=limit)
if _format == 'json':
valid = request.args.get('style', 'rows') == 'full'
return Response(result_dump.dump_as_json(results, valid),
mimetype='application/json')
elif _format == 'txt':
return Response(result_dump.dump_as_txt(results),
mimetype='text/plain')
elif _format == 'csv':
return Response(result_dump.dump_as_csv(results),
mimetype='text/csv')
示例3: create_developer
# 需要导入模块: import flask [as 别名]
# 或者: from flask import json [as 别名]
def create_developer():
if not request.json or not 'platform_id' in request.json:
abort(400)
developer = Developer.query.filter_by(platform_id=request.json['platform_id'],
platform=request.json['platform']).first()
if 'desc' in request.json:
desc = request.json['desc']
else:
desc = ''
if developer is None:
dev_key = generate_dev_key()
developer = Developer(dev_key=dev_key,
platform=request.json['platform'],
platform_id=request.json['platform_id'],
username=request.json['dev_name'],
email=request.json['email'],
description=desc)
developer.insert_to_db()
return jsonify({'dev_key': developer.dev_key}), 201
else:
return jsonify({'created': False}), 304
# 通过 platform 和 platform_id 来获取用户信息
示例4: modify_developer
# 需要导入模块: import flask [as 别名]
# 或者: from flask import json [as 别名]
def modify_developer(dev_key):
developer = Developer.query.filter_by(dev_key=dev_key).first()
if developer is None:
abort(404)
if 'name' in request.json:
developer.username = request.json['name']
if 'desc' in request.json:
developer.description = request.json['desc']
if 'avatar' in request.json:
developer.avatar = request.json['avatar']
if 'email' in request.json:
developer.email = request.json['email']
db.session.add(developer)
try:
db.session.commit()
return jsonify({'modified': True}), 200
except:
db.session.rollback()
abort(500)
# 在dev_key 下创建一个 channel
示例5: create_channel
# 需要导入模块: import flask [as 别名]
# 或者: from flask import json [as 别名]
def create_channel(dev_key):
if not request.json or not 'channel' in request.json:
abort(400)
developer = Developer.query.filter_by(dev_key=dev_key).first()
if developer is None:
abort(404)
channels = developer.channels
if channels is None:
create_channel_and_insert2db(developer, request.json['channel'])
else:
for channel in channels:
if channel.channel == request.json['channel']:
print("existed")
return jsonify({'created': False, 'existed': True}), 304
create_channel_and_insert2db(developer, request.json['channel'])
return jsonify({'created': True, 'existed': False}), 201
# 获得 dev_key 下的所有 channel
示例6: modificate_integration
# 需要导入模块: import flask [as 别名]
# 或者: from flask import json [as 别名]
def modificate_integration(dev_key, integration_id):
if not request.json or not 'channel' in request.json:
abort(400)
developer = get_developer_with_devkey(dev_key)
integration = Integration.query.filter_by(developer_id=developer.id, integration_id=integration_id).first()
if integration is None:
abort(400)
integration.channel.channel = request.json['channel']
if 'name' in request.json:
integration.name = request.json['name']
if 'description' in request.json:
integration.description = request.json['description']
if 'icon' in request.json:
integration.icon = request.json['icon']
db.session.add(integration)
try:
db.session.commit()
except:
db.session.rollback()
abort(500)
return jsonify({'modification': True}), 200
# 保存 github 集成,将所选的仓库与之前的仓库比较,新增则生成 webhook, 否则去掉之前的 webhook
示例7: on_event
# 需要导入模块: import flask [as 别名]
# 或者: from flask import json [as 别名]
def on_event(self, message, handler, namespace=None):
"""Register a SocketIO event handler.
``on_event`` is the non-decorator version of ``'on'``.
Example::
def on_foo_event(json):
print('received json: ' + str(json))
socketio.on_event('my event', on_foo_event, namespace='/chat')
:param message: The name of the event. This is normally a user defined
string, but a few event names are already defined. Use
``'message'`` to define a handler that takes a string
payload, ``'json'`` to define a handler that takes a
JSON blob payload, ``'connect'`` or ``'disconnect'``
to create handlers for connection and disconnection
events.
:param handler: The function that handles the event.
:param namespace: The namespace on which the handler is to be
registered. Defaults to the global namespace.
"""
self.on(message, namespace=namespace)(handler)
示例8: dispatch_request
# 需要导入模块: import flask [as 别名]
# 或者: from flask import json [as 别名]
def dispatch_request(self, *args, **kwargs):
response = super().dispatch_request(*args, **kwargs)
if isinstance(response, flask.Response):
return response
try:
response = self.prepare_response(response)
except Exception as exc:
LOG.error("Cannot build model response: %s", exc)
raise exceptions.UnknownReturnValueError from exc
try:
response = flask.json.jsonify(response)
except Exception as exc:
LOG.error("Cannot convert %s to JSON: %s", response, exc)
raise exceptions.CannotConvertResultToJSONError() from exc
return response
示例9: result
# 需要导入模块: import flask [as 别名]
# 或者: from flask import json [as 别名]
def result():
resultdb = app.config['resultdb']
project = request.args.get('project')
offset = int(request.args.get('offset', 0))
limit = int(request.args.get('limit', 20))
count = resultdb.count(project)
results = list(resultdb.select(project, offset=offset, limit=limit))
return render_template(
"result.html", count=count, results=results,
result_formater=result_dump.result_formater,
project=project, offset=offset, limit=limit, json=json
)
示例10: commands_submit
# 需要导入模块: import flask [as 别名]
# 或者: from flask import json [as 别名]
def commands_submit(session):
data = flask.json.loads(flask.request.values['data'])
# Server-side sanity checking
for command, response_data in data.items():
if not isinstance(command, str):
raise ValueError("Key is not a string")
if command == '':
raise ValueError("Command is blank")
if not isinstance(response_data, dict):
raise ValueError("Response data is not a dict")
if set(response_data.keys()) != set(('response', 'access')):
raise ValueError("Incorrect keys for response_data")
if not isinstance(response_data['response'], (tuple, list)):
response_data['response'] = [response_data['response']]
for response in response_data['response']:
if not isinstance(response, str):
raise ValueError("Value is not a string or list of strings")
if response == '':
raise ValueError("Response is blank")
if not utils.check_length(response):
raise ValueError("Response is too long")
if len(response_data['response']) == 1:
response_data['response'] = response_data['response'][0]
if response_data['access'] not in ('any', 'sub', 'mod'):
raise ValueError("Invalid access level")
await common.rpc.bot.static.modify_commands(data)
history.store('responses', session['user']['id'], data)
return flask.json.jsonify(success='OK', csrf_token=server.app.csrf_token())
示例11: spam_submit
# 需要导入模块: import flask [as 别名]
# 或者: from flask import json [as 别名]
def spam_submit(session):
link_spam = "link_spam" in flask.request.values
data = flask.json.loads(flask.request.values['data'])
# Validation checks
error = verify_rules(data)
if error:
return flask.json.jsonify(error=error, csrf_token=server.app.csrf_token())
if link_spam:
await common.rpc.bot.link_spam.modify_link_spam_rules(data)
else:
await common.rpc.bot.spam.modify_spam_rules(data)
history.store("link_spam" if link_spam else "spam", session['user']['id'], data)
return flask.json.jsonify(success='OK', csrf_token=server.app.csrf_token())
示例12: spam_redirects
# 需要导入模块: import flask [as 别名]
# 或者: from flask import json [as 别名]
def spam_redirects(session):
redirects = await common.url.canonical_url(flask.request.values["url"].strip())
return flask.json.jsonify(redirects=redirects, csrf_token=server.app.csrf_token())
示例13: patch_flask
# 需要导入模块: import flask [as 别名]
# 或者: from flask import json [as 别名]
def patch_flask():
flask.json.jsonify = jsonify
flask.jsonify = flask.json.jsonify
Flask.json_encoder = JSONEncoder
示例14: json
# 需要导入模块: import flask [as 别名]
# 或者: from flask import json [as 别名]
def json(func):
"""
Decorator to render as JSON
:param func:
:return:
"""
if inspect.isclass(func):
apply_function_to_members(func, json)
return func
else:
@functools.wraps(func)
def decorated_view(*args, **kwargs):
data = func(*args, **kwargs)
return _build_response(data, jsonify)
return decorated_view
示例15: callapi
# 需要导入模块: import flask [as 别名]
# 或者: from flask import json [as 别名]
def callapi(url, method='post', payload=None, headers=None, auth=None, check=True):
"""
Simple wrapper around `requests.post`, with excessive logging.
Returns a Flask-friendly tuple on success or failure.
Logs and re-raises any exceptions.
"""
if not headers:
headers = {'Content-type': 'application/json'}
try:
logging.info("URL=%s" % url)
logging.info("Auth=%s" % str(auth))
logging.info("Headers=%s" % headers)
logging.info("Body=%s" % payload)
logging.info("Check=%s" % check)
if (auth is not None):
r = requests.request(method, url, auth=auth, headers=headers, data=payload, verify=bool(strtobool(str(check))))
else:
r = requests.request(method, url, headers=headers, data=payload, verify=check)
if r.status_code >= 200 and r.status_code < 300:
if (payload is None):
return r.text
else:
return ("OK", r.status_code, None)
except:
logging.exception("Can't create new payload. Check code and try again.")
raise
return ("%s" % r.text, r.status_code, None)