def call_user(): """ Makes a phone call to a user. Required Params: userPhone campaignId Optional Params: zipcode repIds fftfCampaign fftfReferer fftfSession """ # parse the info needed to make the call params, campaign = parse_params(request) if not params or not campaign: abort(404) # initiate the call try: call = app.config['TW_CLIENT'].calls.create( to=params['userPhone'], from_=random.choice(campaign['numbers']), url=full_url_for("connection", **params), if_machine='Hangup' if campaign.get('call_human_check') else None, timeLimit=app.config['TW_TIME_LIMIT'], timeout=app.config['TW_TIMEOUT'], status_callback=full_url_for("call_complete_status", **params)) result = jsonify(message=call.status, debugMode=app.debug) result.status_code = 200 if call.status != 'failed' else 500 except TwilioRestException, err: result = jsonify(message=err.msg.split(':')[1].strip()) result.status_code = 200
def post(self): args = parser.parse_args(strict = True) img_path = os.path.expanduser(args['img_path']) if os.path.isfile(img_path): if img_path.lower().find('.png') > 0 or img_path.lower().find('.jpg') > 0 or img_path.lower().find('.jpeg') > 0: aug_gen = prep_from_image(img_path, img_dim, project['augmentations']) pred_list, predicted = multi_predict(aug_gen, models, project['architecture']) pred_list = [[float(p) for p in pred] for pred in list(pred_list)] result = {'weights': project[weights], 'image_path': img_path, 'predicted': project['categories'][np.argmax(predicted)], 'classes': project['categories'], 'class_predictions': pred_list} return jsonify(result) else: return 'File must be a jpeg or png: ' + args['img_path'] elif os.path.isdir(img_path): result = [] for aug_gen, file_name in gen_from_directory(img_path, img_dim, project): pred_list, predicted = multi_predict(aug_gen, models, project['architecture']) pred_list = [[float(p) for p in pred] for pred in list(pred_list)] result.append({'weights': project[weights], 'image_path': file_name, 'predicted': project['categories'][np.argmax(predicted)], 'classes': project['categories'], 'class_predictions': pred_list}) if len(result) > 0: return jsonify(result) else: return 'No images found in directory: ' + args['img_path'] else: return 'Image does not exist locally: ' + args['img_path']
def call_user(): """ Makes a phone call to a user. Required Params: userPhone campaignId Optional Params: zipcode repIds """ # parse the info needed to make the call params, campaign = parse_params(request) if not params or not campaign: abort(404) # initiate the call try: call = app.config["TW_CLIENT"].calls.create( to=params["userPhone"], from_=random.choice(campaign["numbers"]), url=full_url_for("connection", **params), timeLimit=app.config["TW_TIME_LIMIT"], timeout=app.config["TW_TIMEOUT"], status_callback=full_url_for("call_complete_status", **params), ) result = jsonify(message=call.status, debugMode=app.debug) result.status_code = 200 if call.status != "failed" else 500 except TwilioRestException, err: result = jsonify(message=err.msg) # result = jsonify(message=err.msg.split(':')[1].strip()) result.status_code = 500
def recent_calls(): @after_this_request def add_expires_header(response): expires = datetime.utcnow() expires = expires + timedelta(seconds=60) expires = datetime.strftime(expires, "%a, %d %b %Y %H:%M:%S GMT") response.headers['Expires'] = expires return response campaign = request.values.get('campaign', 'default') since = request.values.get('since', datetime.utcnow() - timedelta(days=1)) limit = request.values.get('limit', 50) calls = call_list(campaign, since, limit) serialized_calls = [] if not calls: return jsonify(campaign=campaign, calls=[], count=0) for c in calls: s = dict(timestamp = c.timestamp.isoformat(), number = '%s-%s-XXXX' % (c.areacode, c.exchange)) member = data.get_legislator_by_id(c.member_id) if member: s['member'] = dict( title=member['title'], firstname=member['firstname'], lastname=member['lastname'] ) serialized_calls.append(s) return jsonify(campaign=campaign, calls=serialized_calls, count=len(serialized_calls))
def stats(): password = request.values.get('password', None) campaign = request.values.get('campaign', 'default') if password == app.config['SECRET_KEY']: return jsonify(aggregate_stats(campaign)) else: return jsonify(error="access denied")
def get_groups(): """ Enpoint that returns groups from meetup api """ try: return jsonify({'result': MeetupUtils().get_all_groups()}) except Exception as e: return jsonify({'result': "There was an error" + str(e)})
def stats(): password = request.values.get("password", None) campaign = request.values.get("campaign", "default") if password == app.config["SECRET_KEY"]: return jsonify(aggregate_stats(campaign)) else: return jsonify(error="access denied")
def abortJSON(status, message=None): if message: current_app.logger.error(message) response = jsonify({'error': message}) else: response = jsonify({'error': status.description}) response.status_code = status.code return response
def get_test_runs_by_build_name(build_name): value = parse.unquote(build_name) if not value: return 'A build name must be specified', 400 start_date = _parse_datetimes(flask.request.args.get('start_date', None)) stop_date = _parse_datetimes(flask.request.args.get('stop_date', None)) datetime_resolution = flask.request.args.get('datetime_resolution', 'sec') if datetime_resolution not in ['sec', 'min', 'hour', 'day']: return ('Datetime resolution: %s, is not a valid' ' choice' % datetime_resolution), 400 @region.cache_on_arguments() def _query_test_runs_by_build_name(name, start_date, stop_date): with session_scope() as session: tests = api.get_test_run_dict_by_run_meta_key_value('build_name', name, start_date, stop_date, session) tests = test_run_aggregator.TestRunAggregator(tests).aggregate( datetime_resolution=datetime_resolution) return tests output = _query_test_runs_by_build_name(value, start_date, stop_date) return jsonify({'tests': output})
def get_runs(): start_date = _parse_datetimes(flask.request.args.get('start_date', None)) stop_date = _parse_datetimes(flask.request.args.get('stop_date', None)) with session_scope() as session: db_runs = api.get_all_runs_by_date(start_date, stop_date, session) runs = [run.to_dict() for run in db_runs] return jsonify({'runs': runs})
def get_runs_by_run_metadata_key(run_metadata_key, value): run_metadata_key = parse.unquote(run_metadata_key) value = parse.unquote(value) start_date = _parse_datetimes(flask.request.args.get('start_date', None)) stop_date = _parse_datetimes(flask.request.args.get('stop_date', None)) datetime_resolution = flask.request.args.get('datetime_resolution', 'day') if datetime_resolution not in ['sec', 'min', 'hour', 'day']: message = ('Datetime resolution: %s, is not a valid' ' choice' % datetime_resolution) status_code = 400 return abort(make_response(message, status_code)) with session_scope() as session: runs = (api.get_time_series_runs_by_key_value(run_metadata_key, value, start_date, stop_date, session)) # Groups runs by metadata group_by = "build_name" runs_by_build_name = _group_runs_by_key(runs, group_by) # Group runs by the chosen data_range. # That does not apply when you choose 'sec' since runs are already # grouped by it. aggregated_runs = \ RunAggregator(runs_by_build_name).aggregate(datetime_resolution) return jsonify(_aggregate_runs(aggregated_runs))
def eff_test(): callback_url = request.values.get("callback_url", None) meta = request.values.get("meta", None) if callback_url: t = Thread(target=open_website, args=[callback_url, meta]) t.daemon = True t.start() return jsonify(message="success")
def stats(): password = request.values.get('password', None) campaign = request.values.get('campaign', 'default') # if password == app.config['SECRET_KEY']: # return jsonify(aggregate_stats(campaign)) # else: # return jsonify(error="access denied") return jsonify(error="access denied") # JL HACK ~ disable mysql
def index(): gpio16Val = GPIO.input(16); gpio18Val = GPIO.input(18); # print 'GPIO16:{0} GPIO18:{1}'.format(gpio16Val,gpio18Val); # log_values (gpio16Val, gpio18Val); list = [ { 'param': 'gpioDown', 'val': gpio16Val }, { 'param': 'gpioUp', 'val': gpio18Val } ] return jsonify(results=list)
def get(self): now = int(time.time()) toTs = handleTs(request.args.get('to'), now) * 1000 fromTs = handleTs(request.args.get('from'), now) * 1000 topicstring = request.args.get('topics') amount = parseAmount(request.args.get('amount')) result = getTweetsForTopics(topicstring, amount, fromTs, toTs) return jsonify(result)
def get_tests_by_prefix(prefix): prefix = parse.unquote(prefix) limit = flask.request.args.get('limit', 100) offset = flask.request.args.get('offset', 0) with session_scope() as session: db_tests = api.get_tests_by_prefix(prefix, session, limit=limit, offset=offset) tests = [test.to_dict() for test in db_tests] return jsonify({'tests': tests})
def abortJSON(status, message=None): data = {'status': status.code} if message: current_app.logger.error(message) data['error'] = message else: data['error'] = status.name data['description'] = status.description response = jsonify(data) response.status_code = status.code return response
def random_data(): colors = list("colin") data = [{ "x": 20 * random.random(), "y": 20 * random.random(), "c": random.sample(colors, 1)[0], "size": random.randint(1, 5), "alpha": random.random(), } for _ in range(50)] return jsonify(data)
def get_recent_test_status(status): global region if not region: setup() status = parse.unquote(status) num_runs = flask.request.args.get('num_runs', 10) bug_dict = {} query_threads = [] def _populate_bug_dict(change_num, patch_num, short_uuid, run): bug_dict[run] = elastic_recheck_cached(change_num, patch_num, short_uuid) @region.cache_on_arguments() def _get_recent(status): with session_scope() as session: failed_runs = api.get_recent_failed_runs(num_runs, session) global classifier if classifier: for run in failed_runs: metadata = api.get_run_metadata(run, session=session) short_uuid = None change_num = None patch_num = None for meta in metadata: if meta.key == 'build_short_uuid': short_uuid = meta.value elif meta.key == 'build_change': change_num = meta.value elif meta.key == 'build_patchset': patch_num = meta.value # NOTE(mtreinish): If the required metadata fields aren't # present skip ES lookup if not short_uuid or not change_num or not patch_num: continue query_thread = threading.Thread( target=_populate_bug_dict, args=(change_num, patch_num, short_uuid, run)) query_threads.append(query_thread) query_thread.start() test_runs = api.get_test_runs_by_status_for_run_ids( status, failed_runs, session=session, include_run_id=True) output = [] for run in test_runs: run['start_time'] = run['start_time'].isoformat() run['stop_time'] = run['stop_time'].isoformat() output.append(run) for thread in query_threads: thread.join() return {'test_runs': output, 'bugs': bug_dict} results = _get_recent(status) return jsonify(results)
def auth(): if not self._auth_handler: abort(403) socket_id = request.form["socket_id"] channel_name = request.form.get("channel_name") if channel_name: response = self._auth_simple(socket_id, channel_name) if not response: abort(403) else: response = self._auth_buffered(socket_id) return jsonify(response)
def call_complete_status(): # asynch callback from twilio on call complete params, _ = parse_params(request) if not params: abort(404) return jsonify({ 'phoneNumber': request.values.get('To', ''), 'callStatus': request.values.get('CallStatus', 'unknown'), 'repIds': params['repIds'], 'campaignId': params['campaignId'] })
def list_routes(): output = [] for rule in app.url_map.iter_rules(): options = {} for arg in rule.arguments: options[arg] = "[{0}]".format(arg) url = flask.url_for(rule.endpoint, **options) out_dict = { 'name': rule.endpoint, 'methods': sorted(rule.methods), 'url': parse.unquote(url), } output.append(out_dict) return jsonify({'routes': output})
def count(): @after_this_request def add_expires_header(response): expires = datetime.utcnow() expires = expires + timedelta(seconds=60) expires = datetime.strftime(expires, "%a, %d %b %Y %H:%M:%S GMT") response.headers["Expires"] = expires return response campaign = request.values.get("campaign", "default") return jsonify(campaign=campaign, count=call_count(campaign))
def status_callback(): # async callback from twilio on call events params, _ = parse_params(request) if not params: abort(400) if not params.get('sessionId'): return jsonify({ 'phoneNumber': request.values.get('From', ''), 'callStatus': 'unknown', 'message': 'no sessionId passed, unable to update status', 'campaignId': params['campaignId'] }) if request.values.get('CallStatus') == 'ringing': # update call_session with time interval calculated in Twilio queue call_session = Session.query.get(request.values.get('sessionId')) call_session.queue_delay = datetime.utcnow() - call_session.timestamp db.session.add(call_session) db.session.commit() # CallDuration only present when call is complete # update call_session with status, duration if request.values.get('CallDuration'): call_session = Session.query.get(request.values.get('sessionId')) call_session.status = request.values.get('CallStatus', 'unknown') call_session.duration = request.values.get('CallDuration', None) db.session.add(call_session) db.session.commit() return jsonify({ 'phoneNumber': request.values.get('To', ''), 'callStatus': request.values.get('CallStatus'), 'targetIds': params['targetIds'], 'campaignId': params['campaignId'] })
def call_complete_status(): # asynch callback from twilio on call complete params, _ = parse_params(request) if not params: abort(404) return jsonify( { "phoneNumber": request.values.get("To", ""), "callStatus": request.values.get("CallStatus", "unknown"), "repIds": params["repIds"], "campaignId": params["campaignId"], } )
def status_inbound(): # async callback from twilio on inbound call complete params, campaign = parse_params(request, inbound=True) if not params: abort(400) # find call_session from number with direction inbound that is not complete # if there's more than one, get the most recent one user_phone = request.values.get('From', '') phone_hash = Session.hash_phone(user_phone) call_session = Session.query.filter_by( phone_hash=phone_hash, status='initiated', direction='inbound', campaign_id=campaign.id, location=params['userLocation'] ).order_by(desc(Session.timestamp)).first() if call_session: call_session.status = request.values.get('CallStatus', 'unknown') call_session.duration = request.values.get('CallDuration', None) db.session.add(call_session) db.session.commit() return jsonify({ 'phoneNumber': request.values.get('From', ''), 'callStatus': call_session.status, 'campaignId': params['campaignId'] }) else: return jsonify({ 'phoneNumber': request.values.get('From', ''), 'callStatus': 'unknown', 'message': 'unable to find CallSession matching campaign, location, and phone', 'campaignId': params['campaignId'] })
def get_status(): is_db_available = _check_db_availability() is_er_available = _check_er_availability() status = {'status': {'availability': { 'database': is_db_available, 'elastic-recheck': is_er_available }}} response = jsonify(status) if not is_db_available: response.status_code = 500 return response
def count(): @after_this_request def add_expires_header(response): expires = datetime.utcnow() expires = expires + timedelta(seconds=60) expires = datetime.strftime(expires, "%a, %d %b %Y %H:%M:%S GMT") response.headers['Expires'] = expires return response campaign = request.values.get('campaign', 'default') # return jsonify(campaign=campaign, count=call_count(campaign)) return jsonify('DISABLED') # JL HACK ~ disable mysql
def check_anagram(): first_string = request.args.get('first') second_string = request.args.get('second') status_code = status.HTTP_400_BAD_REQUEST # As long as both values were passed in the query string, check the anagram and return 200 if first_string is not None and second_string is not None: result = {'First String': first_string, 'Second String': second_string, 'isAnagram': str(check(first_string, second_string))} status_code = status.HTTP_200_OK # otherwise return a message in the response and a 400 code else: result = {'Error': 'Need values for first and second to be passed in the query string.'} return jsonify(result), status_code
def get_runs_grouped_by_metadata_per_datetime(key): key = parse.unquote(key) start_date = _parse_datetimes(flask.request.args.get('start_date', None)) stop_date = _parse_datetimes(flask.request.args.get('stop_date', None)) datetime_resolution = flask.request.args.get('datetime_resolution', 'sec') with session_scope() as session: sec_runs = api.get_all_runs_time_series_by_key(key, start_date, stop_date, session) if datetime_resolution not in ['sec', 'min', 'hour', 'day']: return ('Datetime resolution: %s, is not a valid' ' choice' % datetime_resolution), 400 runs = RunAggregator(sec_runs).aggregate(datetime_resolution) return jsonify({'runs': runs})
def get(self): result = {'data': [{'Count': len(m.Book.query.all())}]} return jsonify(result)
def uploaded_file(filename): print("in the uploaded_file") f = request.files[filename] print(f) return jsonify({'text': 'thaisdash'})
def get(self, username): user = m.User.query.filter_by(username=username).first() return jsonify(user.to_dict())
def get(self): users = len(m.User.query.all()) return jsonify({'data': [{'number': users}]})
def get(self, author_id): r = m.Author.query.filter_by(id=author_id).all() result = {'data': [x.to_dict() for x in r]} return jsonify(result)
def getAllResult(): result = Result.query.filter(Result.gehoert_zu == 100).first() dicti = result.__dict__ data = formatResult(dicti) return jsonify(data)
def get(self, book_title): r = m.Book.query.filter_by(title=book_title) result = {'data': [x.to_dict() for x in r]} return jsonify(result)
def diss(): return jsonify({'test': 'application'})
def disp(): return jsonify({'this': 'hello'})
def get(self, querystring, payload): projet = StartingNewProjet(querystring, payload) start = projet.run() return jsonify(start)
def get(self, employee_id): print('Employee id:' + employee_id) result = {'data': {'id': 1, 'name': 'Balram'}} return jsonify(result)
def hello(): return jsonify({'text': 'Hello World!'})
def name(): return jsonify(name=random.choice(lines))
def getResultArea(nr): result = Result.query.filter(Result.nr == nr).first() dicti = result.__dict__ data = formatResult(dicti) return jsonify(data)
def get(self, username): print(username) user = m.User.query.filter_by(username=username).first() token = user.generate_auth_token() return jsonify({ 'token': token.decode('ascii') })
def LoadExpression(): res = utilityMethod.load_expression_json() return jsonify(res)
def getAllParties(): result = Result.query.filter(Result.nr == 100).first() dicti = result.__dict__ data = formatResultParties(dicti) return jsonify(data)
def LoadWordIntent(): res = utilityMethod.load_word_intent() return jsonify(res)
def get(self, author_name): author_name = author_name.split(' ') r = m.Author.query.filter_by(firstName=author_name[0], lastName=author_name[-1]) result = {'data': [x.to_dict() for x in r]} return jsonify(result)
def ReTest(): res = utilityMethod.retest() return jsonify(res)
def get(self): r = m.Author.query.all() result = {'data': [x.to_dict() for x in r]} return jsonify(result)
def get(self, book_id, chapter_id): track = trackServer.getChapter(book_id, chapter_id) return jsonify(track)
def get(self, username): exists = m.User.query.filter_by(username=username).first() return jsonify({"data": [{"exists": exists==True}]})
def get(self): message = str("Service classifier by Andrea Corriga & Francesca Malloci") return jsonify(message)
def get(self, querystring, payload, id_projet): active = ActiverAudit(querystring, payload, id_projet) start = active.run() return jsonify(start)
def m1(): return jsonify({'hello':'world'})
def get(self, querystring, id_projet): execute = ExecuterAudit(querystring, id_projet) start = execute.run() return jsonify(start)
def get(self, querystring, id_projet): obtenir = ObtenirRapport(querystring, id_projet) start = obtenir.run() return jsonify(start)
def hello(): message = {'test': 'The API is working!'} return jsonify(message)
def get(self, book_id, user_id): track = userBookServer.getPickUpInformation(book_id, user_id) return jsonify(track)