def bad_request(error): """ Bad Request response for a request. Takes an error message. """ if isinstance(error, BadRequest): return make_response(jsonify({'code': 400, 'error': 'BadRequest'}), 400) return make_response(jsonify({'code': 400, 'error': error}), 400)
def read_all_entries(category_id='', feed_id=None): if feed_id: feed_ids = [feed_id] else: cursor = Cursor(category_id) feed_ids = [sub.feed_id for sub in cursor.recursive_subscriptions] try: codec = Rfc3339() last_updated = codec.decode(request.args.get('last_updated')) except: last_updated = None for feed_id in feed_ids: try: with stage: feed = stage.feeds[feed_id] for entry in feed.entries: if not last_updated or entry.updated_at <= last_updated: entry.read = True stage.feeds[feed_id] = feed except KeyError: if feed_id: r = jsonify( error='feed-not-found', message='Given feed does not exist' ) r.status_code = 404 return r else: continue return jsonify()
def add_feed(category_id): cursor = Cursor(category_id) url = request.form['url'] try: f = urllib.request.urlopen(url) document = f.read() f.close() except Exception: r = jsonify( error='unreachable-url', message='Cannot connect to given url' ) r.status_code = 400 return r try: feed_links = autodiscovery(document, url) except FeedUrlNotFoundError: r = jsonify( error='unreachable-feed-url', message='Cannot find feed url' ) r.status_code = 400 return r feed_url = feed_links[0].url feed_url, feed, hints = next(iter(crawl([feed_url], 1))) with stage: sub = cursor.subscribe(feed) stage.subscriptions = cursor.subscriptionlist stage.feeds[sub.feed_id] = feed return feeds(category_id)
def create_a_solution(): json_data = request.get_json() if not json_data: return jsonify({'message': 'No input data provided'}), 400 data, errors = schemas.solution_schema.load(json_data) if errors: return jsonify(errors), 422 last = models.Solution.query.filter_by(hash=data['hash']).one_or_none() if last: solution = last solution.xml = data['xml'] solution.usuario = data['usuario'] solution.desafio = data['desafio'] else: solution = models.Solution(data['hash'], data['usuario'], data['desafio'], data['xml']) db.session.add(solution) db.session.commit() result = schemas.solution_schema.dump(solution) return jsonify({'data': result.data})
def move_outline(category_id): source_path = request.args.get('from') if '/feeds/' in source_path: parent_category_id, feed_id = source_path.split('/feeds/') source = Cursor(parent_category_id) target = None for child in source: if child.feed_id == feed_id: target = child else: source = Cursor(source_path, True) target = source.target_child dest = Cursor(category_id) if isinstance(target, Category) and target.contains(dest.value): r = jsonify( error='circular-reference', message='Cannot move into child element.' ) r.status_code = 400 return r source.discard(target) with stage: stage.subscriptions = source.subscriptionlist dest = Cursor(category_id) dest.add(target) with stage: stage.subscriptions = dest.subscriptionlist return jsonify()
def get_club(rowkey): if not check_auth(request): abort(403) club = db_session.query(Club).filter_by(rowkey=rowkey).first() if club is None: abort(404) if request.method =='GET': return jsonify({'idclub': club.idclub, 'name': club.name, 'description': club.description, 'postaladdress': club.postaladdress, 'postalzipcode': club.postalzipcode, 'postalcity': club.postalcity, 'visitingaddress': club.visitingaddress, 'visitingzipcode': club.visitingzipcode, 'visitingcity': club.visitingcity, 'rowkey': club.rowkey}) if request.method =='POST': club.visitingaddress = request.json["visitingaddress"] club.visitingzipcode = request.json["visitingzipcode"] club.visitingcity = request.json["visitingcity"] club.name = request.json["name"] club.postaladdress = request.json["postaladdress"] club.postalzipcode = request.json["postalzipcode"] club.postalcity = request.json["postalcity"] db_session.commit() return jsonify({'idclub': club.idclub, 'name': club.name, 'description': club.description, 'postaladdress': club.postaladdress, 'postalzipcode': club.postalzipcode, 'postalcity': club.postalcity, 'visitingaddress': club.visitingaddress, 'visitingzipcode': club.visitingzipcode, 'visitingcity': club.visitingcity, 'rowkey': club.rowkey})
def profile_view(id): profile = Myprofile.query.get(id) if request.method == "GET": return jsonify({"Data":"No GET request"}) if request.method == "POST": return jsonify({"id":profile.id, "sex":profile.sex, "image":profile.image, "high_score":profile.high_score, "tdollars":profile.tdollars}) return render_template('profile_view.html',profile=profile)
def decorated_function(*args, **kwargs): data = request.get_json(force=True) if 'authtoken' not in data: return jsonify(error="You need to send authtoken along with every request"),403 if not check_status(data['authtoken']): return jsonify(error="Login Required"),403 return f(*args, **kwargs)
def get_stored_entry(objhash, value): """ This is a dispatcher function which dispatches the request to either a function to return an value of an object or a field of a table. """ response = {'status':'success','data':{}} row = UserPyObj.query.filter_by(datahash = objhash).first() if row != None: row.get_pyobj() if value != 'full_result' and value != 'raw': try: responsedata = getattr(row.liveobj, value) if isinstance(responsedata, np.ndarray): responsedata = responsedata.tolist() response['data'] = responsedata return jsonify(response) except: return jsonify({'status':'failure', 'data':'Unable to find value'}) elif value == 'raw': return row.pyobj else: #serialize the full row pass else: response = get_dataset_field(objhash, value) return jsonify(response)
def get_contents(side): assert side in ('a', 'b') path = request.form.get('path', '') if not path: e = {"code": "incomplete", "message": "Incomplete request (need path)"} response = jsonify(e) response.status_code = 400 return response try: abs_path = os.path.join(A_DIR if side == 'a' else B_DIR, path) is_binary = util.is_binary_file(abs_path) if is_binary: size = os.path.getsize(abs_path) contents = "Binary file (%d bytes)" % size else: contents = open(abs_path).read() return Response(contents, mimetype='text/plain') except Exception: e = {"code": "read-error", "message": "Unable to read %s" % abs_path} response = jsonify(e) response.status_code = 400 return response
def get_image(side, path): assert side in ('a', 'b') if not path: e = {"code": "incomplete", "message": "Incomplete request (need path)"} response = jsonify(e) response.status_code = 400 return response mime_type, enc = mimetypes.guess_type(path) if not mime_type.startswith('image/') or enc is not None: e = {"code": "wrongtype", "message": "Requested file of type (%s, %s) as image" % ( mime_type, enc)} response = jsonify(e) response.status_code = 400 return response try: abs_path = os.path.join(A_DIR if side == 'a' else B_DIR, path) contents = open(abs_path).read() return Response(contents, mimetype=mime_type) except Exception: e = {"code": "read-error", "message": "Unable to read %s" % abs_path} response = jsonify(e) response.status_code = 400 return response
def continue_workflow_callback(): """Handle callback to continue a workflow. Expects the request data to contain a object ID in the nonce field. """ request_data = request.get_json() id_object = request_data.get("nonce", "") if id_object: callback_results = request_data.get("results", {}) workflow_object = BibWorkflowObject.query.get(id_object) if workflow_object: results = request_data.get("results", []) for result in results: status = result.get('success', False) if status: recid = result.get('recid') extra_data = workflow_object.get_extra_data() extra_data['url'] = join( cfg["CFG_ROBOTUPLOAD_SUBMISSION_BASEURL"], 'record', str(recid) ) extra_data['recid'] = recid workflow_object.set_extra_data(extra_data) # Will add the results to the engine extra_data column. workflow_object.continue_workflow( delayed=True, callback_results=callback_results ) return jsonify({"result": "success"}) return jsonify({"result": "failed"})
def merge(): try: if request.method == 'OPTIONS': return make_response(jsonify({"Allow":"POST"}), 200) if not request.json or not 'foreground_url' in request.json or not 'background_url' in request.json: abort(400) foreground_url = request.json['foreground_url'] background_url = request.json['background_url'] m = Merger(foreground_url, background_url) m.merge_images() response = { 'output_image':{ 'name': m.get_output_image('name'), 'url' : url_for('get_image', image_name = m.get_output_image('name'),_external=True), 'base64' : m.get_output_image('base64') } } return jsonify(response), 201 except Exception as e: err_msg = e.message if err_msg == '': err_msg = 'Internal Error. Please Try Again' return make_response(jsonify({'error': e.message}), 202)
def api_update(self, pk): is_valid_form = True get_filter_args(self._filters) exclude_cols = self._filters.get_relation_cols() item = self.datamodel.get(pk, self._base_filters) if not item: abort(404) # convert pk to correct type, if pk is non string type. pk = self.datamodel.get_pk_value(item) form = self.edit_form.refresh(request.form) # fill the form with the suppressed cols, generated from exclude_cols self._fill_form_exclude_cols(exclude_cols, form) # trick to pass unique validation form._id = pk if form.validate(): form.populate_obj(item) self.pre_update(item) if self.datamodel.edit(item): self.post_update(item) http_return_code = 200 else: http_return_code = 500 else: is_valid_form = False if is_valid_form: response = make_response(jsonify({'message': self.datamodel.message[0], 'severity': self.datamodel.message[1]}), http_return_code) else: # TODO return dict with from errors validation response = make_response(jsonify({'message': 'Invalid form', 'severity': 'warning'}), 500) return response
def details(): data = [] try: data.append(request.args.get('post')) select_stmt = ('SELECT * FROM Posts WHERE id = %s') if (int(data[0])<0): return jsonify({"code": 1, "response": "object not found"}) post = execute_select(select_stmt, data[0]) if (post): pass else: return jsonify({"code": 1, "response": "object not found"}) except KeyError: answer = {"code": 3, "response": "incorrect request"} return jsonify(answer) except Exception: answer = {"code": 1, "response": "incorrect related"} return jsonify(answer) list = request.args.getlist('related') user_info = post[0][4] forum_info = post[0][5] thread_info = post[0][2] for related in list: if related == 'user': user_info = db_app.user_app.user_app.serialize_user_email(post[0][4]) if related == 'forum': forum_info = db_app.thread_app.thread_app.serialize_forum1(post[0][5]) if related == 'thread': thread_info = serialize_thread1(post[0][2]) answer = jsonify({"code": 0, "response": serialize_post(post[0], user_info, forum_info, thread_info)}) return answer
def get_task(planid): data = mongocli.find_tour(planid) if(data): data['_id'] = None return jsonify(data) else: return jsonify({"result":"none"})
def api_create(self): is_valid_form = True get_filter_args(self._filters) exclude_cols = self._filters.get_relation_cols() form = self.add_form.refresh() self._fill_form_exclude_cols(exclude_cols, form) if form.validate(): item = self.datamodel.obj() form.populate_obj(item) self.pre_add(item) if self.datamodel.add(item): self.post_add(item) http_return_code = 200 else: http_return_code = 500 else: is_valid_form = False if is_valid_form: response = make_response(jsonify({'message': self.datamodel.message[0], 'severity': self.datamodel.message[1]}), http_return_code) else: # TODO return dict with errors response = make_response(jsonify({'message': 'Invalid form', 'severity': 'warning'}), 500) return response
def update_menu_date_relation(menu_date_relation_id): menu_date_relation = db.session.query(MenuDateRelation).filter(MenuDateRelation.id == menu_date_relation_id).one() if menu_date_relation is None: return jsonify( userMessage="관계를 찾을 수 없습니다." ), 404 request_params = request.get_json() if request_params.get('menuId'): menu_id = request_params.get('menuId') else: menu_id = menu_date_relation.menu_id if request_params.get('mealDateId'): meal_date_id = request_params.get('mealDateId') else: meal_date_id = menu_date_relation.meal_date_id q = db.session.query(MenuDateRelation).filter(MenuDateRelation.menu_id == menu_id, MenuDateRelation.meal_date_id == meal_date_id) if q.count() > 0: if q.one() == menu_date_relation: pass else: return jsonify( userMessage="기존에 동일한 관계가 있습니다." ) else: menu_date_relation.menu_id = menu_id menu_date_relation.meal_date_id = meal_date_id db.session.commit() return get_menu_date_relation_by_id(menu_date_relation_id)
def api_fetch_users(username=None, user_id=None): if username: return jsonify( User.query.filter_by(username=username).first_or_404().to_json ) if user_id: return jsonify( User.query.get_or_404(user_id).to_json ) return jsonify( users=[user.to_json for user in User.query.all()] )
def getresults(jobkey): job = Job.fetch(jobkey, connection = conn) if (job.is_finished): return jsonify(job.result) else: return jsonify({"error":"error"}), 202
def oauth_callback(): auth = request.authorization # require client authentication using Basic auth if not auth: response = jsonify({'error': 'invalid_client'}) response.status_code = 401 response.headers['WWW-Authenticate'] = 'Basic realm="Login Required"' return response # we could validate the client_id/secret from the HTTP authentication info here... client_id = auth.username # validate access token token = request.form.get('access_token') if token and request.form.get('method') == 'access_response': survey = request.form.get('survey') response = request.form.get('response') session = get_session(token) if not session.get('user'): return jsonify({'error': 'invalid_grant'}) if not Response.query.filter_by(survey=survey, key=response, username=session.get('user')).count(): abort(404) return jsonify({'success': True}) return jsonify({'error': 'invalid_request'})
def add_vehicle(): user_id = request.args.get('id') # get values from form vplate = request.args.get('vplate').rstrip() vmake = request.args.get('vmake').rstrip() vmodel = request.args.get('vmodel').rstrip() vcapacity = request.args.get('vcapacity').rstrip() vclass = request.args.get('vclass').rstrip().lower() # require vclass be suplux, econ, lux, or suv if (vclass not in ['suplux', 'econ', 'lux', 'suv']): message = "Invalid vehicle class; must be econ, lux, suplux, or suv." data = {'error':1, 'message':message, 'id':user_id} return jsonify(data=data) else: stmt = "INSERT INTO Vehicles (plate_no, make, model, capacity, cname, uid) " + \ "VALUES (\'{}\', \'{}\', \'{}\', {}, \'{}\', {})".format(vplate, vmake, vmodel, vcapacity, vclass, user_id) try: cursor = g.conn.execute(stmt) data = {'error':0, 'id':user_id} return jsonify(data=data) except exc.SQLAlchemyError as e: print str(e) message = "Error entering vehicle, check form entries. Note that drivers cannot share cars per company policy." data = {'error':1, 'message':message, 'id':user_id} return jsonify(data=data)
def complete_trip(): user_id = request.args.get('id') # get values from form tid = request.args.get('comptid').rstrip() amount = request.args.get('tamtcharged').rstrip() paytype = request.args.get('tpaytype').rstrip() prating = request.args.get('tpassrating').rstrip() # require paytype be CASH, AMEX, VISA, or MC if (paytype.lower() not in ['cash', 'amex', 'visa', 'mc']): message = "Invalid payment type; must be CASH, MC, VISA, or AMEX." data = {'error':1, 'message':message, 'id':user_id} return jsonify(data=data) if (paytype=='AMEX' or paytype=='VISA' or paytype=='MC'): # generating random number for auth_id, since we don't have an actual credit card processing system... auth = randint(1,2147483647) stmt = "INSERT INTO Transactions (pay_type, auth_id, amt_charged, tid) VALUES (\'{}\', {}, {}, {})".format(paytype, auth, amount, tid) else: stmt = "INSERT INTO Transactions (pay_type, amt_charged, tid) VALUES (\'{}\', {}, {})".format(paytype, amount, tid) try: cursor = g.conn.execute(stmt) data = {'error':0, 'id':user_id} # if insert was successful, set corresponding trip status to completed stmt2 = "UPDATE Trips SET (status, prating) = (\'completed\', {}) WHERE tid={}".format(prating, tid) cursor = g.conn.execute(stmt2) return jsonify(data=data) except exc.SQLAlchemyError as e: print str(e) message = "Error entering trip information, check form entries." data = {'error':1, 'message':message, 'id':user_id} return jsonify(data=data)
def decorated_function(*args, **kwargs): try: results = f(*args, **kwargs) if 'redirect' in request.form: params = urllib.urlencode(results) return redirect( '%s?%s' % (request.form['redirect'], params), code=303) else: return jsonify(results=results) except AssertionError as ae: if 'redirect_error' in request.form: params = urllib.urlencode({'error': ae.args[0]}) return redirect( '%s?%s' % (request.form['redirect_error'], params), code=303) else: return jsonify(error=ae.args[0]), 400 except Exception as e: if 'redirect_error' in request.form: params = urllib.urlencode({'error': str(e)}) return redirect( '%s?%s' % (request.form['redirect_error'], params), code=303) raise e
def storymap_create(user): """Create a storymap""" try: title, data = _request_get_required('title', 'd') id = _make_storymap_id(user, title) key_prefix = storage.key_prefix(user['uid'], id) content = json.loads(data) storage.save_json(key_prefix+'draft.json', content) user['storymaps'][id] = { 'id': id, 'title': title, 'draft_on': _utc_now(), 'published_on': '' } _user.save(user) _write_embed_draft(key_prefix, user['storymaps'][id]) return jsonify({'id': id}) except Exception, e: traceback.print_exc() return jsonify({'error': str(e)})
def players(): if request.method == 'GET': i_data = db.session.query(Players).all() print i_data data=[] for j in i_data: a = {} a["id"] = j.ID a["name"] = j.name a["awards_no"] = j.awards_no a["date_of_birth"] = j.date_of_birth a["career_start_year"] = j.career_start_year a["career_end_year"] = j.career_end_year data.append(a) print a return jsonify({"data" : data}) else: data=request.json print "data" print data x = Players() x.id = data["id"] x.name = data["name"] x.awards_no = data["awards_no"] x.date_of_birth = data["date_of_birth"] x.career_start_year = data["career_start_year"] x.career_end_year = data["career_end_year"] print x db.session.add(x) db.session.commit() return jsonify({"success":"data added!"})
def charge(): stripe.api_key = "sk_test_GHr5dXDw5KyZXmEYUghkBezc" content = request.json print "**content" print content token = content['stripeToken'] amountInCents = content['amountInCents'] print content['meta'] try: charge = stripe.Charge.create( amount = amountInCents, currency = "usd", source = token, description = content['description'], metadata = content['meta'] ) print "charge*********" print charge return jsonify({"chargeID":charge.id}) except stripe.error.CardError as e: print "The card has been declined" body = e.json_body err = body['error'] print err print e return jsonify({"chargeID":"failed"})
def get_past_trips(): user_id = request.args.get('id') # get values from form start = request.args.get('start').rstrip() end = request.args.get('end').rstrip() # treat empty entries as open interval if (start == '' and end == ''): query = "SELECT P.name, to_char(T.date, \'YYYY-MM-DD\') AS date, to_char(T.time, \'HH:MI:SS\') AS time, T.est_amount, TR.amt_charged, T.drating, T.prating, T.tid FROM " + \ "Trips T, Transactions TR, Passengers P WHERE T.status='completed' AND T.tid=TR.tid AND T.driver={} AND T.passenger=P.uid".format(user_id) elif (start == ''): query = "SELECT P.name, to_char(T.date, \'YYYY-MM-DD\') AS date, to_char(T.time, \'HH:MI:SS\') AS time, T.est_amount, TR.amt_charged, T.drating, T.prating, T.tid FROM " + \ "Trips T, Transactions TR, Passengers P WHERE T.status='completed' AND t.tid=TR.tid AND T.passenger=P.uid AND " + \ "T.driver={} AND T.date <= \'{}\'".format(user_id, end) elif (end == ''): query = "SELECT P.name, to_char(T.date, \'YYYY-MM-DD\') AS date, to_char(T.time, \'HH:MI:SS\') AS time, T.est_amount, TR.amt_charged, T.drating, T.prating, T.tid FROM " + \ "Trips T, Transactions TR, Passengers P WHERE T.status='completed' AND t.tid=TR.tid AND T.passenger=P.uid AND " + \ "T.driver={} AND T.date >= \'{}\'".format(user_id, start) else: query = "SELECT P.name, to_char(T.date, \'YYYY-MM-DD\') AS date, to_char(T.time, \'HH:MI:SS\') AS time, T.est_amount, TR.amt_charged, T.drating, T.prating, T.tid FROM " + \ "Trips T, Transactions TR, Passengers P WHERE T.status='completed' AND t.tid=TR.tid AND T.passenger=P.uid AND " + \ "T.driver={} AND T.date >= \'{}\' AND T.date <= \'{}\'".format(user_id, start, end) try: cursor = g.conn.execute(query) trips = [] for row in cursor: trips.append(list(row)) data = {'error':0, 'id':user_id, 'trips':trips} # if insert was successful, set corresponding trip status to completed return jsonify(data=data) except exc.SQLAlchemyError as e: print str(e) message = "Error retrieving past trips, check date range formats." data = {'error':1, 'message':message, 'id':user_id} return jsonify(data=data)
def submit_message(): name = request.form.get("s","") email = request.form.get("email","") message = request.form.get("message2","") spam = request.form.get("message","") print "Name:", name print "Email:", email print "Message:", message print "Spam:", spam if spam: ip_addr = request.remote_addr with open("blacklist.txt","a") as blacklist: blacklist.write(ip_addr + "\n") return jsonify(success=True, message="Message sent.") if name and email and message: try: print "Sending mail..." send_mail(name=name, email=email, message=message) response = jsonify(success=True, message="Message sent.") except Exception as e: response = jsonify(success=False, message="Message failed to send.") return response else: return jsonify(success=False, message="Message failed to send.")
def delete_vehicle(): user_id = request.args.get('id') # get plate from form vplate = request.args.get('vplate').rstrip() # check whether car exists and belongs to user stmt = "SELECT uid FROM Vehicles V WHERE V.plate_no=\'{}\'".format(vplate) try: cursor=g.conn.execute(stmt) record = cursor.fetchone() if (record == None): message = "Error: no vehicle matches entered license plate." data = {'error':1, 'message':message, 'id':user_id} return jsonify(data=data) elif (str(record[0]) != str(user_id)): message = "Error: you can't delete a vehicle that doesn't belong to you!" data = {'error':1, 'message':message, 'id':user_id} return jsonify(data=data) else: stmt = "DELETE FROM Vehicles V WHERE V.plate_no=\'{}\'".format(vplate) cursor = g.conn.execute(stmt) data = {'error':0, 'id':user_id} return jsonify(data=data) except exc.SQLAlchemyError as e: print str(e) message = "Error deleting vehicle, check form entry." data = {'error':1, 'message':message, 'id':user_id} return jsonify(data=data)
def delete_sslprofile(): data = {} return jsonify(data)
def properties(): return jsonify([c.name for c in meta.tables['all_data'].columns][5:])
def countries(): result = engine.execute("select * from v_countries") return jsonify([row.country for row in result])
def years(): result = engine.execute("select * from v_years") year_list = [row.year for row in result] # years_dict = {'years' : year_list} return jsonify(year_list)
def delete_tenant(): data = {} return jsonify(data)
def delete_vsvip(): data = {} return jsonify(data)
def delete_persistenceprofile(): data = {} return jsonify(data)
def delete_cloud(): data = {} return jsonify(data)
def main(): d = {"csrftoken": "DEpq2MIeXMDcn5V5sazJSTghNCtgzdRv ", "sessionid": "mfxw1q6qyftghyl92rq04a3fpqqq0iny"} return jsonify(d)
def delete_healthmonitor(): data = {} return jsonify(data)
def post(self): event = eventParser.parse_args() inserted_id = self.mongo.db.events.insert_one(event).inserted_id return jsonify({"_id": inserted_id})
def login(): res = { "user_initialized": True, "system_config": { "url": "/api/systemconfiguration", "uuid": "default", "_last_modified": "1523857332750138", "email_configuration": { "from_email": "*****@*****.**", "mail_server_port": 25, "smtp_type": "SMTP_LOCAL_HOST", "mail_server_name": "localhost" }, "global_tenant_config": { "se_in_provider_context": True, "tenant_access_to_provider_se": True, "tenant_vrf": False }, "dns_configuration": { "search_domain": "" }, "ssh_hmacs": ["*****@*****.**", "*****@*****.**", "*****@*****.**", "hmac-sha2-512"], "docker_mode": False, "snmp_configuration": { "version": "SNMP_VER2", "sys_contact": "*****@*****.**", "community": "<sensitive>" }, "portal_configuration": { "use_uuid_from_input": False, "redirect_to_https": True, "sslprofile_ref": "/api/sslprofile/sslprofile-2ddfaff4-ce10-481c-b134-8849614f3159", "sslkeyandcertificate_refs": ["/api/sslkeyandcertificate/sslkeyandcertificate-865b7e54-3aaf-4f7d-ac27-55d53a605abc", "/api/sslkeyandcertificate/sslkeyandcertificate-4913d6d9-2c2c-4964-9d25-e0d7063da264"], "enable_clickjacking_protection": True, "enable_https": True, "disable_remote_cli_shell": False, "password_strength_check": False, "enable_http": True, "allow_basic_authentication": False }, "ntp_configuration": { "ntp_servers": [{ "server": { "type": "DNS", "addr": "0.us.pool.ntp.org" } }, { "server": { "type": "DNS", "addr": "1.us.pool.ntp.org" } }, { "server": { "type": "DNS", "addr": "2.us.pool.ntp.org" } }, { "server": { "type": "DNS", "addr": "3.us.pool.ntp.org" } }] }, "ssh_ciphers": ["aes128-ctr", "aes256-ctr", "arcfour256", "arcfour128"], "default_license_tier": "ENTERPRISE_18" }, "controller": { "api_idle_timeout": 15 }, "version": { "Product": "controller", "Version": "17.2.8", "build": 9022, "Tag": "17.2.8-9022-20180329.172906", "Date": "2018-03-29T17:29:06+00:00", "min_version": 15.2, "ProductName": "Avi Cloud Controller" }, "user": { "username": "******", "name": "admin", "is_superuser": True, "full_name": "System Administrator", "ui_property": "{\"defaultTimeframe\":\"6h\",\"valuesToDisplay\":\"avg\",\"sideRailOpen\":true,\"logs\":{\"savedSearch\":[],\"sidebarActiveTab\":\"1\"},\"appDashboard\":{\"viewType\":\"list\"},\"grid\":{\"pageSize\":30}}", "local": True, "email": "", "default_tenant_ref": "https://10.10.28.91/api/tenant/admin#admin" }, "tenants": [{ "url": "https://10.10.28.91/api/tenant/admin#admin", "uuid": "admin", "name": "admin", "local": True }, { "url": "https://10.10.28.91/api/tenant/tenant-ddf3c372-3b94-4235-9745-246e10fbafbc#avinetworks", "uuid": "tenant-ddf3c372-3b94-4235-9745-246e10fbafbc", "name": "avinetworks", "_last_modified": "1523857471333603", "config_settings": { "se_in_provider_context": True, "tenant_access_to_provider_se": True, "tenant_vrf": False }, "local": True }, { "url": "https://10.10.28.91/api/tenant/tenant-9d97ae61-950e-4c1b-ac8b-567d82b8311f#webapp", "uuid": "tenant-9d97ae61-950e-4c1b-ac8b-567d82b8311f", "name": "webapp", "_last_modified": "1523857474301593", "config_settings": { "se_in_provider_context": True, "tenant_access_to_provider_se": True, "tenant_vrf": False }, "local": True }] } return jsonify(res)
def to_json_message(self): return jsonify({ "positive": "{:.8f}".format(float(self.positive)), "negative": "{:.8f}".format(float(self.negative)), "neutral": "{:.8f}".format(float(self.neutral)) })
def create_virtualservice(): responce = { "url": "https://10.10.28.91/api/virtualservice/virtualservice-e5d922ed-1392-4c2d-80d7-0cea5bc378a3#Test-vs", "uuid": "virtualservice-e5d922ed-1392-4c2d-80d7-0cea5bc378a3", "name": "Test-vs", "enabled": True, "application_profile_ref": "https://10.10.28.91/api/applicationprofile/applicationprofile-053aaf82-24d2-4e59-95e4-760e8954d963#System-HTTP", "se_group_ref": "https://10.10.28.91/api/serviceenginegroup/serviceenginegroup-f32c5b36-5984-40e8-a86c-096e8c4d32af#Default-Group", "vrf_context_ref": "https://10.10.28.91/api/vrfcontext/vrfcontext-2687e8a8-7e2c-40cd-a5aa-48e1893481be#global", "analytics_profile_ref": "https://10.10.28.91/api/analyticsprofile/analyticsprofile-badbc9ce-8585-43aa-821d-45716e72d01c#System-Analytics-Profile", "tenant_ref": "https://10.10.28.91/api/tenant/tenant-ddf3c372-3b94-4235-9745-246e10fbafbc#avinetworks", "cloud_ref": "https://10.10.28.91/api/cloud/cloud-a1c23bff-deae-4e4b-b530-5fbeb9914adb#Test-vcenter-cloud", "vsvip_ref": "https://10.10.28.91/api/vsvip/vsvip-b1ccce54-974c-4573-b363-a5dd23a9d451#vsvip-aherrE", "_last_modified": "1523857513193459", "network_profile_ref": "https://10.10.28.91/api/networkprofile/networkprofile-0d027197-0131-4496-89cd-b506877f255c#System-TCP-Proxy", "weight": 1, "flow_dist": "LOAD_AWARE", "delay_fairness": False, "vip": [{ "vip_id": "myvip", "avi_allocated_fip": False, "auto_allocate_ip": False, "enabled": True, "auto_allocate_floating_ip": False, "avi_allocated_vip": False, "ip_address": { "type": "V4", "addr": "10.90.20.52" } }], "cloud_type": "CLOUD_NONE", "scaleout_ecmp": False, "max_cps_per_client": 0, "traffic_enabled": True, "type": "VS_TYPE_NORMAL", "bulk_sync_kvcache": False, "use_bridge_ip_as_vip": False, "active_standby_se_tag": "ACTIVE_STANDBY_SE_1", "use_vip_as_snat": False, "services": [{ "enable_ssl": False, "port_range_end": 80, "port": 80 }, { "enable_ssl": False, "port_range_end": 443, "port": 443 }], "pool_ref": "https://10.10.28.91/api/pool/pool-53d52b3c-d36d-4136-8ad4-9d217956e205#my-test-pool", "ign_pool_net_reach": False, "east_west_placement": False, "limit_doser": False, "ssl_sess_cache_avg_size": 1024, "enable_autogw": True, "remove_listening_port_on_vs_down": False, "close_client_conn_on_config_update": False, "flow_label_type": "NO_LABEL", "vip_runtime": [{ "num_additional_se": 0, "vip_id": "myvip", "requested_resource": { "num_se": 1, "num_standby_se": 0 } }], "tls_ticket_key": [{ "hmac_key": "yeRXvVlB2SzDaZF+du4Wyg==", "name": "d3ea53c7-9b22-4bfd-807f-66e27037e117", "aes_key": "2uEFgkzrauN//GWZhpAirg==" }, { "hmac_key": "Rr5zuHyC/dK7gy5O7PVBkA==", "name": "a851ff6b-7926-48f3-8770-4707d80d2e68", "aes_key": "fXFVcfDWZACLYNjW1EgEKA==" }, { "hmac_key": "PfY4Cn7TiHEr4vU0a/FTTQ==", "name": "a3ae9f3b-46b4-4732-b4f9-64fe2c56cebf", "aes_key": "A6S7elkfgHYNJrGSYbY2iw==" }], "redis_ip": "127.0.0.1", "redis_db": 8, "version": 9, "redis_port": 5023, "network_profile_ref_data": { "profile": { "tcp_proxy_profile": { "receive_window": 64, "time_wait_delay": 2000, "cc_algo": "CC_ALGO_NEW_RENO", "nagles_algorithm": False, "max_syn_retransmissions": 8, "ignore_time_wait": False, "use_interface_mtu": True, "idle_connection_type": "KEEP_ALIVE", "aggressive_congestion_avoidance": False, "idle_connection_timeout": 600, "max_retransmissions": 8, "automatic": True, "ip_dscp": 0 }, "type": "PROTOCOL_TYPE_TCP_PROXY" }, "url": "https://10.10.28.91/api/networkprofile/networkprofile-0d027197-0131-4496-89cd-b506877f255c#System-TCP-Proxy", "tenant_ref": "https://10.10.28.91/api/tenant/admin#admin", "uuid": "networkprofile-0d027197-0131-4496-89cd-b506877f255c", "name": "System-TCP-Proxy" }, "application_profile_ref_data": { "uuid": "applicationprofile-053aaf82-24d2-4e59-95e4-760e8954d963", "url": "https://10.10.28.91/api/applicationprofile/applicationprofile-053aaf82-24d2-4e59-95e4-760e8954d963#System-HTTP", "type": "APPLICATION_PROFILE_TYPE_HTTP", "tenant_ref": "https://10.10.28.91/api/tenant/admin#admin", "http_profile": { "max_rps_uri": 0, "keepalive_header": False, "max_rps_cip_uri": 0, "x_forwarded_proto_enabled": False, "connection_multiplexing_enabled": False, "websockets_enabled": True, "enable_request_body_buffering": True, "hsts_enabled": False, "compression_profile": { "compressible_content_ref": "https://10.10.28.91/api/stringgroup/stringgroup-2a9f6a6f-137d-49e1-8eaa-f36f751efce3#System-Compressible-Content-Types", "type": "AUTO_COMPRESSION", "compression": False, "remove_accept_encoding_header": True }, "xff_enabled": True, "disable_keepalive_posts_msie6": True, "keepalive_timeout": 30000, "ssl_client_certificate_mode": "SSL_CLIENT_CERTIFICATE_NONE", "http_to_https": False, "spdy_enabled": False, "respond_with_100_continue": True, "client_body_timeout": 30000, "httponly_enabled": False, "hsts_max_age": 365, "max_bad_rps_cip": 0, "server_side_redirect_to_https": False, "client_max_header_size": 12, "client_max_request_size": 48, "cache_config": { "min_object_size": 100, "query_cacheable": False, "xcache_header": True, "age_header": True, "enabled": False, "default_expire": 600, "max_cache_size": 0, "heuristic_expire": False, "date_header": True, "aggressive": False, "max_object_size": 4194304, "mime_types_group_refs": ["https://10.10.28.91/api/stringgroup/stringgroup-0c596eae-3b10-4727-bd32-d2c48ffabcb0#System-Cacheable-Resource-Types"] }, "max_rps_unknown_uri": 0, "ssl_everywhere_enabled": False, "spdy_fwd_proxy_mode": False, "allow_dots_in_header_name": False, "client_header_timeout": 10000, "post_accept_timeout": 30000, "secure_cookie_enabled": False, "max_response_headers_size": 48, "xff_alternate_name": "X-Forwarded-For", "max_rps_cip": 0, "client_max_body_size": 0, "enable_fire_and_forget": False, "max_rps_unknown_cip": 0, "max_bad_rps_cip_uri": 0, "max_bad_rps_uri": 0, "use_app_keepalive_timeout": False }, "preserve_client_port": False, "preserve_client_ip": False, "name": "System-HTTP" }, "pool_ref_data": { "lb_algorithm": "LB_ALGORITHM_LEAST_CONNECTIONS", "use_service_port": False, "server_auto_scale": False, "host_check_enabled": False, "tenant_ref": "https://10.10.28.91/api/tenant/tenant-ddf3c372-3b94-4235-9745-246e10fbafbc#avinetworks", "rewrite_host_header_to_sni": False, "capacity_estimation": False, "servers": [{ "ratio": 1, "ip": { "type": "V4", "addr": "10.90.20.12" }, "hostname": "10.90.20.12", "enabled": True, "verify_network": True, "static": False, "resolve_server_by_dns": False, "rewrite_host_header": False }], "fewest_tasks_feedback_delay": 10, "rewrite_host_header_to_server_name": False, "lookup_server_by_name": False, "uuid": "pool-53d52b3c-d36d-4136-8ad4-9d217956e205", "cloud_ref": "https://10.10.28.91/api/cloud/cloud-a1c23bff-deae-4e4b-b530-5fbeb9914adb#Test-vcenter-cloud", "lb_algorithm_core_nonaffinity": 2, "vrf_ref": "https://10.10.28.91/api/vrfcontext/vrfcontext-2687e8a8-7e2c-40cd-a5aa-48e1893481be#global", "application_persistence_profile_ref": "https://10.10.28.91/api/applicationpersistenceprofile/applicationpersistenceprofile-d6a3f83b-b4d1-48ee-a751-9cc3679c816c#Test-Persistece-Profile", "inline_health_monitor": True, "default_server_port": 80, "request_queue_depth": 128, "graceful_disable_timeout": 1, "server_count": 1, "sni_enabled": True, "request_queue_enabled": False, "name": "my-test-pool", "max_concurrent_connections_per_server": 0, "url": "https://10.10.28.91/api/pool/pool-53d52b3c-d36d-4136-8ad4-9d217956e205#my-test-pool", "enabled": True, "health_monitor_refs": ["https://10.10.28.91/api/healthmonitor/healthmonitor-1b17c992-2004-4670-9f05-f267c99fc19a#Test-Healthmonitor"], "connection_ramp_duration": 10 }, "cloud_ref_data": { "vtype": "CLOUD_NONE", "license_tier": "ENTERPRISE_18", "uuid": "cloud-a1c23bff-deae-4e4b-b530-5fbeb9914adb", "enable_vip_static_routes": False, "url": "https://10.10.28.91/api/cloud/cloud-a1c23bff-deae-4e4b-b530-5fbeb9914adb#Test-vcenter-cloud", "tenant_ref": "https://10.10.28.91/api/tenant/admin#admin", "mtu": 1300, "state_based_dns_registration": True, "prefer_static_routes": False, "license_type": "LIC_CORES", "apic_mode": False, "dhcp_enabled": False, "name": "Test-vcenter-cloud" }, "vsvip_ref_data": { "east_west_placement": False, "uuid": "vsvip-b1ccce54-974c-4573-b363-a5dd23a9d451", "url": "https://10.10.28.91/api/vsvip/vsvip-b1ccce54-974c-4573-b363-a5dd23a9d451#vsvip-aherrE", "tenant_ref": "https://10.10.28.91/api/tenant/tenant-ddf3c372-3b94-4235-9745-246e10fbafbc#avinetworks", "cloud_ref": "https://10.10.28.91/api/cloud/cloud-a1c23bff-deae-4e4b-b530-5fbeb9914adb#Test-vcenter-cloud", "vip": [{ "vip_id": "myvip", "avi_allocated_fip": False, "auto_allocate_ip": False, "enabled": True, "auto_allocate_floating_ip": True, "avi_allocated_vip": True, "ip_address": { "type": "V4", "addr": "10.90.20.52" } }], "vrf_context_ref": "https://10.10.28.91/api/vrfcontext/vrfcontext-2687e8a8-7e2c-40cd-a5aa-48e1893481be#global", "name": "vsvip-aherrE" }, "shared_vs_refs": [] } return jsonify(responce)
def job_catalog(): return jsonify({ "tasks": current_app.config.get('catalog', {}).keys() })
def get(self): return jsonify(list(self.mongo.db.events.find()))
def get_job(uuid): for job in sched.list_jobs(): if job['id'] == uuid: return jsonify(**job), 200 return error('No job with id %s found' % uuid), 404
def handle_invalid_usage(error): response = jsonify(error.to_dict()) response.status_code = error.status_code return response
def posts_index(): posts = Post.query.all() print(posts) pschema = posts_schema.dump(posts) print(pschema) return jsonify(pschema)
def error(message): return jsonify(**{ "description": message })
def getCountriesConfig(): return jsonify(MediationConfig.getCountries())
def list_jobs(): return jsonify(**{ "values": sched.list_jobs() })
def bad_request(error): return jsonify({ "success": False, "error": 400, "message": "bad request" }), 400
def all_surveys(): results = get_all_surveys() if isinstance(results, list): return jsonify({'status': 'ok', 'data': results}), 200 return jsonify({'status': 'ok', 'data': 'No surveys in database'}), 200
def not_found(error): return jsonify({ "success": False, "error": 404, "message": "Resource not found" }), 404
def internal_error(error): return jsonify({ "success": False, "error": 500, "message": "internal server error" })
def forbidden(e): return jsonify({ "message": "Endpoint Not Found", "error": str(e), "data": None }), 404
def unprocessable(error): return jsonify({ "success": False, "error": 422, "message": "unprocessable" }), 422
def forbidden(e): return jsonify({ "message": "Forbidden", "error": str(e), "data": None }), 403
def amenity_id(amenity_id): """Retrieves a Amenity object""" my_amenity = storage.get('Amenity', amenity_id) if my_amenity is None: abort(404) return jsonify(my_amenity.to_dict())