def session_check_update(session_name, check_name):
try:
req = request.get_json()
if req is None:
req = {}
fw.sessions[session_name].checks.update(name=check_name, **req)
return make_response(jsonify(message='Rollback check updated'), status.HTTP_200_OK)
except CheckNotFound as e:
http_code = status.HTTP_404_NOT_FOUND
except CheckNotValid as e:
http_code = status.HTTP_400_BAD_REQUEST
except CheckNotUpdated as e:
return make_response(jsonify(message='Rollback check not updated'), status.HTTP_204_NO_CONTENT)
except Exception as e:
http_code = status.HTTP_500_INTERNAL_SERVER_ERROR
return make_response(jsonify(message='Failed to update rollback check', error=e.message), http_code)
python类get_json()的实例源码
def add_user():
content = request.get_json(silent=True)
user = User(**content.get('user'))
try:
db.query("INSERT INTO users " +
"(email, password) " +
"VALUES ('{0}', '{1}')".format(user.email,
user.password))
except IntegrityError as e:
logger.info("User exists for {0}".format(user.email))
return jsonify({"error": "Email {0} already has an user".format(user.email)})
rows = db.query("SELECT seq FROM sqlite_sequence WHERE NAME = 'users'")
user_id = rows.all()[0].get('seq', 0)
created = db.query("SELECT * FROM users WHERE id = {0}".format(user_id))
return jsonify(**created.all()[0])
def hello():
if request.method == 'GET':
if request.args.get("hub.verify_token") == VERIFY_TOKEN:
return request.args.get("hub.challenge")
else:
return 'Invalid verification token'
if request.method == 'POST':
output = request.get_json()
for event in output['entry']:
messaging = event['messaging']
for x in messaging:
if x.get('message'):
recipient_id = x['sender']['id']
if x['message'].get('text'):
message = x['message']['text']
bot.send_text_message(recipient_id, message)
if x['message'].get('attachments'):
for att in x['message'].get('attachments'):
bot.send_attachment_url(recipient_id, att['type'], att['payload']['url'])
else:
pass
return "Success"
def update_payments(id):
try:
if not request.is_json:
raise DataValidationError('Invalid payment: Content Type is not json')
data = request.get_json(silent=True)
message = payment_service.update_payment(id,payment_replacement=data)
rc = status.HTTP_200_OK
except PaymentNotFoundError as e:
message = e.message
rc = status.HTTP_404_NOT_FOUND
except DataValidationError as e:
message = e.message
rc = status.HTTP_400_BAD_REQUEST
return make_response(jsonify(message), rc)
######################################################################
# UPDATE AN EXISTING PAYMENT PARTIALLY
######################################################################
def update_partial_payments(id):
try:
if not request.is_json:
raise DataValidationError('Invalid payment: Content Type is not json')
data = request.get_json(silent=True)
message = payment_service.update_payment(id,payment_attributes=data)
rc = status.HTTP_200_OK
except PaymentNotFoundError as e:
message = e.message
rc = status.HTTP_404_NOT_FOUND
except DataValidationError as e:
message = e.message
rc = status.HTTP_400_BAD_REQUEST
return make_response(jsonify(message), rc)
######################################################################
# DELETE A PAYMENT
######################################################################
def charge_payment(user_id):
try:
if not request.data:
raise DataValidationError('Invalid request: body of request contained no data')
if not request.is_json:
raise DataValidationError('Invalid request: request not json')
data = request.get_json()
if data['amount']:
if(data['amount'] < 0):
raise DataValidationError('Invalid request: Order amount is negative.')
else:
resp = payment_service.perform_payment_action(user_id,payment_attributes=data)
if resp == True:
message = {'success' : 'Default payment method for user_id: %s has been charged $%.2f' % (str(user_id), data['amount'])}
rc = status.HTTP_200_OK
except DataValidationError as e:
message = {'error' : e.message}
rc = status.HTTP_400_BAD_REQUEST
except KeyError as e:
message = {'error' : 'Invalid request: body of request does not have the amount to be charged'}
rc = status.HTTP_400_BAD_REQUEST
return make_response(jsonify(message), rc)
def update_or_delete_comment(defendant=None, comment=None):
""" Update or delete defendant comments
"""
if request.method == 'PUT':
body = request.get_json()
return CommentsController.update(
body,
comment_id=comment,
user_id=g.user.id
)
else:
return CommentsController.delete(
comment_id=comment,
defendant_id=defendant,
user_id=g.user.id
)
def update_or_delete_comment(ticket=None, comment=None):
""" Update or delete ticket comments
"""
if request.method == 'PUT':
body = request.get_json()
return CommentsController.update(
body,
comment_id=comment,
ticket_id=ticket,
user_id=g.user.id
)
else:
return CommentsController.delete(
comment_id=comment,
ticket_id=ticket,
user_id=g.user.id
)
def validate_body(schema_desc):
"""
Validate json body
"""
def real_decorator(func):
@wraps(func)
def wrapper(*args, **kwargs):
try:
body = request.get_json()
if not Schemas.get(func.__name__):
Schemas[func.__name__] = Schema(schema_desc, required=True)
Logger.debug(unicode('registering schema for %s' % (func.__name__)))
Schemas[func.__name__](body)
except (Invalid, MultipleInvalid) as ex:
Logger.error(unicode(ex))
msg = 'Missing or invalid field(s) in body, expecting {}'.format(schema_desc)
raise BadRequest(msg)
return func(*args, **kwargs)
return wrapper
return real_decorator
def auth():
"""
Check user/password and returns token if valid
"""
if settings.API.get('forwarded_host'):
try:
if not request.environ['HTTP_X_FORWARDED_HOST'] == settings.API['forwarded_host']:
raise BadRequest('Invalid HTTP_X_FORWARDED_HOST')
except KeyError:
raise BadRequest('Missing HTTP_X_FORWARDED_HOST')
body = request.get_json()
authenticated, ret = GeneralController.auth(body)
if authenticated:
return ret
else:
raise Unauthorized(ret)
def put_relays(pin_id):
data = request.get_json()
wanted_state = data.get('state_str')
reset_to_auto = wanted_state == 'auto'
# p = synced_pins[int(pin_id)]
p = Pin.query.filter(Pin.pin_id is int(pin_id)).one()
if reset_to_auto:
p.reset_user_override()
else:
p.set_user_override(wanted_state)
db.session.add(p)
p = Pin.query.filter(Pin.pin_id is int(pin_id)).one()
# Share to other processes
return jsonify({'relay': p.as_pub_dict()}), 200
def create_tenant():
logger.info("User %s requested creation", g.user)
data = request.get_json(force=True)
logger.debug("Request data: %s" % data)
mconf = data['machine_conf'] if 'machine_conf' in data else CONF.MACHINE
cconf = data['cloud_conf'] if 'cloud_conf' in data else CONF.CLOUD_CONFIG
ip, machine_id = tenant_create(tenant_name=data['tenant'],
tenant_keys=extract_keys(data['pub_key']),
image_name_or_id=data['image_id'],
credentials=credentials, cloud_conf=cconf,
machine_conf=mconf)
tenant = Tenant(tenant_name=data['tenant'], machine_id=machine_id, ip=ip)
db.session.add(tenant)
db.session.commit()
return jsonify(tenant=data['tenant'], machine_id=machine_id, ip=ip), 202
def get_or_add_objects(api_root, id_):
# TODO: Check if user has access to read or write objects in collection - right now just check for permissions on the collection.
if request.method == "GET":
if permission_to_read(api_root, id_):
objects = get_backend().get_objects(api_root, id_, request.args, ("id", "type", "version"))
if objects:
return Response(response=flask.json.dumps(objects),
status=200,
mimetype=MEDIA_TYPE_STIX_V20)
else:
abort(404)
else:
abort(403)
elif request.method == "POST":
if permission_to_write(api_root, id_):
# can't I get this from the request itself?
request_time = common.format_datetime(common.get_timestamp())
status = get_backend().add_objects(api_root, id_, request.get_json(force=True), request_time)
return Response(response=flask.json.dumps(status),
status=202,
mimetype=MEDIA_TYPE_TAXII_V20)
else:
abort(403)
def require_login_api(func):
"""
A custom implementation of Flask-login's built-in @login_required decorator.
This decorator will allow usage of the API endpoint if the user is either currently logged in via the app
or if the user authenticates with an API key in the POST JSON parameters.
This implementation overrides the behavior taken when the current user is not authenticated by
returning the predefined AUTH_FAILURE JSON response with HTTP status code 401.
This decorator is intended for use with API endpoints.
"""
@wraps(func)
def decorator(*args, **kwargs):
data = request.get_json()
if current_user.is_authenticated:
return func(*args, **kwargs)
try:
if data and data.get('api_key'):
user = database.user.get_user_by_api_key(data['api_key'], active_only=True)
login_user(user)
del data['api_key']
request.get_json = lambda: data
return func(*args, **kwargs)
except UserDoesNotExistException:
return jsonify(AUTH_FAILURE), AUTH_FAILURE_CODE
return jsonify(AUTH_FAILURE), AUTH_FAILURE_CODE
return decorator
def optional_login_api(func):
"""
This decorator is similar in behavior to require_login_api, but is intended for use with endpoints that offer
extended functionality with a login, but can still be used without any authentication.
The decorator will set current_user if authentication via an API key is provided, and will continue without error
otherwise.
This decorator is intended for use with API endpoints.
"""
@wraps(func)
def decorator(*args, **kwargs):
data = request.get_json()
if current_user.is_authenticated:
return func(*args, **kwargs)
try:
if data and data.get('api_key'):
user = database.user.get_user_by_api_key(data['api_key'], active_only=True)
login_user(user)
del data['api_key']
request.get_json = lambda: data
return func(*args, **kwargs)
except UserDoesNotExistException:
return jsonify(AUTH_FAILURE), AUTH_FAILURE_CODE
return func(*args, **kwargs)
return decorator
def test_optional_login_api_deactivated_user(self):
with app.test_request_context():
@optional_login_api
def login_optional():
if current_user.is_authenticated:
return 'authenticated'
return 'not authenticated'
self.assertEqual('not authenticated', login_optional())
user = util.testing.UserFactory.generate()
database.user.deactivate_user(user.user_id)
request.get_json = lambda: {
'api_key': user.api_key,
}
resp, resp_code = login_optional()
self.assertEqual(constants.api.AUTH_FAILURE, json.loads(resp.data))
self.assertEqual(constants.api.AUTH_FAILURE_CODE, resp_code)
def test_require_login_frontend(self):
with app.test_request_context():
@require_login_frontend()
def login_required():
return 'success'
self.assertEqual(login_required().status_code, 302) # Redirect
user = util.testing.UserFactory.generate(password='password')
request.get_json = lambda: {
'username': user.user_id,
'password': 'password',
}
login_user(user)
self.assertEqual(login_required(), 'success')
@require_login_frontend(only_if=False)
def conditional_login_required():
return 'success'
self.assertEqual(login_required(), 'success')
rest_api.py 文件源码
项目:fabric8-analytics-stack-analysis
作者: fabric8-analytics
项目源码
文件源码
阅读 20
收藏 0
点赞 0
评论 0
def train_and_save_kronos():
app.logger.info("Submitting the training job")
input_json = request.get_json()
training_data_url = input_json.get("training_data_url")
fp_min_support_count = input_json.get(gnosis_constants.FP_MIN_SUPPORT_COUNT_NAME,
gnosis_constants.FP_MIN_SUPPORT_COUNT_VALUE)
fp_intent_topic_count_threshold = input_json.get(
gnosis_constants.FP_INTENT_TOPIC_COUNT_THRESHOLD_NAME,
gnosis_constants.FP_INTENT_TOPIC_COUNT_THRESHOLD_VALUE)
fp_num_partition = input_json.get(gnosis_constants.FP_NUM_PARTITION_NAME,
gnosis_constants.FP_NUM_PARTITION_VALUE)
response = submit_job(input_bootstrap_file='/bootstrap_action.sh',
input_src_code_file='/tmp/training.zip',
training_data_url=training_data_url,
fp_min_support_count=str(fp_min_support_count),
fp_intent_topic_count_threshold=str(fp_intent_topic_count_threshold),
fp_num_partition=str(fp_num_partition))
return flask.jsonify(response)
rest_api.py 文件源码
项目:fabric8-analytics-stack-analysis
作者: fabric8-analytics
项目源码
文件源码
阅读 27
收藏 0
点赞 0
评论 0
def predict_and_score():
input_json = request.get_json()
app.logger.info("Analyzing the given EPV")
app.logger.info(input_json)
response = {"message": "Failed to load model, Kronos Region not available"}
if app.scoring_status:
response = score_eco_user_package_dict(
user_request=input_json,
user_eco_kronos_dict=app.user_eco_kronos_dict,
eco_to_kronos_dependency_dict=app.eco_to_kronos_dependency_dict,
all_package_list_obj=app.all_package_list_obj)
app.logger.info("Sending back Kronos Response")
app.logger.info(response)
return flask.jsonify(response)
rest_api.py 文件源码
项目:fabric8-analytics-stack-analysis
作者: fabric8-analytics
项目源码
文件源码
阅读 24
收藏 0
点赞 0
评论 0
def submit_kronos_evaluation():
app.logger.info("Submitting the evaluation job")
response = {
"status_description": "Failed to load model, Kronos Region not available"}
if not app.scoring_status:
return flask.jsonify(response)
result_id = str(uuid1())
input_json = request.get_json()
training_data_url = input_json.get("training_data_url")
response = submit_evaluation_job(input_bootstrap_file='/uranus_bootstrap_action.sh',
input_src_code_file='/tmp/testing.zip',
training_url=training_data_url,
result_id=result_id)
response["evaluation_S3_result_id"] = result_id
return flask.jsonify(response)