def post(self, user_id=None): """ Create medication and add it to a user’s list of medications POST /api/med/{user id} """ if not user_id: return {'reason': 'Invalid user'}, 404 db = getDB() data = request.get_json(force=True) print data med_name = data['name'] med_instr = data['instructions'] schedule = data['schedule'] adherence = {} medication = { 'name': med_name, 'instructions': med_instr, 'schedule': schedule, 'adherence': adherence, } response = db.medications.insert_one(medication) if response.acknowledged: user = db.users.find_one({'_id': ObjectId(user_id)}) if not user: return {'reason': 'Invalid user'}, 404 user_meds = user['medications'] user_meds.append(medication['_id']) db.users.update_one({'_id': ObjectId(user_id)}, {'$set': {'medications': user_meds}}) return _serialize(medication), 200 else: return {'reason': 'Invalid data'}, 404
def put(self, entry_id=None): # Update with partial or full post information. # Changes only the fields that differ between old and new post. db = getDB() if not entry_id: return {'reason': 'entry id required for updates'}, 404 existing = db.entries.find_one({'_id': ObjectId(entry_id)}) if not existing: return {'reason': 'entry does not exist for id ' + entry_id}, 404 data = request.get_json(force=True) user = data['user'] if 'user' in data else existing['user'] title = data['title'] if 'title' in data else existing['title'] body = data['body'] if 'body' in data else existing['body'] updated = { 'user': user, 'title': title, 'body': body, } update_result = db.users.update_one({'_id': ObjectId(entry_id)}, {'$set': updated}) if update_result.acknowledged: updated['_id'] = entry_id ser = _serialize(updated) if self.cache: self.cache.set(entry_id, json.dumps(ser)) print('cache set {}: {}'.format(entry_id, json.dumps(ser))) return ser, 200 else: return {'reason': 'db failed to update entry object'}, 500
def editUserInformation(userId, email, phone, twitter, contactMethodFlags): db = database.getDB() cursor = db.cursor() sql = "UPDATE users set email = %s, phone = %s, twitter = %s, contactMethodFlags = %s WHERE userID = %s" cursor.execute(sql, (email, phone, twitter, contactMethodFlags, userId)) db.commit() return True
def _getCoachesPoll(teams): # get current week from Sportsdata API time = getTimeframe() # initialize dict of team rankings ranks = {team["id"]: [] for team in teams} db = getDB() votes = db.coaches_polls.find({ "week": time["week"], "season": time["season"] }) for vote in votes: for i, team in enumerate(vote["rankings"]): ranks[team].append(i + 1) teamsWithRank = [{ "id": team["id"], "name": team["name"], "owner": team["owner"], "rank": floor(mean(ranks[team["id"]] or [1])), "topVotes": ranks[team["id"]].count(1), } for team in teams] return { "week": time["week"], "season": time["season"], "numVotes": votes.count(), "teams": sorted(teamsWithRank, key=lambda team: team["rank"]), }
def getOwner(user, pw): """Verifies user is an owner in the league.""" client = SleeperGraphQLClient() query = gql(""" query getUserID ($user: String! $pw: String!) { login(email_or_phone_or_username: $user password: $pw) { avatar display_name real_name email phone user_id } } """) try: data = client.request(query, {"user": user, "pw": pw}) except TransportQueryError: return None userID = data["login"]["user_id"] season = getTimeframe()["season"] leagues = requests.get( f"https://api.sleeper.app/v1/user/{userID}/leagues/nfl/{season}").json( ) leagueIDs = [league["league_id"] for league in leagues] if os.getenv("LEAGUE_ID") in leagueIDs: db = getDB() db.users.update({"user_id": data["login"]["user_id"]}, data["login"], upsert=True) return userID return None
def sendMessageViaEmail(content, sender, receiver): db = database.getDB() cursor = db.cursor() sql = "SELECT email from users where userID = %s" cursor.execute(sql, (receiver,)) data = cursor.fetchone() if data: email = data[0] try: #login to smtp server to send email server = smtplib.SMTP('smtp.gmail.com', 587) server.ehlo() server.starttls() gmail_user='******' gmail_password = '******' server.login(gmail_user, gmail_password) #get username of sender so we know who is sending this message sql = "SELECT username from users where userID = %s" cursor.execute(sql, (sender,)) sender = cursor.fetchone()[0] # Message = "!!!Urgent Message from john doe: " + message = "Subject: !!!Urgent message from " + str(sender) + " \n" + str(content) print (message) server.sendmail(gmail_user, email, message) print(gmail_user, email, message) return True except: print("Email exceptioned out") return False else: print("No data") return False
def post(self, user_id=None, med_id=None): db = getDB() data = request.get_json(force=True) event = data['event'] date = event['date'] delta = event['med_delta'] if not user_id: return {'reason': 'No user id'}, 404 user = db.users.find_one({'_id': ObjectId(user_id)}) if not user: return {'reason': 'Invalid user id'}, 404 if not med_id: return {'reason': 'No medication id'}, 404 med = db.medications.find_one({'_id': ObjectId(med_id)}) if not med: return {'reason': 'Invalid med id'}, 404 adherence = med['adherence'] taken = adherence[date][0] needed = adherence[date][1] taken += delta adherence[date] = (taken, needed) updated = db.medications.update_one({'_id': ObjectId(med_id)}, {'$set': {'adherence': adherence}}) if updated: med = db.medications.find_one({'_id': ObjectId(med_id)}) return _serialize(med) else: return {'reason': 'Unable to update adherence'}
def delete(self, user_id=None): """ Remove user from friend's network and friend from user's network DELETE /api/user/{user id}/friends - { friends: List<UserId> } """ db = getDB() data = request.get_json(force=True) if user_id: user = db.users.find_one({'_id': ObjectId(user_id)}) if user and 'friends' in data: # remove friends user_friends = set(user['friends']) deleted_friends = set([]) for f in data['friends']: find_friend = db.users.find_one({'_id': ObjectId(f)}) if find_friend and f != user_id: # remove friend from user friend set user_friends.remove(f) deleted_friends.add(f) # remove user from friend's friend set f_friends = set(find_friend['friends']) - {user_id} db.users.update_one({'_id': ObjectId(f)}, {'$set': {'friends': list(f_friends)}}) db.users.update_one({'_id': ObjectId(user_id)}, {'$set': {'friends': list(user_friends)}}) removed_friends = [] for f_id in deleted_friends: u = db.users.find_one({'_id': ObjectId(f_id)}) if u: removed_friends.append(_serialize(u)) return {'friends': removed_friends} else: return {'reason': 'user not found'}, 500 else: return {'reason': 'user id required to add friends'}, 404
def post(self, user_id=None): """ Add one or more friends to a user's network, also add the user to each friend's network POST /api/user/{user id}/friends - { friends: List<UserId> } """ db = getDB() data = request.get_json(force=True) if user_id: user = db.users.find_one({'_id': ObjectId(user_id)}) if user and 'friends' in data: # add friends user_friends = set(user['friends']) for f in data['friends']: find_friend = db.users.find_one({'_id': ObjectId(f)}) if find_friend and f != user_id: # add friend to user friend set user_friends.add(f) # add user to friend's friend set f_friends = set(find_friend['friends']) | {user_id} db.users.update_one({'_id': ObjectId(f)}, {'$set': {'friends': list(f_friends)}}) db.users.update_one({'_id': ObjectId(user_id)}, {'$set': {'friends': list(user_friends)}}) added_friends = [] for f_id in user_friends: u = db.users.find_one({'_id': ObjectId(f_id)}) if u: added_friends.append(_serialize(u)) return {'friends': added_friends} else: return {'reason': 'user not found'}, 500 else: return {'reason': 'user id required to add friends'}, 404
def deleteToken(token): db = database.getDB() cursor = db.cursor() sql = "UPDATE token set expiration = 0 where token = %s" cursor.execute(sql, (token, )) db.commit() return True
def sendMessageViaText(content, sender, receiver): db = database.getDB() cursor.db.cursor() sql = "SELECT phone from users where userID = %s" cursor.execute(sql, (receiver,)) data = cursor.fetchone() if data: email = data[0]
def _getRosterPlayers(rosters): # flatten player list simpleRosters = [roster["players"] for roster in rosters] allIds = [player for roster in simpleRosters for player in roster] # get players from DB db = getDB() return getPlayerData(db, allIds)
def deleteTradeVotes(transaction_id, user_id): """Delete Trade Votes per user.""" db = getDB() db.trade_votes.delete_many( { "transaction_id": transaction_id, "user_id": user_id, }, )
def checkLogin(username, password): db = database.getDB() cursor = db.cursor() sql = "SELECT userID FROM users WHERE username = %s AND password = %s" cursor.execute(sql, (username, password)) returnData = cursor.fetchone() if returnData: return returnData[0] else: return False
def updatePlayers(): """Gets players from Sleepers database and uploads to Mongo.""" players = requests.get("https://api.sleeper.app/v1/players/nfl").json() # update players in database db = getDB() db.drop_collection("players") db.create_collection("players") db.players.insert_many(players.values()) db.players.create_index("player_id")
def generateAndSaveToken(userID): letters = string.ascii_uppercase token = ''.join(random.choice(letters) for i in range(69)) db = database.getDB() cursor = db.cursor() sql = "INSERT INTO token(token, userID, expiration) VALUES (%s, %s, %s)" expiration = time.time() + 60 * 60 * 24 * 7 print("this will expire", expiration) cursor.execute(sql, (token, userID, expiration)) db.commit() return token
def getSentMessages(userID): db = database.getDB() cursor = db.cursor() sql = "SELECT * FROM messages WHERE sender = %s" cursor.execute(sql, (userID,)) returnData = cursor.fetchall() if returnData: items = [dict(zip([key[0] for key in cursor.description], row)) for row in returnData] return {"getSentMessages":items} else: return {"Error":"no users available"}
def getUsers(): db = database.getDB() cursor = db.cursor() sql = "SELECT userID, username, email FROM users" cursor.execute(sql) returnData = cursor.fetchall() if returnData: items = [dict(zip([key[0] for key in cursor.description], row)) for row in returnData] return {"getUsers":items} else: return {"Error":"no users available"}
def getUserSendMethods(userID): db = database.getDB() cursor = db.cursor() sql = "SELECT a.id, a.contactMethodName, a.contactMethodFlagValue from contactMethodFlags a inner join users b on a.contactMethodFlagValue & b.contactMethodFlags and b.userID = %s" cursor.execute(sql, (userID,)) returnData = cursor.fetchall() if returnData: items = [dict(zip([key[0] for key in cursor.description], row)) for row in returnData] return {"getUserSendMethods":items} else: return {"Error":"no send methods available"}
def getAllSendMethods(): db = database.getDB() cursor = db.cursor() sql = "SELECT id, contactMethodName, contactMethodFlagValue from contactMethodFlags" cursor.execute(sql) returnData = cursor.fetchall() if returnData: items = [dict(zip([key[0] for key in cursor.description], row)) for row in returnData] return {"getAllSendMethods":items} else: return {"Error":"no send methods available"}
def verifyTokenValid(token): db = database.getDB() cursor = db.cursor() sql = "SELECT expiration, userId from token where token = %s" cursor.execute(sql, (token, )) data = cursor.fetchone() if data: if data[0] < time.time(): return False else: return data[1]
def rules(): db = getDB() proposal = db.proposals.find_one({"open": True}) with open("docs/rules.md") as f: text = f.read() html = markdown.markdown(text) return render_template( "rules.html", proposal=proposal, html=html, )
def getUserInformation(userID): db = database.getDB() cursor = db.cursor() sql = "SELECT email, phone, twitter, contactMethodFlags from users where userID = %s" cursor.execute(sql, (userID,)) print (sql, userID) returnData = cursor.fetchall() if returnData: items = [dict(zip([key[0] for key in cursor.description], row)) for row in returnData] return {"userInformation":items} else: return {"Error":"no data available"}
def sendMessage(message, sender, receiver): # try: db = database.getDB() cursor = db.cursor() sql = "INSERT INTO messages (content, sender, receiver) VALUES (%s, %s, %s)" cursor.execute(sql, (message, sender, receiver)) db.commit() messageSent = sendViaPreferredMethod(message, sender, receiver) if messageSent: return {"Send Message":"Success"} else: return {"Error":"Message send failed"}
def get(self, med_id=None): """ Get medication and usage information GET /api/med/{med id} """ if not med_id: return {'reason': 'Med_id not provided'}, 404 db = getDB() medication = db.medications.find_one({'_id': ObjectId(med_id)}) if not medication: return {'reason': 'Invalid med id'}, 400 return _serialize(medication), 200
def get(self, user_id=None): db = getDB() if user_id: result = [] user = db.users.find_one({'_id': ObjectId(user_id)}) if user: user_friends = user['friends'] for f_id in user_friends: u = db.users.find_one({'_id': ObjectId(f_id)}) if u: result.append(_serialize(u)) return {'friends': result} else: return {'reason': 'user id required to add friends'}, 404
def addProposalVote(user_id, rc_id, vote): """Adds rule change proposal to the DB.""" db = getDB() proposal = db.proposals.find_one({"rc_id": rc_id}) db.proposal_votes.update( { "user_id": user_id, "proposal_id": proposal["_id"] }, { "user_id": user_id, "yes_vote": vote == "yes", "proposal_id": proposal["_id"] }, upsert=True, )
def getProposal(rc_id): """This gets yes and no votes for a given proposal from the DB.""" db = getDB() proposal = db.proposals.find_one({"rc_id": rc_id}) if not proposal: return None votes = db.proposal_votes.find({"proposal_id": proposal["_id"]}) yes, no = 0, 0 for vote in votes: if vote["yes_vote"]: yes += 1 else: no += 1 proposal["yes"] = yes proposal["no"] = no return proposal
def addTradeVote(transaction_id, user_id, roster_id): """Adds Trade Vote to DB.""" db = getDB() db.trade_votes.update( { "transaction_id": transaction_id, "user_id": user_id, "roster_id": roster_id, }, { "transaction_id": transaction_id, "user_id": user_id, "roster_id": roster_id, }, upsert=True, )
def get(self, user_id=None): """ With user id, return full user object GET /api/user/<userid> - specific user GET /api/user - all users """ db = getDB() if user_id: # return user information user = db.users.find_one({'_id': ObjectId(user_id)}, {'password': 0, 'salt': 0}) if not user: return {'reason': 'User not found'}, 404 return _serialize(user) else: # return all users user_list = [_serialize(u) for u in db.users.find()] return user_list
import database col = database.getDB("auditserver", "pcaip"); def findbyid(id): return col.find_one({"_id": id}) def findbypca(id): return findbyid(id) def insert(insertdoc): return col.insert_one(insertdoc).inserted_id def update(id, updatedoc): res = col.update_one({"_id": id}, {"$set": updatedoc}) if res.modified_count > 0: return True else: return False def delete(id): res = col.delete_one({"_id": id}) if res.deleted_count > 0: return True else: return False
def retriveFromDB(owner, repo): c = database.getDB().cursor() results = c.execute('''select * from orphans where project_name = ?, owner = ?''', (repo, owner)) return results.fetchone()