本文整理汇总了Python中bottle.request.body方法的典型用法代码示例。如果您正苦于以下问题:Python request.body方法的具体用法?Python request.body怎么用?Python request.body使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类bottle.request
的用法示例。
在下文中一共展示了request.body方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: get_token
# 需要导入模块: from bottle import request [as 别名]
# 或者: from bottle.request import body [as 别名]
def get_token():
# Get JSON Payload
try:
payload = json.load(request.body)
username = payload["username"]
password = payload["password"]
pwhash = _get_password_hash(password)
except:
response.status = 400
return dict({"message":"No valid JSON found in post body or mandatory fields missing."})
user_list = rc.scan_iter("USER:*")
for user in user_list:
user_record = json.loads(rc.get(user))
if user_record["username"] == username and user_record["hash"] == pwhash:
user_token = _issue_token(user=username, id=user[5:], expiry=token_expiry_seconds)
if 'raw' in request.query:
return(user_token)
else:
return(dict(token_type="bearer", access_token=user_token))
response.status = 401
return(dict(info="could not authorize user"))
# Test Auth Token
示例2: set_admin_password
# 需要导入模块: from bottle import request [as 别名]
# 或者: from bottle.request import body [as 别名]
def set_admin_password():
api_auth = _authenticate()
# Only Admin can do this
if api_auth["admin"] != "True" or api_auth["authenticated"] == "False":
response.status = 401
return dict({"info":"Unauthorized."})
try:
payload = json.load(request.body)
new_password = payload["password"]
except:
response.status = 400
return dict({"info":"No valid JSON found in post body or mandatory fields missing."})
# Read record for admin user
admin_record = json.loads(rc.get("USER:0"))
admin_record["hash"] = _get_password_hash(new_password)
rc.set("USER:0", json.dumps(admin_record, ensure_ascii=False))
return(dict(info="updated"))
# Read Key
示例3: eventsindex
# 需要导入模块: from bottle import request [as 别名]
# 或者: from bottle.request import body [as 别名]
def eventsindex():
if request.body:
anevent=request.body.read()
# bottlelog('request:{0}\n'.format(anevent))
request.body.close()
# valid json?
try:
eventDict=json.loads(anevent)
except ValueError:
response.status=500
return
# let the message queue worker who gets this know where it was posted
eventDict['endpoint']='events'
# post to event message queue
ensurePublish=mqConn.ensure(mqproducer,mqproducer.publish,max_retries=10)
ensurePublish(eventDict,exchange=eventTaskExchange,routing_key=options.taskexchange)
return
示例4: cefindex
# 需要导入模块: from bottle import request [as 别名]
# 或者: from bottle.request import body [as 别名]
def cefindex():
if request.body:
anevent=request.body.read()
request.body.close()
# valid json?
try:
cefDict=json.loads(anevent)
except ValueError:
response.status=500
return
# let the message queue worker who gets this know where it was posted
cefDict['endpoint']='cef'
# post to eventtask exchange
ensurePublish=mqConn.ensure(mqproducer,mqproducer.publish,max_retries=10)
ensurePublish(cefDict,exchange=eventTaskExchange,routing_key=options.taskexchange)
return
示例5: index
# 需要导入模块: from bottle import request [as 别名]
# 或者: from bottle.request import body [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
示例6: sync_alert_schedules
# 需要导入模块: from bottle import request [as 别名]
# 或者: from bottle.request import body [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
示例7: update_alert_schedules
# 需要导入模块: from bottle import request [as 别名]
# 或者: from bottle.request import body [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
示例8: create_user
# 需要导入模块: from bottle import request [as 别名]
# 或者: from bottle.request import body [as 别名]
def create_user():
api_auth = _authenticate()
# Only Admin can do this
if api_auth["admin"] != "True" or api_auth["authenticated"] == "False":
response.status = 401
return dict({"info":"Unauthorized."})
try:
payload = json.load(request.body)
username = payload["username"]
password = payload["password"]
except:
response.status = 400
return dict({"info":"No valid JSON found in post body or mandatory fields missing."})
if _find_user(username) == "found":
response.status = 400
return dict({"info":"This user exists already."})
# Set ID and password hash for user
new_userid = rc.incr("_USERID_")
pwhash = _get_password_hash(password)
user_record = {}
user_record["username"] = username
user_record["hash"] = pwhash
user_record["quota"] = "0"
rc.set("USER:"+str(new_userid), json.dumps(user_record, ensure_ascii=False))
return(dict(info="created", id=new_userid))
# Read User
示例9: set_user_quota
# 需要导入模块: from bottle import request [as 别名]
# 或者: from bottle.request import body [as 别名]
def set_user_quota(id):
api_auth = _authenticate()
# Only Admin can do this
if api_auth["admin"] != "True" or api_auth["authenticated"] == "False":
response.status = 401
return dict({"info":"Unauthorized."})
# Get Payload
try:
payload = json.load(request.body)
quota = payload["quota"]
except:
response.status = 400
return dict({"info":"No valid JSON found in post body or mandatory fields missing."})
# Read from Redis
try:
user_record = json.loads(rc.get("USER:"+str(id)))
except:
response.status = 404
return dict({"info":"Not found."})
user_record["quota"] = quota
rc.set("USER:"+str(id), json.dumps(user_record, ensure_ascii=False))
return dict({"info":"Quota updated for user."})
# Delete User
示例10: create_route
# 需要导入模块: from bottle import request [as 别名]
# 或者: from bottle.request import body [as 别名]
def create_route():
api_auth = _authenticate()
# Authorization is needed for this endpoint
if api_auth["authenticated"] == "False":
response.status = 401
return dict({"info":"Unauthorized."})
# Get User ID
user_id = api_auth["id"]
try:
payload = json.load(request.body)
key = payload["key"]
content_type = payload["content_type"]
except:
response.status = 400
return dict({"info":"No valid JSON found in post body or mandatory fields missing."})
id = str(uuid.uuid4())
# Construct Resource Location
redis_key = "ROUTE:"+str(id)
route_record = {}
route_record["key"] = key
route_record["content_type"] = content_type
route_record["user_id"] = user_id
# Write to Redis
try:
rc.set(redis_key, json.dumps(route_record, ensure_ascii=False))
except:
response.status = 400
return dict({"info":"not a valid request"})
return(dict(info="ok", path="/routes/"+str(id)))
# Route - Read Key
示例11: post_to_bin
# 需要导入模块: from bottle import request [as 别名]
# 或者: from bottle.request import body [as 别名]
def post_to_bin(id):
bin_key = "BIN:"+str(id)
# Read Bin from Redis
try:
bin_content = rc.get(bin_key)
if bin_content == None:
raise ValueError('not found')
bin_record = json.loads(bin_content)
user_id = bin_record["user_id"]
list = bin_record["list"]
except:
response.status = 404
return dict({"info":"Not found."})
# Construct Resource Location from user_id and id
redis_key = "LIST:"+str(user_id)+"::"+str(list)
try:
rc.lpush(redis_key, request.body.read())
except:
response.status = 400
return dict({"info":"not a valid request"})
return("OK")
####### Helper functions
# Parse Routes for nested keys
示例12: register
# 需要导入模块: from bottle import request [as 别名]
# 或者: from bottle.request import body [as 别名]
def register():
""" Register an endpoint request
1. Start an executor client object corresponding to the endpoint
2. Pass connection info back as a json response.
"""
print("Request: ", request)
print("foo: ", request.app.ep_mapping)
print(json.load(request.body))
endpoint_details = json.load(request.body)
print(endpoint_details)
# Here we want to start an executor client.
# Make sure to not put anything into the client, until after an interchange has
# connected to avoid clogging up the pipe. Submits will block if the client has
# no endpoint connected.
endpoint_id = str(uuid.uuid4())
fw = spawn_forwarder(request.app.address, endpoint_id=endpoint_id)
connection_info = fw.connection_info
ret_package = {'endpoint_id': endpoint_id}
ret_package.update(connection_info)
print("Ret_package : ", ret_package)
print("Ep_id: ", endpoint_id)
request.app.ep_mapping[endpoint_id] = ret_package
return ret_package
示例13: add
# 需要导入模块: from bottle import request [as 别名]
# 或者: from bottle.request import body [as 别名]
def add():
body = request.body
if PY3:
body = TextIOWrapper(body, encoding='utf-8')
data = DotDict(json.load(body))
if data.user != request.auth[0]:
abort(401, "Error: user does not match authentication!")
result = db.add(data)
return result
示例14: do_put_record
# 需要导入模块: from bottle import request [as 别名]
# 或者: from bottle.request import body [as 别名]
def do_put_record(self):
reqid = request.query.getunicode('reqid')
info = self.browser_mgr.init_remote_browser_session(reqid=reqid)
if not info:
return self._raise_error(400, 'invalid_connection_source')
user = info['the_user']
collection = info['collection']
recording = info['recording']
kwargs = dict(user=user.name,
coll=collection.my_id,
rec=recording.my_id,
type='put_record')
url = request.query.getunicode('target_uri')
params = {'url': url}
upstream_url = self.get_upstream_url('', kwargs, params)
headers = {'Content-Type': request.environ.get('CONTENT_TYPE', 'text/plain')}
r = requests.put(upstream_url,
data=request.body,
headers=headers,
)
try:
res = r.json()
if res['success'] != 'true':
print(res)
return {'error_message': 'put_record_failed'}
warc_date = res.get('WARC-Date')
except Exception as e:
print(e)
return {'error_message': 'put_record_failed'}
return res
示例15: _get_parent
# 需要导入模块: from bottle import request [as 别名]
# 或者: from bottle.request import body [as 别名]
def _get_parent(self):
params = json.load(request.body)
parent = params.get('parent')
if parent is None or 'id' not in parent:
abort(400, 'Missing parameter: parent(id)')
parent_id = parent['id']
return get_folder_by_id(self._db_session, parent_id)