def getTasks(): if not request.json: abort(400) if request.headers['Content-Type'] != 'application/json; charset=UTF-8': abort(400) username = request.json.get('username') if username not in session: return redirect('/') taskData = [] try: tasks = r.table('Tasks').filter({"username": username}).run(g.rdb_conn) for data in tasks: taskData.append(data) except RqlError: logging.warning('DB code verify failed on /api/getTasks/') resp = make_response(jsonify({"Error": "503 DB error"}), 503) resp.headers['Content-Type'] = "application/json" resp.cache_control.no_cache = True return resp taskData = dumps(taskData) resp = make_response(taskData, 200) resp.headers['Content-Type'] = "application/json" resp.cache_control.no_cache = True return resp
def deleteTask(): if not request.json: abort(400) if request.headers['Content-Type'] != 'application/json': abort(400) task_id = request.json.get('task_id') try: # r.table('UsersInfo').get(mobileNo).update({"smscode": SMScode}).run(g.rdb_conn) r.table('Tasks').get(task_id).delete().run(g.rdb_conn) except RqlError: logging.warning('DB code verify failed on /api/deleteTask/') payload = "LOG_INFO=" + simplejson.dumps({ '/editTask/<username>/<task_id>/':'DB operation failed on /editTask/<task_id>/' }) requests.post("https://logs-01.loggly.com/inputs/e15fde1a-fd3e-4076-a3cf-68bd9c30baf3/tag/python/", payload) resp = make_response(jsonify({"Error": "503 DB error"}), 503) resp.headers['Content-Type'] = "application/json" resp.cache_control.no_cache = True return resp resp = make_response(jsonify({"OK": "Task Deleted"}), 200) resp.headers['Content-Type'] = "application/json" resp.cache_control.no_cache = True return resp
def confirmUser(smscode): # make request to get one task if 'username' not in request.cookies: return redirect('/') username = request.cookies.get('username') try: user = r.table( 'UsersInfo').get(username).pluck('smscode').run(g.rdb_conn) r.table('UsersInfo').get(username).update({"userVerified": "yes"}) except RqlError: logging.warning('DB op failed on /confirmUser/') resp = make_response(jsonify({"Error": "503 DB error"}), 503) resp.headers['Content-Type'] = "application/json" resp.cache_control.no_cache = True return resp if str(user) is not str(smscode): return """ EMAIL VERFICATION FAILED """ return redirect("/task/createTask/", code=302)
def detail(): try: voice_one = r.hgetall('+254711082306') voice_two = r.hgetall('+254711082513') voice_three = r.hgetall('+254711082514') visitor = Visitor() visitor.ip_address = request.remote_addr session = Session() page = Page('/detail') event = Event('convertion', 'call') # category - action tracker.track_pageview(page, session, visitor) tracker.track_event(event, session, visitor) data = [voice_one, voice_two, voice_three] print data resp = make_response(render_template('detail.html', data=data)) resp.cache_control.no_cache = True return resp except Exception, e: logging.warning('failed on detail route') raise e
def categorize(model, category_ids, vectors, word): try: vector = model.get_vector(word) maxIndex = model.cosine_similarities(vector, vectors).argmax() return category_ids[maxIndex] except KeyError: logging.warning("word {} is not in vocabulary")
def getTasks(): if not request.json: abort(400) if request.headers['Content-Type'] != 'application/json': abort(400) username = request.json.get('username') taskData = [] try: tasks = r.table('Tasks').filter({"username": username}).run(g.rdb_conn) for data in tasks: taskData.append(data) except RqlError: payload = "LOG_INFO=" + simplejson.dumps({ 'Request':'app.before' }) requests.post("https://logs-01.loggly.com/inputs/e15fde1a-fd3e-4076-a3cf-68bd9c30baf3/tag/python/", payload) logging.warning('DB code verify failed on /api/getTasks/') resp = make_response(jsonify({"Error": "503 DB error"}), 503) resp.headers['Content-Type'] = "application/json" resp.cache_control.no_cache = True return resp taskData = dumps(taskData) resp = make_response(taskData, 200) resp.headers['Content-Type'] = "application/json" resp.cache_control.no_cache = True return resp
def addNewsLetter(): if not request.json: abort(400) if request.headers['Content-Type'] != 'application/json': abort(400) email = request.json.get('email') # mobile no is the id - primary key try: r.table('newsLetter').insert({ 'email': email, }).run(g.rdb_conn) except RqlError: logging.warning('DB could not write on /api/newsLetter/') resp = make_response(jsonify({'Error': 'Save Failed'}), 503) resp.headers['Content-Type'] = "application/json" resp.cache_control.no_cache = True return resp resp = make_response(jsonify({'OK': 'Content Saved'}), 202) resp.headers['Content-Type'] = "application/json" resp.cache_control.no_cache = True return resp
def taskInfo(task_id): if 'username' not in request.cookies: return redirect('/') if request.cookies.get('username') == '' or request.cookies.get('username') is None: return redirect('/') username = request.cookies.get('username') try: user = r.table('Tasks').get(task_id).run(g.rdb_conn) task_title = str(user['task_title']) task_desc = str(user['task_desc']) task_urgency = str(user['task_urgency']) task_category = str(user['task_category']) due_date = str(user['due_date']) contactPersons = str(user['contactPersons']) location = str(user['locationData']) except RqlError: logging.warning('DB operation failed on /editTask/<task_id>/') resp = make_response(jsonify({"Error": "503 DB error"}), 503) resp.headers['Content-Type'] = "application/json" resp.cache_control.no_cache = True return resp return render_template( 'EditTask.html', task_category=task_category, task_urgency=task_urgency, locationData=location, contactPersons=contactPersons, task_desc=task_desc, task_title=task_title, due_date=due_date, username=username, task_id=task_id)
def adminSign(): if request.method == 'POST': if not request.json: abort(400) if request.headers['Content-Type'] != 'application/json': abort(400) username = request.json.get('username') password = request.json.get('password') try: user = r.table('Admin').get(username).run(g.rdb_conn) except Exception, e: logging.warning('DB failed on /admin/ -> user not found') raise e if user is None: resp = make_response(jsonify({"Not Found": "User Not Found"}), 404) resp.headers['Content-Type'] = "application/json" resp.cache_control.no_cache = True return resp resp = make_response(jsonify({"OK": "Signed In"}), 200) resp.headers['Content-Type'] = "application/json" resp.cache_control.no_cache = True return resp
def getRandID(): if not request.json: abort(400) if request.headers['Content-Type'] != 'application/json': abort(400) # use the mobile number as the id number its a unique entity username = request.json.get('username') email = request.json.get('email') password = request.json.get('password') email = str(email) username = str(username) try: user = r.table('UsersInfo').get(username).run(g.rdb_conn) if user is not None: resp = make_response(jsonify({"Error": "User Exists"}), 400) resp.headers['Content-Type'] = "application/json" resp.cache_control.no_cache = True return resp user = r.table('UsersInfo').filter({"email": email}).limit(1).run(g.rdb_conn) if user is not None: resp = make_response(jsonify({"Error": "User Exists"}), 400) resp.headers['Content-Type'] = "application/json" resp.cache_control.no_cache = True return resp except RqlError: logging.warning('DB code verify failed on /api/signUp/') resp = make_response(jsonify({"Error": "503 DB error"}), 503) resp.headers['Content-Type'] = "application/json" resp.cache_control.no_cache = True return resp SMScode = randint(10000, 99999) # sendMail.sendMail(email, SMScode, username) hashed_password = hashlib.sha512(password + salt).hexdigest() try: r.table( 'UsersInfo').insert({"state": "", "username": username, "dob": "", "email": email, "password": hashed_password, "smscode": SMScode, "mobileNo": ""}).run(g.rdb_conn) except RqlError: logging.warning('DB code verify failed on /api/signUp/') resp = make_response(jsonify({"Error": "503 DB error"}), 503) resp.headers['Content-Type'] = "application/json" resp.cache_control.no_cache = True return resp resp = make_response(jsonify({"OK": "Signed Up"}), 202) resp.headers['Content-Type'] = "application/json" resp.cache_control.no_cache = True return resp
def editTask(task_id): if not request.json: abort(400) if request.headers['Content-Type'] != 'application/json; charset=UTF-8': abort(400) username = request.json.get('username') if username not in session: return redirect('/') task_urgency = request.json.get('task_urgency') task_title = request.json.get('title') task_desc = request.json.get('description') # task_category = request.json.get('category') due_date = request.json.get('due_date') task_id = request.json.get('task_id') locationData = request.json.get('locationData') contactPersons = request.json.get('contactPersons') # make request to get one task if request.method == 'GET': try: user_task = r.table('Tasks').get(task_id).run(g.rdb_conn) except RqlError: logging.warning('DB op failed on /api/editTask/') resp = make_response(jsonify({"Error": "503 DB error"}), 503) resp.headers['Content-Type'] = "application/json" resp.cache_control.no_cache = True return resp resp = make_response(jsonify({"Task fetched": user_task}), 202) resp.headers['Content-Type'] = "application/json" resp.cache_control.no_cache = True return resp try: r.table( 'Tasks').get(task_id).update({'task_desc': task_desc, 'task_title': task_title, 'task_urgency': task_urgency, 'due_date': due_date, "locationData": locationData, 'contactPersons': contactPersons }).run(g.rdb_conn) except RqlError: logging.warning('DB code verify failed on /api/editTask/') resp = make_response(jsonify({"Error": "503 DB error"}), 503) resp.headers['Content-Type'] = "application/json" resp.cache_control.no_cache = True return resp resp = make_response(jsonify({"OK": "Task Updated"}), 202) resp.headers['Content-Type'] = "application/json" resp.cache_control.no_cache = True return resp
def credit(username): if username not in session: return redirect("/") if request.method == "GET": if not request.json: abort(400) if request.headers["Content-Type"] != "application/json; charset=UTF-8": abort(400) password = request.json.get("password") username = request.json.get("username") try: user = r.table("Payments").get(str(username)).pluck("credit_available").run(g.rdb_conn) credit = json.dumps(user) resp = make_response(jsonify(credit), 202) resp.headers["Content-Type"] = "application/json" resp.cache_control.no_cache = True return resp except RqlError: logging.warning("DB code verify failed on /api/credit" + username) resp = make_response(jsonify({"Error": "503 DB error"}), 503) resp.headers["Content-Type"] = "application/json" resp.cache_control.no_cache = True return resp if request.method == "POST": if not request.json: abort(400) if request.headers["Content-Type"] != "application/json; charset=UTF-8": abort(400) password = request.json.get("password") username = request.json.get("username") try: user = r.table("Payments").get(str(username)).pluck("credit_available").run(g.rdb_conn) resp = make_response(jsonify({"OK": "User Updated"}), 202) resp.headers["Content-Type"] = "application/json" resp.cache_control.no_cache = True return resp except RqlError: logging.warning("DB code verify failed on /api/credit" + username) resp = make_response(jsonify({"Error": "503 DB error"}), 503) resp.headers["Content-Type"] = "application/json" resp.cache_control.no_cache = True return resp
def ga(): data = main() print data try: resp = make_response(render_template('ga.html', data=data)) resp.cache_control.no_cache = True return resp except Exception, e: logging.warning('Failed on -> /') raise e
def _set_namespaces(self, groups): """Search and set the requested GitLab namespaces (groups) to work with. In case the namespace code is not found within GitLab, an alert will be outputted. """ if groups: for group_id in groups: try: self.namespaces[group_id] = self.gl.groups.get(group_id) except gitlab.exceptions.GitlabGetError: logging.warning(f"GitLab group '{group_id}' not found.")
def _set_namespaces(self, namespaces): """Search and set the requested Github namespaces (orgs) to work with. In case the namespace name is not found within Github, an alert will be outputted. """ if namespaces: for org_name in namespaces: try: self.namespaces[org_name] = self.gh.get_organization(org_name) except github.UnknownObjectException: logging.warning(f"Github org '{org_name}' not found.")
def _connect(self): gh = Github(os.getenv("GITHUB_TOKEN")) try: gh.get_user().login except github.GithubException as e: logging.warning(f'No valid GitHub token entered, authentication failed: {e}.') return except github.BadCredentialsException as e: logging.warning(f'GitHub User authentication failed: {e}.') return return gh
def _set_personal_users(self, users): """Search and set the requested GitLab users to work with their personal repos. In case the username is not found within GitLab, an alert will be outputted. """ if users: for username in users: try: self.users[username] = self.gl.users.list(username=username)[0] except IndexError: logging.warning(f"GitLab user '{username}' not found.")
def index(): """ render index page :return: index template """ # join to another table try: resp = make_response(render_template('index.html')) resp.cache_control.no_cache = True return resp except Exception, e: logging.warning('Failed on -> /') raise e
def getAdminTasks(): if request.method == 'POST': if not request.json: abort(400) if request.headers['Content-Type'] != 'application/json; charset=UTF-8': abort(400) # add to sessions then login if 'username' not in request.cookies: return redirect('/') username = request.cookies.get('username') if request.cookies.get('username') == '' or request.cookies.get('username') is None: return redirect('/') taskData = [] try: tasks = r.table('Tasks').filter( {'task_urgency': 'started'}).limit(50).run(g.rdb_conn) for data in tasks: taskData.append(data) except RqlError: logging.warning('DB code verify failed on /api/adminTasks/') resp = make_response(jsonify({"Error": "503 DB error"}), 503) resp.headers['Content-Type'] = "application/json" resp.cache_control.no_cache = True return resp taskData = dumps(taskData) resp = make_response(taskData, 200) resp.headers['Content-Type'] = "application/json" resp.cache_control.no_cache = True return resp try: task_size = r.table('Tasks').count().run(g.rdb_conn) except RqlError: logging.warning('DB code verify failed on /api/adminTasks/') resp = make_response(jsonify({"Error": "503 DB error"}), 503) resp.headers['Content-Type'] = "application/json" resp.cache_control.no_cache = True return resp return render_template('adminViewTasks.html', task_size=task_size)
def _cleanViews(self): ''' Load relevant mysql views and drop them ''' # iterate on each db to get the list of triggers for database_name in self.what_to_handle['w']: self.cnx.database = database_name self.cursor.execute("SHOW FULL TABLES IN {} WHERE TABLE_TYPE LIKE 'VIEW'".format(database_name)) for view_name in [view for (view,*_) in self.cursor]: sql = "DROP VIEW {db}.{name}".format(db=database_name,name=view_name) L.debug(sql) if(self.args.dry_run): L.warning("Dry dropping view {db}.{name}".format(db=database_name,name=view_name)) else: self.cursor.execute(sql)
def _cleanTriggers(self): ''' Load relevant mysql triggers and drop them ''' # iterate on each db to get the list of triggers for database_name in self.what_to_handle['t']: self.cnx.database = database_name self.cursor.execute("SHOW TRIGGERS") for trigger_name in [trigger for (trigger,*_) in self.cursor]: sql = "DROP TRIGGER {db}.{name}".format(db=database_name,name=trigger_name) L.debug(sql) if(self.args.dry_run): L.warning("Dry dropping function {db}.{name}".format(db=database_name,name=trigger_name)) else: self.cursor.execute(sql)
def get_ccs(self, status='open'): """Pulls and yield CC from the requested Gerrit's namespaces using an SSH command. skip: Number of changes to skip. result_cnt: Keeping count of the number of results left to return. cc_content: Outputted JSON of CC from the ssh command. lines: Line-separated JSON copy of cc_content. patch: One gerrit CC. """ for project in self.namespaces: skip = 0 results_cnt = self.query_limit gerrit_identity_file = os.getenv("GERRIT_IDENTITY_FILE") if not gerrit_identity_file: logging.warning( 'No identity file found for Gerrit. Please set "GERRIT_IDENTITY_FILE to be the path to the identity file' ) continue while results_cnt >= self.query_limit: cc_content = check_output([ 'ssh', self.host, '-p', '29418', '-i', gerrit_identity_file, 'gerrit', 'query', '--comments', '--all-approvals', '--format=JSON', '--start', str(skip), 'limit:' + str(self.query_limit), 'project:' + project, 'status:' + status, ]) lines = cc_content.splitlines() for line in lines: patch = json.loads(line) if patch.get('type') == 'stats' or patch.get('owner').get( 'name') in self.bot_users: continue # ignore output stats query yield patch results_cnt = len(lines) - 1 skip += results_cnt
def signIn(): if not request.json: abort(400) if request.headers['Content-Type'] != 'application/json': abort(400) password = request.json.get('password') username = request.json.get('username') email = request.json.get('email') try: user = r.table('UsersInfo').get(username).run(g.rdb_conn) except Exception, e: logging.warning('DB signIn failed on /api/signIn/ - user Not Found') raise e
def _cleanSP(self): ''' Load relevant stored procedures and drop them ''' # first load stored procedures sql = "SHOW PROCEDURE STATUS WHERE Db NOT IN(" +self.ignore_dbs_str + ") " sql += "AND Db IN('" + "','".join(self.what_to_handle['s']) + "')" L.debug(sql) self.cursor.execute(sql) res = [(Db,Name) for (Db,Name,*_) in self.cursor] for sp in res: sql = "DROP PROCEDURE {db}.{name}".format(db=sp[0],name=sp[1]) L.debug(sql) if(self.args.dry_run): L.warning("Dry dropping sp {db}.{name}".format(db=sp[0],name=sp[1])) else: self.cursor.execute(sql)
def _cleanTriggers(self): ''' Load relevant mysql triggers and drop them ''' # iterate on each db to get the list of triggers for database_name in self.what_to_handle['t']: self.cnx.database = database_name self.cursor.execute("SHOW TRIGGERS") for trigger_name in [trigger for (trigger, *_) in self.cursor]: sql = "DROP TRIGGER {db}.{name}".format(db=database_name, name=trigger_name) L.debug(sql) if (self.args.dry_run): L.warning("Dry dropping function {db}.{name}".format( db=database_name, name=trigger_name)) else: self.cursor.execute(sql)
def _cleanFunctions(self): ''' Load relevant mysql functions and drop them ''' # first load functions sql = "SHOW FUNCTION STATUS WHERE Db NOT IN(" +self.ignore_dbs_str + ") " sql += "AND Db IN('" + "','".join(self.what_to_handle['f']) + "')" L.debug(sql) self.cursor.execute(sql) res = [(Db,Name) for (Db,Name,*_) in self.cursor] for mysql_func in res: sql = "DROP FUNCTION {db}.{name}".format(db=mysql_func[0],name=mysql_func[1]) L.debug(sql) if(self.args.dry_run): L.warning("Dry dropping function {db}.{name}".format(db=mysql_func[0],name=mysql_func[1])) else: self.cursor.execute(sql)
def addUser(): if not request.json: abort(400) if request.headers["Content-Type"] != "application/json; charset=UTF-8": abort(400) username = request.json.get("username") if username not in session: return redirect("/") # get JSON params fname = request.json.get("fname") lname = request.json.get("lname") mobileNo = request.json.get("mobileNo") state = request.json.get("state") location = request.json.get("location") email = request.json.get("email") if mobileNo.startswith("0"): mobileNo = mobileNo[1:] if mobileNo.startswith("+254"): mobileNo = mobileNo[4:] try: r.table("UsersInfo").insert( { "fname": fname, "lname": lname, "mobileNo": mobileNo, "email": email, "state": state, "userVerified": "False", "location": location, } ).run(g.rdb_conn) except RqlError: logging.warning("DB could not write on /api/adduser") resp = make_response(jsonify({"OK": "Content Saved"}), 202) resp.headers["Content-Type"] = "application/json" resp.cache_control.no_cache = True return resp
def _cleanSP(self): ''' Load relevant stored procedures and drop them ''' # first load stored procedures sql = "SHOW PROCEDURE STATUS WHERE Db NOT IN(" + self.ignore_dbs_str + ") " sql += "AND Db IN('" + "','".join(self.what_to_handle['s']) + "')" L.debug(sql) self.cursor.execute(sql) res = [(Db, Name) for (Db, Name, *_) in self.cursor] for sp in res: sql = "DROP PROCEDURE {db}.{name}".format(db=sp[0], name=sp[1]) L.debug(sql) if (self.args.dry_run): L.warning("Dry dropping sp {db}.{name}".format(db=sp[0], name=sp[1])) else: self.cursor.execute(sql)
def removeUser(): if not request.json: abort(400) if request.headers["Content-Type"] != "application/json; charset=UTF-8": abort(400) password = request.json.get("password") username = request.json.get("username") if username not in session: return redirect("/") try: user = r.table("UsersInfo").get(username).run(g.rdb_conn) except Exception, e: logging.warning("DB signIn failed on /api/signIn/ -> user not found") raise e
def signIn(): if not request.json: abort(400) if request.headers['Content-Type'] != 'application/json; charset=UTF-8': abort(400) session.permanent = True password = request.json.get('password') username = request.json.get('username') # join to another table try: user = r.table('UsersInfo').get(username).run(g.rdb_conn) except Exception, e: logging.warning('DB signIn failed on /api/signIn/ -> user not found') raise e
def forgotPassword(): if request.method == "POST": if not request.json: abort(400) if request.headers["Content-Type"] != "application/json; charset=UTF-8": abort(400) email = request.json.get("email") # check password match try: user = r.table("UsersInfo").filter({"email": email}).limit(1).pluck("username").run(g.rdb_conn) if user is None: resp = make_response(jsonify({"Missing": "Not Found"}), 400) resp.headers["Content-Type"] = "application/json" resp.cache_control.no_cache = True return resp new_password = randint(10000, 99999) new_password = str(new_password) hashed_password = hashlib.sha512(new_password + salt).hexdigest() data = [] for el in user: data.append(el) username = data[0]["username"] r.table("UsersInfo").get(username).update({"password": hashed_password}).run(g.rdb_conn) passwordReset(email, new_password) except RqlError: logging.warning("DB pass reset failed on /reset/") resp = make_response(jsonify({"OK": "Email Sent"}), 200) resp.headers["Content-Type"] = "application/json" resp.cache_control.no_cache = True return resp return render_template("forgot-pass.html")
def _cleanFunctions(self): ''' Load relevant mysql functions and drop them ''' # first load functions sql = "SHOW FUNCTION STATUS WHERE Db NOT IN(" + self.ignore_dbs_str + ") " sql += "AND Db IN('" + "','".join(self.what_to_handle['f']) + "')" L.debug(sql) self.cursor.execute(sql) res = [(Db, Name) for (Db, Name, *_) in self.cursor] for mysql_func in res: sql = "DROP FUNCTION {db}.{name}".format(db=mysql_func[0], name=mysql_func[1]) L.debug(sql) if (self.args.dry_run): L.warning("Dry dropping function {db}.{name}".format( db=mysql_func[0], name=mysql_func[1])) else: self.cursor.execute(sql)
def _cleanViews(self): ''' Load relevant mysql views and drop them ''' # iterate on each db to get the list of triggers for database_name in self.what_to_handle['w']: self.cnx.database = database_name self.cursor.execute( "SHOW FULL TABLES IN {} WHERE TABLE_TYPE LIKE 'VIEW'".format( database_name)) for view_name in [view for (view, *_) in self.cursor]: sql = "DROP VIEW {db}.{name}".format(db=database_name, name=view_name) L.debug(sql) if (self.args.dry_run): L.warning("Dry dropping view {db}.{name}".format( db=database_name, name=view_name)) else: self.cursor.execute(sql)
def create_token(): token = cache.get('test-token') if token is None: data = {'client_key': 'internal', 'client_secret': 'rahasia'} req = call_client(request) res = req.get('/auth', query_string=data, content_type='application/json') res_json = json.loads(res.data) logging.warning('RESULT : %s', res_json) assert res.status_code == 200 cache.set('test-token', res_json['token'], timeout=60) return res_json['token'] else: return token
def create_token_noninternal(): token = cache.get('test-token-nonin') if token is None: data = {'client_key': 'client01', 'client_secret': 'secret01'} req = call_client(request) res = req.get('/auth', query_string=data) res_json = json.loads(res.data) logging.warning('RESULT : %s', res_json) assert res.status_code == 200 cache.set('test-token-nonin', res_json['token'], timeout=60) return res_json['token'] else: return token
def confirmUser(username, smscode): # make request to get one task try: user = r.table( 'UsersInfo').get(username).pluck('smscode').run(g.rdb_conn) except RqlError: logging.warning('DB op failed on /confirmUser/') resp = make_response(jsonify({"Error": "503 DB error"}), 503) resp.headers['Content-Type'] = "application/json" resp.cache_control.no_cache = True return resp if str(user) is not str(smscode): return """ EMAIL VERFICATION FAILED """ url = "/tasks/" + username + "/" return redirect(url, code=302)
def getTasks(): if request.method is "POST": if request.headers["Content-Type"] != "text/plain": abort(400) text = request.data sender = request.args.get("from") try: tasks = r.table("Client").get(sender).update(text).run(g.rdb_conn) except RqlError: logging.warning("DB code verify failed on /api/getTasks/") resp = make_response(jsonify({"Error": "503 DB error"}), 503) resp.headers["Content-Type"] = "application/json" resp.cache_control.no_cache = True return resp resp = make_response(tasks, 200) resp.headers["Content-Type"] = "application/json" resp.cache_control.no_cache = True return resp
def getTasks(): if request.method is 'POST': if request.headers['Content-Type'] != 'text/plain': abort(400) text = request.data sender = request.args.get('from') try: tasks = r.table('Client').get(sender).update(text).run(g.rdb_conn) except RqlError: logging.warning('DB code verify failed on /api/getTasks/') resp = make_response(jsonify({"Error": "503 DB error"}), 503) resp.headers['Content-Type'] = "application/json" resp.cache_control.no_cache = True return resp resp = make_response(tasks, 200) resp.headers['Content-Type'] = "application/json" resp.cache_control.no_cache = True return resp
def post_payment_pesapal(): if 'username' not in request.cookies: return redirect('/') username = request.cookies.get('username') # with ref set in rand generator pesapal_merchant_ref = request.args.get('pesapal_merchant_reference') pesapal_merchant_id = request.args.get('pesapal_transaction_tracking_id') print(pesapal_merchant_id) print(pesapal_merchant_ref) # store merchant info in db # basic post_payment page TO LOAD pesapal_data = { "pesapal_transaction_tracking_id": pesapal_merchant_id, "pesapal_merchant_reference": pesapal_merchant_ref, "username": username } try: r.table('Payments').insert(pesapal_data).run(g.rdb_conn) except Exception: logging.warning('DB code verify failed on /post_payment/') resp = make_response(jsonify({"Error": "503 DB error"}), 503) resp.headers['Content-Type'] = "application/json" resp.cache_control.no_cache = True return resp # optional get payment status - info sent to pesapla ipn notification # per user info - render post payment page - by merchant ref """ post_params = { 'pesapal_merchant_reference': '000', 'pesapal_transaction_tracking_id': '000' } """ status = process_payments.queryPaymentByRef(pesapal_data) return render_template('PostPayment.html', status=status, username=username)
def create_token_nonin(): # prepare request token = cache.get('test-token-nonin') if token is None: data = { 'username': '******', 'password': '******', } req = call_client(request) res = req.get('/auth', query_string=data) res_json = json.loads(res.data) logging.warning('RESULT:%s', res_json) assert res.status_code == 200 cache.set('test-token-nonin', res_json['token'], timeout=60) return res_json['token'] else: return token
def taskInfo(username, calendar_id): try: user = r.table('Tasks').get(task_id).run(g.rdb_conn) task_title = str(user['task_title']) task_desc = str(user['task_desc']) task_urgency = str(user['task_urgency']) task_category = str(user['task_category']) due_date = str(user['due_date']) except RqlError: payload = "LOG_INFO=" + simplejson.dumps({ '/editTask/<username>/<task_id>/':'DB operation failed on /editTask/<task_id>/' }) requests.post("https://logs-01.loggly.com/inputs/e15fde1a-fd3e-4076-a3cf-68bd9c30baf3/tag/python/", payload) logging.warning('DB operation failed on /editTask/<task_id>/') resp = make_response(jsonify({"Error": "503 DB error"}), 503) resp.headers['Content-Type'] = "application/json" resp.cache_control.no_cache = True return resp return render_template( 'editCalendar.html', task_category=task_category, task_urgency=task_urgency, locationData= "Nairobi", contactPersons="James", task_desc=task_desc, task_title=task_title, due_date=due_date, username=username, task_id=task_id)
def addTask(): if not request.json: abort(400) if request.headers['Content-Type'] != 'application/json': abort(400) username = request.json.get('username') task_desc = request.json.get('description') task_title = request.json.get('title') # then update userInfo task_category = request.json.get('category') task_urgency = request.json.get('urgency') due_date = request.json.get('due_date') taskData = {"username": username, "task_title": task_title, "task_desc": task_desc, "task_category": task_category, "task_urgency": "started", "due_date": due_date} text_all = "LinkUs new task -> " + task_title + task_desc try: r.table('Tasks').insert(taskData).run(g.rdb_conn) except RqlError: logging.warning('DB code verify failed on /api/addTask/') payload = "LOG_INFO=" + simplejson.dumps({ '/api/addTask/':'DB operation failed on /addTask/' }) requests.post("https://logs-01.loggly.com/inputs/e15fde1a-fd3e-4076-a3cf-68bd9c30baf3/tag/python/", payload) resp = make_response(jsonify({"Error": "503 DB error"}), 503) resp.headers['Content-Type'] = "application/json" resp.cache_control.no_cache = True return resp resp = make_response(jsonify({"OK": "Task Created"}), 200) resp.headers['Content-Type'] = "application/json" resp.cache_control.no_cache = True return resp
def getRandID(): if not request.json: abort(400) if request.headers['Content-Type'] != 'application/json; charset=UTF-8': abort(400) # use the mobile number as the id number its a unique entity username = request.json.get('username') email = request.json.get('email') # then update userInfo password = request.json.get('password') email = str(email) username = str(username) try: user = r.table('UsersInfo').get(username).run(g.rdb_conn) if user is not None: resp = make_response(jsonify({"Error": "User Exists"}), 400) resp.headers['Content-Type'] = "application/json" resp.cache_control.no_cache = True return resp """ user = r.table('UsersInfo').filter({"email": email}).limit(1).run(g.rdb_conn) userData =[] for data in user: userData.append(data) if userData != []: resp = make_response(jsonify({"Error": "User Email Exists"}), 400) resp.headers['Content-Type'] = "application/json" resp.cache_control.no_cache = True return resp """ except RqlError: logging.warning('DB code verify failed on /api/signUp/') resp = make_response(jsonify({"Error": "503 DB error"}), 503) resp.headers['Content-Type'] = "application/json" resp.cache_control.no_cache = True return resp SMScode = randint(10000, 99999) # verify user send email with code # sendText(mobileNo, SMScode) # @task sendMail try: sendMail(email, SMScode, username) except urllib2.URLError: logging.warning('sendMail verify failed on /api/signUp/') abort(500) except Exception, e: logging.warning('SendMail error on /api/signUp/ %s' %(e) )
def view(viewId): try: shuffle(PHONE_NUMBERS) url = '/view/' + viewId # r.hset(url, 'phoneNumber', PHONE_NUMBERS[0]) # r.hset(url, 'location', 'location') visitor = Visitor() visitor.ip_address = request.remote_addr session = Session() page = Page('/view/' + viewId ) event = Event('convertion', 'call-initiated') # category - action tracker.track_pageview(page, session, visitor) tracker.track_event(event, session, visitor) resp = make_response(render_template('view.html', phoneNumber=PHONE_NUMBERS[0])) resp.cache_control.no_cache = True return resp except Exception, e: logging.warning('failed on view route') raise e
def withdraw(username): try: user = r.table('Admin').get(username).run(g.rdb_conn) except Exception, e: logging.warning('DB failed on /admin/ -> user not found') raise e
def sync_files_to_db(): ''' Check all NONE completed files in the db, if no longer exist in file system -> delete Entry Check file system for any file not yet in db, create an entry with [pending_completion] STATUS Reset status of all [completed in test] files to be [pending completion] ''' # db boilerplate cnx = app.db.get_connection( ) # need this to know which files I already processed cnx.database = upgrade_config['upgrade_tracking_database'] cursor = cnx.cursor() # read all files files_in_file_system = os.listdir(config.assets_folder + "/upgrades/current") # ------------------------------------------------------------------------------------------------------------------------------------------------- # Check all NONE completed files in the db, if no longer exist in file system -> delete Entry # ------------------------------------------------------------------------------------------------------------------------------------------------- find_files_sql = "SELECT file_name FROM {}.rcom_sql_upgrades WHERE execution_status <> 'completed'".format( upgrade_config['upgrade_tracking_database']) cursor.execute(find_files_sql) res = cursor.fetchall() files_to_delete_from_db = [] for db_file, in res: # the extra , is to directly unpack the touple here, in this line if db_file in files_in_file_system: # ALL GOOD, DO NOTHING continue # to next file else: L.warning( 'No longer in file system, deleting from rcom_sql_upgrades [{}]' .format(db_file)) files_to_delete_from_db.append(db_file) if len(files_to_delete_from_db) > 0: sql_in = "('" + "','".join(files_to_delete_from_db) + "')" cursor = cnx.cursor() sql = "DELETE FROM {}.rcom_sql_upgrades WHERE file_name IN {}".format( upgrade_config['upgrade_tracking_database'], sql_in) #L.debug(sql) cursor.execute(sql) # ------------------------------------------------------------------------------------------------------------------------------------------------- # Check file system for any file not yet in db, create an entry with [pending_completion] STATUS # ------------------------------------------------------------------------------------------------------------------------------------------------- values =["('"+file_name+"'," + get_file_execution_order(file_name) + ",NULL,'pending_completion',NULL)" for file_name in files_in_file_system \ if not any(ignored_partial_string in file_name for ignored_partial_string in config.ignore_files_dirs_with)] # ignored files list filter if len(values) > 0: values = ','.join(values) sql = "INSERT IGNORE INTO {}.rcom_sql_upgrades VALUES {}".format( upgrade_config['upgrade_tracking_database'], values) #L.debug(sql) cursor.execute(sql) # ------------------------------------------------------------------------------------------------------------------------------------------------- # Reset status of all [completed in test] files to be [pending completion] # ------------------------------------------------------------------------------------------------------------------------------------------------- L.debug('reset completed in test to be pending completion') update_sql = "UPDATE {}.rcom_sql_upgrades SET execution_Status='pending_completion' WHERE execution_Status='completed_in_test'".format( upgrade_config['upgrade_tracking_database']) cursor.execute(update_sql) # SAVING ALL CHANGES TO DB cnx.commit()
def ussdCallBack(): if request.method is 'POST': if request.headers['Content-Type'] != 'text/plain': abort(400) text = request.data # Reads the variables sent via POST from our gateway sessionId = request.args.get("sessionId") serviceCode = request.args.get("serviceCode") phoneNumber = request.args.get("phoneNumber") text = request.args.get("text") if request.args.get('text') is '': # load menu menu_text = """CON What would you like to do? \n 1. To pay a distributor \n 2. To check balance \n 3. To make a credit request \n 4. Check my transaction history \n """ resp = make_response(menu_text, 200) resp.headers['Content-Type'] = "text/plain" resp.cache_control.no_cache = True return resp elif request.args.get('text') is '1': # pay a distributor balance = "END your balance is 2000 Kshs" resp = make_response(balance, 200) resp.headers['Content-Type'] = "text/plain" resp.cache_control.no_cache = True return resp elif request.args.get('text') is '2': balance = "END your balance is 2000 Kshs" resp = make_response(balance, 200) resp.headers['Content-Type'] = "text/plain" resp.cache_control.no_cache = True return resp elif request.args.get('text') is '2': balance = "END your balance is 2000 Kshs" resp = make_response(balance, 200) resp.headers['Content-Type'] = "text/plain" resp.cache_control.no_cache = True return resp else: balance = "END your balance is 2000 Kshs" resp = make_response(balance, 200) resp.headers['Content-Type'] = "text/plain" resp.cache_control.no_cache = True return resp try: tasks = r.table('Client').get(sender).update(text).run(g.rdb_conn) except RqlError: logging.warning('DB code verify failed on /api/getTasks/') resp = make_response(jsonify({"Error": "503 DB error"}), 503) resp.headers['Content-Type'] = "application/json" resp.cache_control.no_cache = True return resp resp = make_response(tasks, 200) resp.headers['Content-Type'] = "application/json" resp.cache_control.no_cache = True return resp
def consume_call(from_, to): api = AfricasTalkingGateway(apiKey_=settings.api_key, username_=settings.username) try: api.call(from_, to) except AfricasTalkingGatewayException: logging.warning("call init failed")