本文整理汇总了Python中bottle.request.json方法的典型用法代码示例。如果您正苦于以下问题:Python request.json方法的具体用法?Python request.json怎么用?Python request.json使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类bottle.request
的用法示例。
在下文中一共展示了request.json方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: _new_element
# 需要导入模块: from bottle import request [as 别名]
# 或者: from bottle.request import json [as 别名]
def _new_element(self, element_id=None):
body = request.json
root_id = body.get('root_id')
parent_id = body.get('parent_id')
new_root = body.get('new_root')
obj = body.get('obj')
params = body.get('params') or {}
assert obj
assert not (root_id and parent_id)
assert not (root_id and new_root)
if parent_id:
parent = self._registry.elements[parent_id]
elif new_root:
parent = self._registry.roots['root']._new_root()
else:
parent = self._registry.roots[root_id or 'root']
element = parent.new(obj, id=element_id, **params)
return self._get_element(element.id)
示例2: jsonify
# 需要导入模块: from bottle import request [as 别名]
# 或者: from bottle.request import json [as 别名]
def jsonify(fn):
@ft.wraps(fn)
def inner(*a, **kw):
response.content_type = 'application/json'
try:
data = fn(*a, **kw)
except HTTPError as e:
response.status = e.status_code
data = {'errors': [e.body]}
except schema.Error as e:
response.status = 400
data = {'errors': e.errors, 'schema': e.schema}
except Exception as e:
log.exception(e)
response.status = 500
data = {'errors': [str(e)]}
return json.dumps(data or {}, indent=2, ensure_ascii=False)
return inner
示例3: login
# 需要导入模块: from bottle import request [as 别名]
# 或者: from bottle.request import json [as 别名]
def login():
data = schema.validate(request.json, {
'type': 'object',
'properties': {
'username': {'type': 'string'},
'password': {'type': 'string'},
'timezone': {'type': 'string', 'enum': all_timezones},
'theme': {'type': 'string', 'default': 'base'}
},
'required': ['username', 'password', 'timezone']
})
try:
local.connect(data['username'], data['password'])
except imap.Error as e:
response.status = 400
return {'errors': ['Authentication failed.'], 'details': str(e)}
del data['password']
request.session.update(data)
return {}
示例4: run
# 需要导入模块: from bottle import request [as 别名]
# 或者: from bottle.request import json [as 别名]
def run(host='127.0.0.1', port=10086):
from bottle import post, run, request, response
@post('/puppet')
def serve():
'''Puppet Web Trading Interface'''
task = request.json
if task:
try:
return getattr(acc, task.pop('action'))(**task)
except Exception as e:
response.bind(status=502)
return {'puppet': str(e)}
return {'puppet': '仅支持json格式'}
print('Puppet version:', __version__)
acc = Account()
run(host=host, port=port)
示例5: get_config
# 需要导入模块: from bottle import request [as 别名]
# 或者: from bottle.request import json [as 别名]
def get_config(self, screen):
"""Method to retrieve config file for screen."""
# Define the path to the config file
conffile = os.path.join(self.folder, "screens", screen, "conf.json")
if os.path.isfile(conffile):
# Get the config file
with open(conffile, "r") as cfg_file:
# Load the JSON object
conf = json.load(cfg_file)
# Return the "params" section
result = self.api_success(conf.get("params", dict()))
else:
# Something's gone wrong
result = self.api_error("No screen called: {}".format(screen))
# Provide the response
return json.dumps(result)
示例6: create_job
# 需要导入模块: from bottle import request [as 别名]
# 或者: from bottle.request import json [as 别名]
def create_job(self, commit_id, clone_url, build_id, project_id, github_private_repo, branch, env=None, fork=False):
git_repo = {
"commit": commit_id,
"clone_url": clone_url,
"github_private_repo": github_private_repo,
"branch": branch,
"fork": fork
}
self.execute('''
INSERT INTO job (id, state, build_id, type,
name, project_id, build_only,
dockerfile, cpu, memory, repo, env_var, cluster_name)
VALUES (gen_random_uuid(), 'queued', %s, 'create_job_matrix',
'Create Jobs', %s, false, '', 1, 1024, %s, %s, 'master')
''', [build_id, project_id, json.dumps(git_repo), env], fetch=False)
示例7: grafana_time_stats
# 需要导入模块: from bottle import request [as 别名]
# 或者: from bottle.request import json [as 别名]
def grafana_time_stats(self, req):
req = request.json or {}
from_var = req['range']['from'][:10]
to_var = req['range']['to'][:10]
from_dt = datetime.strptime(from_var, '%Y-%m-%d')
to_dt = datetime.strptime(to_var, '%Y-%m-%d')
td = timedelta(days=1)
dates = []
timestamps = []
while from_dt <= to_dt:
dates.append(from_dt.date().isoformat())
timestamps.append(from_dt.timestamp() * 1000)
from_dt += td
resp = [self.load_series(target, dates, timestamps) for target in req['targets']]
return resp
示例8: change_indihub_agent_mode
# 需要导入模块: from bottle import request [as 别名]
# 或者: from bottle.request import json [as 别名]
def change_indihub_agent_mode(mode):
"""Change INDIHUB Agent mode with a current INDI-profile"""
if active_profile == "" or not indi_server.is_running():
response.content_type = 'application/json'
response.status = 500
return json.dumps({'message': 'INDI-server is not running. You need to run INDI-server first.'})
indihub_agent.stop()
if mode == 'off':
return
indihub_agent.start(active_profile, mode)
###############################################################################
# Startup standalone server
###############################################################################
示例9: job_create
# 需要导入模块: from bottle import request [as 别名]
# 或者: from bottle.request import json [as 别名]
def job_create():
_logger.debug("job_create")
try:
job_data = request.json
except ValueError:
response.status = defines.HTTP_STATUS_BAD_REQUEST
return dict(status=defines.ERROR, reason='No valid JSON object.')
if job_data is None:
response.status = defines.HTTP_STATUS_BAD_REQUEST
return dict(status=defines.ERROR, reason='No script provided.')
try:
job_id = get_job_engine().submit_job(job_data)
return dict(status=defines.SUCCESS, data=job_id)
except (ScriptSyntaxError, SyntaxError) as ex:
response.status = defines.HTTP_STATUS_BAD_REQUEST
return dict(status=defines.ERROR, reason=str(ex))
示例10: index
# 需要导入模块: from bottle import request [as 别名]
# 或者: from bottle.request import json [as 别名]
def index():
'''return a json version of whois for an ip address'''
if request.body:
arequest = request.body.read()
request.body.close()
# valid json?
try:
requestDict = json.loads(arequest)
except ValueError:
response.status = 500
if 'ipaddress' in requestDict and isIPv4(requestDict['ipaddress']):
response.content_type = "application/json"
response.body = getWhois(requestDict['ipaddress'])
else:
response.status = 500
sendMessgeToPlugins(request, response, 'ipwhois')
return response
示例11: sync_alert_schedules
# 需要导入模块: from bottle import request [as 别名]
# 或者: from bottle.request import json [as 别名]
def sync_alert_schedules():
'''an endpoint to return alerts schedules'''
if not request.body:
response.status = 503
return response
alert_schedules = json.loads(request.body.read())
request.body.close()
response.content_type = "application/json"
mongoclient = MongoClient(options.mongohost, options.mongoport)
schedulers_db = mongoclient.meteor['alertschedules'].with_options(codec_options=CodecOptions(tz_aware=True))
results = schedulers_db.find()
for result in results:
if result['name'] in alert_schedules:
new_sched = alert_schedules[result['name']]
result['total_run_count'] = new_sched['total_run_count']
result['last_run_at'] = new_sched['last_run_at']
if result['last_run_at']:
result['last_run_at'] = toUTC(result['last_run_at'])
logger.debug("Inserting schedule for {0} into mongodb".format(result['name']))
schedulers_db.save(result)
response.status = 200
return response
示例12: update_alert_schedules
# 需要导入模块: from bottle import request [as 别名]
# 或者: from bottle.request import json [as 别名]
def update_alert_schedules():
'''an endpoint to return alerts schedules'''
if not request.body:
response.status = 503
return response
alert_schedules = json.loads(request.body.read())
request.body.close()
response.content_type = "application/json"
mongoclient = MongoClient(options.mongohost, options.mongoport)
schedulers_db = mongoclient.meteor['alertschedules'].with_options(codec_options=CodecOptions(tz_aware=True))
schedulers_db.remove()
for alert_name, alert_schedule in alert_schedules.items():
if alert_schedule['last_run_at']:
alert_schedule['last_run_at'] = toUTC(alert_schedule['last_run_at'])
logger.debug("Inserting schedule for {0} into mongodb".format(alert_name))
schedulers_db.insert(alert_schedule)
response.status = 200
return response
示例13: verisSummary
# 需要导入模块: from bottle import request [as 别名]
# 或者: from bottle.request import json [as 别名]
def verisSummary(verisRegex=None):
try:
# aggregate the veris tags from the incidents collection and return as json
client = MongoClient(options.mongohost, options.mongoport)
# use meteor db
incidents = client.meteor['incidents']
iveris = incidents.aggregate([
{"$match": {"tags": {"$exists": True}}},
{"$unwind": "$tags"},
{"$match": {"tags": {"$regex": ''}}},
{"$project": {
"dateOpened": 1,
"tags": 1,
"phase": 1,
"_id": 0
}}
])
if iveris:
return json.dumps(list(iveris), default=json_util.default)
else:
return json.dumps(list())
except Exception as e:
logger.error('Exception while aggregating veris summary: {0}\n'.format(e))
示例14: _callback_wrapper
# 需要导入模块: from bottle import request [as 别名]
# 或者: from bottle.request import json [as 别名]
def _callback_wrapper(self, callback):
def wrapper(*args, **kwargs):
request.content_type = 'application/json'
result = callback(*args, **kwargs)
return self._encoder.to_json(result)
return wrapper
示例15: _update_data
# 需要导入模块: from bottle import request [as 别名]
# 或者: from bottle.request import json [as 别名]
def _update_data(self, element_id):
element = self._registry.elements[element_id]
body = request.json
data = body.get('data')
assert data
element.update_data(data)
return {'id': element_id, 'status': 'success'}