def allow(): try: last_query = session['last_check_id_request'] except KeyError as e: raise BadRequestKeyError(e.message) openid_request = oidserver.decodeRequest(last_query) if 'yes' in request.form: if request.form.get('remember', 'no') == 'yes': trust_root = openid_request.trust_root session['approved'][trust_root] = 'always' response = openid_request.answer(True, identity=base_url + 'id') sreg_request = sreg.SRegRequest.fromOpenIDRequest(openid_request) sreg_data = { 'name': config['name'], } sreg_response = sreg.SRegResponse.extractResponse( sreg_request, sreg_data) response.addExtension(sreg_response) elif 'no' in request.form: response = openid_request.answer(False) else: raise BadRequestKeyError('strange allow post.') return render_response(response)
def stats(): """ Get a file stats :return: file stats dict """ try: msg = {'message': 'error: missing data'} data = request.get_json(force=True) if 'file' not in data.keys(): msg = {'message': 'error: bad body'} raise BadRequestKeyError() except (BadRequestKeyError, BadRequest, Exception) as e: return msg, 400 status_code = 200 contents = {} msg = {} response = {'request': '/file/stats'} rc, result = get_file_stats(data['file']) if rc == 0: response['response'] = result else: msg = result status_code = 404 response.update(contents) response.update(msg) return response, status_code
def check_unknown_fields(self, data, original_data): """ Ensure no additional fields are passed """ unknown = set(original_data) - set(self.fields) if unknown: raise BadRequestKeyError("Unknown field {}".format(unknown))
def check_unknown_field(self, data, original_data): """ Check that a single instance of a field validates """ unknown = set(original_data) - set(self.fields) if unknown: raise BadRequestKeyError("Unknown field {}".format(unknown))
def check_unknown_fields(self, data, original_data): """ Ensure no additional fields are passed """ unknown = set() for output in original_data: unknown = set(unknown).union(set(output)) - set(data) if unknown: raise BadRequestKeyError("Unknown field", unknown)
def check_unknown_fields(self, data, original_data, many): """ Ensure no additional fields are passed """ if not many: self.check_unknown_field(data, original_data) return if len(data) != len(original_data): raise BadRequestKeyError( "Could not parse all fields, {}".format(original_data)) for index in range(0, len(data)): self.check_unknown_field(data[index], original_data[index])
def register_app(): username = request.headers.get('username') password = request.headers.get('password') app_name = (request.form or {}).get('app_name') if not username: raise BadRequestKeyError("username should be provided in the header") if not password: raise BadRequestKeyError("password should be provided in the header") if not app_name: raise BadRequest("app_name must me provided in request body") result = create_app(username, password, app_name) if result == 0: raise Unauthorized("username/password did not match.") return jsonify({'app_id': result.app_id, 'app_name': result.app_name, 'app_key': result.app_key})
def add_patient(): "add new patient if logged in" if not session.get('logged_in'): # logged_in key present and True abort(401) try: xray = bool2int(request.form['xray']) if not xray: flash('No Xray data, cannot make diagnosis') return redirect(url_for('new_patient')) patient_id = request.form['patient_id'] # should not be empty if len(patient_id) < 5: # could flash(msg) raise BadRequestKeyError('patient id invalid, too short') ddensity = choice2int(request.form['double_density']) ob_diam = float(request.form['oblique_diameter']) app_shape = choice2appendage(request.form['appendage_shape']) gender = request.form['gender'] except (BadRequestKeyError, Exception) as inst: # app.logger.warning('request.form %s', str(type(request.form))) # app.logger.warning("inst type %s args %s inst %s", str(type(inst)), inst.args, inst) # we may: redirect if form incomplete (not store in db), re-raise exception, log messages # raise # raise BadRequestKeyError(*inst.args) flash('Patient info incomplete, please re-enter') return redirect(url_for('new_patient')) has_patient = get_params(patient_id) if has_patient: flash("patient id '%s' already exists, please re-enter" % patient_id) return redirect(url_for('new_patient')) x_outcome = '' if (xray > 0): x_outcome = getXrayOutcome(gender, ddensity, ob_diam, app_shape) dz = getNowTimeInt() ctmri = 0 cur = g.db.cursor() cur.execute('insert into patients (patient_id, gender, date_created, \ xray, double_density, oblique_diameter, \ appendage_shape, xray_outcome, ctmri) values \ (%s, %s, %s, %s, %s, %s, %s, %s, %s);', (patient_id, gender, dz, xray, ddensity, ob_diam, app_shape, x_outcome, ctmri)) g.db.commit() flash('New patient was successfully posted') return redirect(url_for('show_patient', patient_id=patient_id))
def search_products(): query=None try: if request.args.get('code', default=None, type=None) is not None: query = request.args.get('code', '') iCode = int(query) row = searchSvc.getProductsByCode(iCode) return jsonify(row) elif request.args.get('descr', default=None, type=None) is not None: query = request.args.get('descr', '') rows = searchSvc.getProductsByDescr(query) return jsonify(rows) else: raise BadRequestKeyError("Error getting params") except Exception as error: if type(error).__name__=="BadRequestKeyError": return jsonify(error = "Send code or description") , 400 else: return jsonify(error = "Error Inesperado, {}".format(error)) , 500
def services_modify(name): """ Get, stop or restart an fswatch service by name or all (<name> == '_all') json body: { "action": on of ["start", "stop", "restart"] } :param name: fswatch service name or '_all' for addressing all execsnoop services :return: status of changes made or requested service info """ ALL_SERVICES = '_all' ALLOWED_ACTIONS = ['start', 'stop', 'restart'] DEFAULT_STATUS_CODE = 200 contents = {} response = {'request': f'/fswatch/services/{name}'} msg = {} status_code = DEFAULT_STATUS_CODE if request.method == 'POST': # GET a single service is allowed without body try: data = request.get_json(force=True) if 'action' not in data.keys(): msg = {'message': 'error: bad body'} status_code = 400 raise BadRequestKeyError() if 'action' in data.keys( ) and data['action'] not in ALLOWED_ACTIONS: msg = {'message': 'error: bad action'} status_code = 400 raise BadRequestKeyError() except BadRequestKeyError: return msg, status_code except BadRequest: return {'message': 'error: missing data'}, 400 elif request.method != 'GET': return {}, 400 if status_code == DEFAULT_STATUS_CODE: units = interface.systemd_adapter.get_all_systemd_units('fswatch@') if request.method == 'GET': # resolve the GET request and return a single service if name == ALL_SERVICES: # ALL_SERVICES is allowed only for POST method msg = { 'message': "info: use the designated API endpoint '/fswatch/services' or use POST" } else: found_service = [ unit for unit in units if unit['name'] == name ] if len(found_service) > 0: contents = {'response': found_service[0]} if not contents: msg = {'message': 'error: unknown service name'} status_code = 404 elif request.method == 'POST': names = [u['name'] for u in units] if name == ALL_SERVICES: contents = { 'response': interface.systemd_adapter.run(data['action'], names) } else: for unit_name in names: if unit_name.rstrip('.service') == name.rstrip('.service'): contents = { 'response': interface.systemd_adapter.run( data['action'], name) } break if not contents and data['action'] == 'start': # if no service was found and the action is start contents = { 'response': interface.systemd_adapter.run('start', name) } if not contents: msg = {'message': 'no services modified'} response.update(contents) response.update(msg) return response, status_code
def __getitem__(self, key): v = dict.get(self, key, None) if not v: raise BadRequestKeyError(key) return v
def raise_400(): '''As expected, werkzeug exceptions can be manually raised with expected behavior''' raise BadRequestKeyError('This is a custom message') return 'OK'