def create_letter(): letter_result = None search_email = session['id'] user_email = session['login'] user_surname = session['last_name'] count_result = db.counts_for_menu(search_email) if request.method == 'POST': topic = request.form['topic'] body = request.form['body'] date = request.form['date'] draft = request.form['draft'] if 'letterid' in request.args.keys(): let = request.args.get('letterid') db.update(let, topic, body, date, draft) else: recipient = request.form['recipient'] db.create(search_email, recipient, topic, body, date, draft) return redirect(url_for('inbox')) if 'letterid' in request.args.keys(): let = request.args.get('letterid') letter_result = db.full_letter(let) return render_template('new_letter.html', mails=letter_result, inbox_count=count_result, user_email=user_email, user_surname=user_surname, active_index='create_letter')
def put(self): u = authorize(request) j = request.json try: id = int(request.args.get('id',None)) except: abort(400, 'Malformed request') if not j: abort(400, 'Malformed request') if not db.exists('POST').where(id=id): abort(400, 'Malformed request') (comment,) = unpack(j,'comment') if comment == "": abort(400, 'Malformed request') comment_id = db.insert('COMMENT').with_values( comment=comment, author=u[1], published=str(time.time()) ).execute() p = db.select('POST').where(id=id).execute() comment_list = text_list_to_set(p[7],process_f=lambda x: int(x)) comment_list.add(comment_id) comment_list = set_to_text_list(comment_list) db.update('POST').set(comments=comment_list).where(id=id).execute() return { 'message': 'success' }
def updateProfile(): login_info = request.get_json() auth = vafs_jwt("nusstu\\" + login_info['userName'], login_info['password']) user_id = login_info['userName'].upper() if "error" in auth: return util.response_json(False, 1, auth), HTTP_UNAUTHORISED if User.query.filter_by(nus_net_id=user_id).first() != None: uName = name(auth).data db.update(User).where(User.nus_net_id == user_id).values(name=uName) db.session.commit() else: uName = name(auth).data u = User(name=uName, nus_net_id=user_id) db.session.add(u) db.session.commit() if User.query.filter_by(nus_net_id=user_id).first().mods == []: uId = User.query.filter_by(nus_net_id=user_id).first().id util.add_mods(auth, uId) else: uId = User.query.filter_by(nus_net_id=user_id).first().id util.update_mods(auth, uId) u = User.query.filter_by(nus_net_id=user_id).first() u.get_busy_time() flag_modified(u, "timetable") db.session.commit() return redirect(url_for('profile', nusNetId=user_id))
def get_issues(org_name): ''' Get github issues associated to each Organization's Projects. ''' issues = [] labels = [] # Flush the current db session to save projects added in current run db.session.flush() # Only grab this organizations projects projects = db.session.query(Project).filter( Project.organization_name == org_name).all() # Populate issues for each project for project in projects: # Mark this projects issues for deletion db.session.execute( db.update(Issue, values={ 'keep': False }).where(Issue.project_id == project.id)) # Get github issues api url _, host, path, _, _, _ = urlparse(project.code_url) issues_url = 'https://api.github.com/repos' + path + '/issues' # Ping github's api for project issues got = get_github_api( issues_url, headers={'If-None-Match': project.last_updated_issues}) # Verify if content has not been modified since last run if got.status_code == 304: db.session.execute( db.update(Issue, values={ 'keep': True }).where(Issue.project_id == project.id)) logging.info('Issues %s have not changed since last update', issues_url) elif not got.status_code in range(400, 499): # Update project's last_updated_issue field project.last_updated_issues = got.headers['ETag'] db.session.add(project) # Save each issue in response for issue in got.json(): # Type check the issue, we are expecting a dictionary if type(issue) == type({}): # Pull requests are returned along with issues. Skip them. if "/pull/" in issue['html_url']: continue issue_dict = dict(title=issue['title'], html_url=issue['html_url'], body=issue['body'], project_id=project.id) issues.append(issue_dict) labels.append(issue['labels']) else: logging.error('Issue for project %s is not a dictionary', project.name) return issues, labels
def edit_elective(elective_id, name="", desc="", course_id="", prereq=""): if name or desc or course_id or prereq: elective = get_elective(elective_id) if elective: updates = {} if name: updates['NAME'] = name if desc: updates['`DESC`'] = desc if not course_id is None or course_id == ' ': updates['COURSE_ID'] = str(course_id) if prereq: updates['PREREQ'] = str(prereq) query = "UPDATE elective SET " + "".join([ "%s = '%s', " % (x, updates[x]) for x in updates ])[:-2] + " WHERE elective_id=%s" % (elective_id) update(DB.ELECTIVE, query, []) return False
def put(self): j = request.json try: id = int(request.args.get('id',None)) except: abort(400, 'Malformed request') u = authorize(request) u_username = u[1] if not j or not id: abort(400, 'Malformed request') if not db.exists('POST').where(id=id): abort(400, 'Malformed request') # check the logged in user made this post post_author = db.select('POST').where(id=id).execute()[1] if u[1] != post_author: # exposing what post id's are valid and unvalid # may be a security issue lol abort(403, 'You Are Unauthorized To Edit That Post') (desc,src) = unpack(j,'description_text','src',required=False) if desc == None and src == None: abort(400, 'Malformed Request') updated = {} if desc: updated['description'] = desc if src: updated['src'] = src db.update('POST').set(**updated).where(id=id).execute() return { 'message': 'success' }
def get_issues(org_name): ''' Get github issues associated to each Organization's Projects. ''' issues = [] # Only grab this organization's projects projects = db.session.query(Project).filter(Project.organization_name == org_name).all() # Populate issues for each project for project in projects: # Mark this project's issues for deletion # :::here (issue/false) db.session.execute(db.update(Issue, values={'keep': False}).where(Issue.project_id == project.id)) # don't try to parse an empty code_url if not project.code_url: continue # Get github issues api url _, host, path, _, _, _ = urlparse(project.code_url) # Only check issues if its a github project if host != 'github.com': continue path = sub(r"[\ /]+\s*$", "", path) issues_url = GITHUB_ISSUES_API_URL.format(repo_path=path) # Ping github's api for project issues # :TODO: non-github projects are hitting here and shouldn't be! got = get_github_api(issues_url, headers={'If-None-Match': project.last_updated_issues}) # Verify that content has not been modified since last run if got.status_code == 304: # :::here (issue/true) db.session.execute(db.update(Issue, values={'keep': True}).where(Issue.project_id == project.id)) logging.info('Issues %s have not changed since last update', issues_url) elif got.status_code not in range(400, 499): # Update project's last_updated_issue field project.last_updated_issues = unicode(got.headers['ETag']) db.session.add(project) responses = get_adjoined_json_lists(got, headers={'If-None-Match': project.last_updated_issues}) # Save each issue in response for issue in responses: # Type check the issue, we are expecting a dictionary if isinstance(issue, dict): # Pull requests are returned along with issues. Skip them. if "/pull/" in issue['html_url']: continue issue_dict = dict(title=issue['title'], html_url=issue['html_url'], body=issue['body'], project_id=project.id, labels=issue['labels'], created_at=issue['created_at'], updated_at=issue['updated_at']) issues.append(issue_dict) else: logging.error('Issue for project %s is not a dictionary', project.name) return issues
def edit(id): name = request.form['name'] price = float(request.form['price']) qty = int(request.form['qty']) product = Product(id, name, price, qty) db.update(db.open_db(db_url), product) return redirect(url_for('details_by_id', id=id))
def put(self): j = request.json id = request.args.get('id', None) u = get_dummy_user() u_username = u[1] if not j or not id: abort(400, 'Malformed request') id = int(id) if not db.exists('POST').where(id=id): abort(400, 'Malformed request') # check the logged in user made this post post_author = db.select('POST').where(id=id).execute()[1] if u[1] != post_author: # exposing what post id's are valid and unvalid # may be a security issue lol abort(403, 'You Are Unauthorized To Edit That Post') (desc, src) = unpack(j, 'description_text', 'src', required=False) if desc == None and src == None: abort(400, 'Malformed Request') updated = {} if desc: updated['description'] = desc if src: updated['src'] = src db.update('POST').set(**updated).where(id=id).execute() return {'message': 'success'}
def put(self): u = authorize(request) u_username = u[1] j = get_request_json() id = get_request_arg('id', int, required=True) if not db.exists('POST').where(id=id): abort(404, 'Post Not Found') # check the logged in user made this post post_author = db.select('POST').where(id=id).execute()[1] if u[1] != post_author: # exposing what post id's are valid and unvalid # may be a security issue lol abort(403, 'You Are Unauthorized To Edit That Post') (desc,src) = unpack(j,'description_text','src',required=False) if desc == None and src == None: abort(400, "Expected at least 'description_text' or 'src'") updated = {} if desc: updated['description'] = desc if src: updated['src'] = src db.update('POST').set(**updated).where(id=id).execute() return { 'message': 'success' }
def get_issues(org_name): ''' Get github issues associated to each Organization's Projects. ''' issues = [] # Only grab this organization's projects projects = db.session.query(Project).filter(Project.organization_name == org_name).all() # Populate issues for each project for project in projects: # Mark this project's issues for deletion # :::here (issue/false) db.session.execute(db.update(Issue, values={'keep': False}).where(Issue.project_id == project.id)) # don't try to parse an empty code_url if not project.code_url: continue # Get github issues api url _, host, path, _, _, _ = urlparse(project.code_url) # Only check issues if its a github project if host != 'github.com': continue path = sub(r"[\ /]+\s*$","",path) issues_url = GITHUB_ISSUES_API_URL.format(repo_path=path) # Ping github's api for project issues # :TODO: non-github projects are hitting here and shouldn't be! got = get_github_api(issues_url, headers={'If-None-Match': project.last_updated_issues}) # Verify that content has not been modified since last run if got.status_code == 304: # :::here (issue/true) db.session.execute(db.update(Issue, values={'keep': True}).where(Issue.project_id == project.id)) logging.info('Issues %s have not changed since last update', issues_url) elif got.status_code not in range(400, 499): # Update project's last_updated_issue field project.last_updated_issues = unicode(got.headers['ETag']) db.session.add(project) responses = get_adjoined_json_lists(got, headers={'If-None-Match': project.last_updated_issues}) # Save each issue in response for issue in responses: # Type check the issue, we are expecting a dictionary if isinstance(issue, dict): # Pull requests are returned along with issues. Skip them. if "/pull/" in issue['html_url']: continue issue_dict = dict(title=issue['title'], html_url=issue['html_url'], body=issue['body'], project_id=project.id, labels=issue['labels']) issues.append(issue_dict) else: logging.error('Issue for project %s is not a dictionary', project.name) return issues
def update(self): db.update(table='users', values={ 'first_login': self.first_login, 'banned': self.banned, 'admin': self.admin }, params={'ip': self.ip}) return 1
def remove_admin(self, user): admins = json.loads( db.select(table='boards', fields=['admins'], params={'name': self.name})) admins.remove(user.id) db.update(table='boards', values={'admins': admins}, params={'name': self.name}) return 1
def drop_club(usr_id, club_id): delete(DB.CLUBS, 'DELETE FROM club_user_xref WHERE usr_id=%s AND club_id=%s', [usr_id, club_id]) enrollment_count = query_one(DB.CLUBS, "SELECT enrollment_count " "FROM club " "WHERE club_id = %s", club_id) query = "UPDATE club SET enrollment_count = %s WHERE club_id = %s" params = [enrollment_count[0] - 1, club_id] update(DB.CLUBS, query, params)
def put(self): u = authorize(request) id = get_request_arg('id', int, required=True) if not db.exists('POST').where(id=id): abort(404, 'Post Not Found') p = db.select('POST').where(id=id).execute() likes = text_list_to_set(p[4], process_f=lambda x: int(x)) likes.discard(u[0]) likes = set_to_text_list(likes) db.update('POST').set(likes=likes).where(id=id).execute() return {'message': 'success'}
def remove_student(student_id, club_id): delete(DB.CLUBS, 'DELETE FROM club_user_xref WHERE usr_id=%s AND club_id=%s', [student_id, club_id]) enrollment_count = query_one(DB.CLUBS, "SELECT enrollment_count " "FROM club " "WHERE club_id = %s", club_id) query = "UPDATE club SET enrollment_count = %s WHERE club_id = %s" params = [enrollment_count[0] - 1, club_id] update(DB.CLUBS, query, params) return False
def commit_bet(self, bet, balance_change): if bet.player_id != self.id: raise Exception("Player id doesnt match with bets player id") won = bet.outcome == bet.bet_on changes = {} changes['balance'] = "balance + ({})".format(str(balance_change)) changes['number_of_bets'] = "number_of_bets + 1" changes['wagered'] = "wagered + {}".format(bet.amount) if won: changes['number_of_bets_won'] = "number_of_bets_won + 1" where = "id = {}".format(self.id) db.update('players', changes, where)
def enroll_user(usr_id, club_id): print(usr_id, club_id) insert(DB.CLUBS, 'INSERT INTO club_user_xref (club_id, usr_id) VALUES (%s, %s) ' 'ON DUPLICATE KEY UPDATE club_id=club_id', [club_id, usr_id]) enrollment_count = query_one(DB.CLUBS, "SELECT enrollment_count " "FROM club " "WHERE club_id = %s", club_id) query = "UPDATE club SET enrollment_count = %s WHERE club_id = %s" params = [enrollment_count[0] + 1, club_id] update(DB.CLUBS, query, params)
def add_admin(self, user): admins = json.loads( db.select(table='boards', fields=['admins'], params={'name': self.name})) if user.id in admins: return 1 admins.append(user.id) db.update(table='boards', values={'admins': admins}, params={'name': self.name}) return 1
def POST(self, id): item = db.get_from_table('item', int(id))[0] form = new.form() if not form.validates(): form.fill(item) return render.edit(form, item, self.title, self.type, []) db.update('item', id, description=form.d.description, rate=form.d.rate, hrs=form.d.hrs, date=form.d.date ) raise web.seeother('/invoices/' + str(item.invoice_id))
def dao_upsert_sprint(metric): db_metric = db.Session().query(TeamMetric).filter_by( project_id=metric.project_id, sprint_id=str(metric.sprint_id)).first() if db_metric: db.update(TeamMetric, filters={ 'project_id': metric.project_id, 'sprint_id': metric.sprint_id }, **metric.__dict__) else: db.save(TeamMetric(**metric.__dict__))
def POST(self, id): form = new.form() invoice = db.get_from_table('invoice', int(id)) if not form.validates(): return render.edit(invoice, form) client = db.get_client_id(form.d.client) db.update('invoice', id, project_title=form.d.title, description=form.d.description, client_id=client, date=form.d.date ) raise web.seeother('/invoices')
def get_issues(org_name): ''' Get github issues associated to each Organization's Projects. ''' issues = [] labels = [] # Flush the current db session to save projects added in current run db.session.flush() # Only grab this organizations projects projects = db.session.query(Project).filter(Project.organization_name == org_name).all() # Populate issues for each project for project in projects: # Mark this projects issues for deletion db.session.execute(db.update(Issue, values={'keep': False}).where(Issue.project_id == project.id)) # Get github issues api url _, host, path, _, _, _ = urlparse(project.code_url) issues_url = 'https://api.github.com/repos' + path + '/issues' # Ping github's api for project issues got = get_github_api(issues_url, headers={'If-None-Match': project.last_updated_issues}) # Verify if content has not been modified since last run if got.status_code == 304: db.session.execute(db.update(Issue, values={'keep': True}).where(Issue.project_id == project.id)) logging.info('Issues %s have not changed since last update', issues_url) elif not got.status_code in range(400,499): # Update project's last_updated_issue field project.last_updated_issues = got.headers['ETag'] db.session.add(project) responses = get_adjoined_json_lists(got, headers={'If-None-Match': project.last_updated_issues}) # Save each issue in response for issue in responses: # Type check the issue, we are expecting a dictionary if type(issue) == type({}): # Pull requests are returned along with issues. Skip them. if "/pull/" in issue['html_url']: continue issue_dict = dict(title=issue['title'], html_url=issue['html_url'], body=issue['body'], project_id=project.id) issues.append(issue_dict) labels.append(issue['labels']) else: logging.error('Issue for project %s is not a dictionary', project.name) return issues, labels
def put(self): u = get_dummy_user() id = request.args.get('id', None) if not id: abort(400, 'Malformed request') id = int(id) if not db.exists('POST').where(id=id): abort(400, 'Malformed request') p = db.select('POST').where(id=id).execute() likes = text_list_to_set(p[4], process_f=lambda x: int(x)) likes.discard(u[0]) likes = set_to_text_list(likes) db.update('POST').set(likes=likes).where(id=id).execute() return {'message': 'success'}
def put(self): u = authorize(request) try: id = int(request.args.get('id', None)) except: abort(400, 'Malformed request') if not db.exists('POST').where(id=id): abort(400, 'Malformed request') p = db.select('POST').where(id=id).execute() likes = text_list_to_set(p[4], process_f=lambda x: int(x)) likes.add(u[0]) likes = set_to_text_list(likes) db.update('POST').set(likes=likes).where(id=id).execute() return {'message': 'success'}
def put(self): u = authorize(request) try: id = int(request.args.get('id',None)) except: abort(400, 'Malformed request') if not db.exists('POST').where(id=id): abort(400, 'Malformed request') p = db.select('POST').where(id=id).execute() likes = text_list_to_set(p[4],process_f=lambda x: int(x)) likes.discard(u[0]) likes = set_to_text_list(likes) db.update('POST').set(likes=likes).where(id=id).execute() return { 'message': 'success' }
def put(self): u = authorize(request) u_id = int(u[0]) j = get_request_json() allowed_keys = ['password', 'name', 'email'] safe = {} valid_keys = [k for k in j.keys() if k in allowed_keys] if len(valid_keys) < 1: abort(400, 'Expected at least one field to change') if "password" in valid_keys and j["password"] == "": abort(400, 'Password cannot be empty') for k in valid_keys: safe[k] = j[k] db.update('USER').set(**safe).where(id=u_id).execute() return {"msg": "success"}
def dao_upsert_git_metric(metric): db_metric = db.Session().query(GitMetric).filter_by( team_id=metric["team_id"], name=metric["name"], pr_number=metric["pr_number"]).first() if db_metric: db.update(GitMetric, filters={ 'team_id': metric["team_id"], 'name': metric["name"], 'pr_number': metric["pr_number"] }, **metric) else: db.save(GitMetric(**metric))
def put(self): u = authorize(request) u_id = int(u[0]) follow_list = text_list_to_set(u[4]) to_follow = request.args.get('username',None) if to_follow == None or not db.exists('USER').where(username=to_follow): abort(400,'Malformed Request') if to_follow == u[1]: abort(400,'Malformed Request') to_follow = db.select('USER').where(username=to_follow).execute()[0] if to_follow not in follow_list: db.raw('UPDATE USERS SET FOLLOWED_NUM = FOLLOWED_NUM + 1 WHERE ID = ?',[to_follow]) follow_list.add(to_follow) db.update('USER').set(following=set_to_text_list(follow_list)).where(id=u_id).execute() return { 'message': 'success' }
def POST(self, id): client = db.get_from_table('client', int(id))[0] form = new.form() if not form.validates(): form.fill(client) return render.edit(form, client, self.title, self.type, []) db.update('client', id, name=form.d.name, address=form.d.address, city=form.d.city, state=form.d.state, zip_code=form.d.zip_code, phone=form.d.phone, email=form.d.email, contact=form.d.contact ) raise web.seeother('/clients')
def put(self): u = authorize(request) u_id = int(u[0]) follow_list = text_list_to_set(u[4],process_f=lambda x: int(x)) to_follow = request.args.get('username',None) if to_follow == None or not db.exists('USER').where(username=to_follow): abort(400,'Malformed Request') if to_follow == u[1]: abort(400,'Malformed Request') to_follow = db.select('USER').where(username=to_follow).execute()[0] if to_follow not in follow_list: db.raw('UPDATE USERS SET FOLLOWED_NUM = FOLLOWED_NUM + 1 WHERE ID = ?',[to_follow]) follow_list.add(to_follow) db.update('USER').set(following=set_to_text_list(follow_list)).where(id=u_id).execute() return { 'message': 'success' }
def put(self): u = get_dummy_user() id = request.args.get('id',None) if not id: abort(400, 'Malformed request') id = int(id) if not db.exists('POST').where(id=id): abort(400, 'Malformed request') p = db.select('POST').where(id=id).execute() likes = text_list_to_set(p[4],process_f=lambda x:int(x)) likes.add(u[0]) likes = set_to_text_list(likes) db.update('POST').set(likes=likes).where(id=id).execute() return { 'message': 'success' }
def put(self): u = get_dummy_user() u_id = int(u[0]) if not request.json: abort(400, 'Malformed request') allowed_keys = ['password', 'name', 'email'] safe = {} valid_keys = [k for k in request.json.keys() if k in allowed_keys] if len(valid_keys) < 1: abort(400, 'Malformed request') if "password" in valid_keys and request.json["password"] == "": abort(400, 'Malformed request') for k in valid_keys: safe[k] = request.json[k] db.update('USER').set(**safe).where(id=u_id).execute() return {"message": "success"}
def put(self): u = authorize(request) j = get_request_json() id = get_request_arg('id', int, required=True) if not db.exists('POST').where(id=id): abort(404, 'Post Not Found') (comment, ) = unpack(j, 'comment') if comment == "": abort(400, 'Comment cannot be empty') comment_id = db.insert('COMMENT').with_values( comment=comment, author=u[1], published=str(time.time())).execute() p = db.select('POST').where(id=id).execute() comment_list = text_list_to_set(p[7], process_f=lambda x: int(x)) comment_list.add(comment_id) comment_list = set_to_text_list(comment_list) db.update('POST').set(comments=comment_list).where(id=id).execute() return {'message': 'success'}
def post(self): j = get_request_json() (un, ps) = unpack(j, 'username', 'password') if not db.exists('USER').where(username=un, password=ps): abort(403, 'Invalid Username/Password') t = gen_token() db_r = db.update('USER').set(curr_token=t).where(username=un) db_r.execute() return {'token': t}
def put(self): u = authorize(request) u_id = int(u[0]) follow_list = text_list_to_set(u[4], process_f=lambda x: int(x)) to_follow = get_request_arg('username', required=True) if not db.exists('USER').where(username=to_follow): abort(404, 'User Not Found') if to_follow == u[1]: abort(400, "Sorry, you can't follow yourself.") to_follow = db.select('USER').where(username=to_follow).execute()[0] if to_follow not in follow_list: db.raw( 'UPDATE USERS SET FOLLOWED_NUM = FOLLOWED_NUM + 1 WHERE ID = ?', [to_follow]) follow_list.add(to_follow) db.update('USER').set(following=set_to_text_list(follow_list)).where( id=u_id).execute() return {'message': 'success'}
def put(self): u = authorize(request) u_id = int(u[0]) if not request.json: abort(400, 'Malformed request') allowed_keys=['password','name','email'] safe = {} valid_keys = [k for k in request.json.keys() if k in allowed_keys] if len(valid_keys) < 1: abort(400, 'Malformed request') if "password" in valid_keys and request.json["password"] == "": abort(400, 'Malformed request') for k in valid_keys: safe[k] = request.json[k] db.update('USER').set(**safe).where(id=u_id).execute() return { "msg": "success" }
def post(self): if not request.json: abort(400, 'Malformed Request') (un, ps) = unpack(request.json, 'username', 'password') if not db.exists('USER').where(username=un, password=ps): abort(403, 'Invalid Username/Password') t = gen_token() db_r = db.update('USER').set(curr_token=t).where(username=un) db_r.execute() return {'token': t}
def ban(self, duration=0): db.update(table='users', values={'banned': '1'}, params={'ip': self.ip}) if duration > 0: db.db.execute( """ CREATE EVENT `%sban` ON SCHEDULE AT CURRENT_TIMESTAMP + INTERVAL %s HOUR ON COMPLETION NOT PRESERVE DO BEGIN UPDATE users SET banned=0 WHERE ip=%s END; """, ( self.ip, duration, self.ip, )) return 1
def put(self): u = get_dummy_user() u_id = int(u[0]) following = text_list_to_set(u[4], process_f=lambda x: int(x)) to_follow = request.args.get('username', None) if to_follow == u[1]: abort(400, 'Malformed Request') if to_follow == None or not db.exists('USER').where( username=to_follow): abort(400, 'Malformed Request Or Unknown username') to_follow = db.select('USER').where(username=to_follow).execute()[0] if to_follow in following: db.raw( 'UPDATE USERS SET FOLLOWED_NUM = FOLLOWED_NUM - 1 WHERE ID = ?', [to_follow]) following.discard(to_follow) db.update('USER').set(following=set_to_text_list(following)).where( id=u_id).execute() return {'message': 'success'}
def post(self): if not request.json: abort(400,'Malformed Request') (un,ps) = unpack(request.json,'username','password') if not db.exists('USER').where(username=un,password=ps): abort(403,'Invalid Username/Password') t = gen_token() db_r = db.update('USER').set(curr_token=t).where(username=un) db_r.execute() return { 'token': t }
def update(uuid, **kwargs): gallery = Gallery.get(uuid=uuid) if not gallery.published and kwargs.get('published', False): kwargs['published_at'] = datetime.datetime.utcnow() title = Gallery.create_url_title(kwargs.get('name', gallery.name)) GalleryTitle.add_title(uuid, title) gallery = update(gallery, kwargs) for item_data in kwargs.get('items', []): if 'gallery_uuid' in item_data.keys(): item_data.pop('gallery_uuid') if item_data.get('uuid'): GalleryItem.update(item_data.pop('uuid'), **item_data) else: GalleryItem.create(gallery_uuid=gallery.uuid, **item_data) return gallery
def update_gallery(uuid, **kwargs): gallery = get(Gallery, uuid=uuid) if not gallery.published and kwargs.get('published', False): kwargs['published_at'] = datetime.datetime.utcnow() gallery = update(gallery, kwargs) current_items = [item.get('uuid') for item in kwargs.get('items', [])] item_list = get_list(GalleryItem, gallery_uuid=gallery.uuid) delete_items = [item.uuid for item in item_list if item.uuid not in current_items] for uuid in delete_items: GalleryItem.delete(uuid) for item in kwargs.get('items', []): if item.get('uuid'): GalleryItem.update(uuid=item.pop('uuid'), **item) else: item['gallery_uuid'] = gallery.uuid GalleryItem.add_item(**item) return gallery.to_dict()
def update_asana_attribute(uuid, **kwargs): asana_attribute = get(AsanaAttribute, uuid) update(asana_attribute, **kwargs) return asana_attribute.to_dict()
def update_asana(uuid, **kwargs): asana = get(Asana, uuid) update(asana, **kwargs) return asana.to_dict()
def update_asana_image(uuid, **kwargs): asana_image = get(AsanaImage, uuid) update(asana_image, **kwargs) return asana_image.to_dict()
def main(org_name=None, org_sources=None): ''' Run update over all organizations. Optionally, update just one. ''' # set org_sources org_sources = org_sources or ORG_SOURCES_FILENAME # Collect a set of fresh organization names. organization_names = set() # Retrieve all organizations and shuffle the list in place. orgs_info = get_organizations(org_sources) shuffle(orgs_info) if org_name: orgs_info = [org for org in orgs_info if org['name'] == org_name] # Iterate over organizations and projects, saving them to db.session. for org_info in orgs_info: if not is_safe_name(org_info['name']): error_dict = { "error": unicode('ValueError: Bad organization name: "%s"' % org_info['name']), "time": datetime.now() } new_error = Error(**error_dict) db.session.add(new_error) # commit the error db.session.commit() continue try: filter = Organization.name == org_info['name'] existing_org = db.session.query(Organization).filter(filter).first() organization_names.add(org_info['name']) # Mark everything associated with this organization for deletion at first. # :::here (event/false, story/false, project/false, organization/false) db.session.execute(db.update(Event, values={'keep': False}).where(Event.organization_name == org_info['name'])) db.session.execute(db.update(Story, values={'keep': False}).where(Story.organization_name == org_info['name'])) db.session.execute(db.update(Project, values={'keep': False}).where(Project.organization_name == org_info['name'])) db.session.execute(db.update(Organization, values={'keep': False}).where(Organization.name == org_info['name'])) # commit the false keeps db.session.commit() # Empty lat longs are okay. if 'latitude' in org_info: if not org_info['latitude']: org_info['latitude'] = None if 'longitude' in org_info: if not org_info['longitude']: org_info['longitude'] = None organization = save_organization_info(db.session, org_info) organization_names.add(organization.name) # flush the organization db.session.flush() if organization.rss or organization.website: logging.info("Gathering all of %s's stories." % organization.name) stories = get_stories(organization) if stories: for story_info in stories: save_story_info(db.session, story_info) # flush the stories db.session.flush() if organization.projects_list_url: logging.info("Gathering all of %s's projects." % organization.name) projects = get_projects(organization) for proj_dict in projects: save_project_info(db.session, proj_dict) # flush the projects db.session.flush() if organization.events_url: if not meetup_key: logging.error("No Meetup.com key set.") if 'meetup.com' not in organization.events_url: logging.error("Only Meetup.com events work right now.") else: logging.info("Gathering all of %s's events." % organization.name) identifier = get_event_group_identifier(organization.events_url) if identifier: for event in get_meetup_events(organization, identifier): save_event_info(db.session, event) # flush the events db.session.flush() else: logging.error("%s does not have a valid events url" % organization.name) # Get issues for all of the projects logging.info("Gathering all of %s's open GitHub issues." % organization.name) issues = get_issues(organization.name) for issue in issues: save_issue(db.session, issue) # flush the issues db.session.flush() for issue in issues: save_labels(db.session, issue) # commit everything db.session.commit() # Remove everything marked for deletion. # :::here (event/delete, story/delete, project/delete, issue/delete, organization/delete) db.session.query(Event).filter(Event.keep == False).delete() db.session.query(Story).filter(Story.keep == False).delete() db.session.query(Issue).filter(Issue.keep == False).delete() db.session.query(Project).filter(Project.keep == False).delete() db.session.query(Organization).filter(Organization.keep == False).delete() # commit objects deleted for keep=False db.session.commit() except: # Raise the error, get out of main(), and don't commit the transaction. raise else: # Commit and move on to the next organization. # final commit before moving on to the next organization db.session.commit() # prune orphaned organizations if no organization name was passed if not org_name: for bad_org in db.session.query(Organization): if bad_org.name in organization_names: continue # delete orphaned organizations, all other deletions will cascade db.session.execute(db.delete(Organization).where(Organization.name == bad_org.name)) # commit for deleting orphaned organizations db.session.commit()
def main(org_name=None, minimum_age=3*3600): ''' Run update over all organizations. Optionally, update just one. Also optionally, reset minimum age to trigger org update, in seconds. ''' # Set a single cutoff timestamp for orgs we'll look at. maximum_updated = time() - minimum_age # Keep a set of fresh organization names. organization_names = set() # Retrieve all organizations and shuffle the list in place. orgs_info = get_organizations() shuffle(orgs_info) if org_name: orgs_info = [org for org in orgs_info if org['name'] == org_name] # Iterate over organizations and projects, saving them to db.session. for org_info in orgs_info: if not is_safe_name(org_info['name']): error_dict = { "error" : 'ValueError: Bad organization name: "%s"' % org_info['name'], "time" : datetime.now() } new_error = Error(**error_dict) db.session.add(new_error) db.session.commit() continue try: filter = Organization.name == org_info['name'] existing_org = db.session.query(Organization).filter(filter).first() organization_names.add(org_info['name']) if existing_org and not org_name: if existing_org.last_updated > maximum_updated: # Skip this organization, it's been updated too recently. logging.info("Skipping update for {0}".format(org_info['name'].encode('utf8'))) continue # Mark everything in this organization for deletion at first. db.session.execute(db.update(Event, values={'keep': False}).where(Event.organization_name == org_info['name'])) db.session.execute(db.update(Story, values={'keep': False}).where(Story.organization_name == org_info['name'])) db.session.execute(db.update(Project, values={'keep': False}).where(Project.organization_name == org_info['name'])) db.session.execute(db.update(Organization, values={'keep': False}).where(Organization.name == org_info['name'])) organization = save_organization_info(db.session, org_info) organization_names.add(organization.name) if organization.rss or organization.website: logging.info("Gathering all of %s's stories." % organization.name) stories = get_stories(organization) if stories: for story_info in stories: save_story_info(db.session, story_info) if organization.projects_list_url: logging.info("Gathering all of %s's projects." % organization.name) projects = get_projects(organization) for proj_info in projects: save_project_info(db.session, proj_info) if organization.events_url: if not meetup_key: logging.error("No Meetup.com key set.") else: logging.info("Gathering all of %s's events." % organization.name) identifier = get_event_group_identifier(organization.events_url) if identifier: for event in get_meetup_events(organization, identifier): save_event_info(db.session, event) else: logging.error("%s does not have a valid events url" % organization.name) # Get issues for all of the projects logging.info("Gathering all of %s's project's issues." % organization.name) issues = get_issues(organization.name) for issue_info in issues: save_issue_info(db.session, issue_info) # Remove everything marked for deletion. db.session.query(Event).filter(not Event.keep).delete() db.session.query(Story).filter(not Story.keep).delete() db.session.query(Project).filter(not Project.keep).delete() db.session.query(Issue).filter(not Issue.keep).delete() db.session.query(Organization).filter(not Organization.keep).delete() except: # Raise the error, get out of main(), and don't commit the transaction. raise else: # Commit and move on to the next organization. db.session.commit() # Stop right here if an org name was specified. if org_name: return # Delete any organization not found on this round. for bad_org in db.session.query(Organization): if bad_org.name in organization_names: continue db.session.execute(db.delete(Event).where(Event.organization_name == bad_org.name)) db.session.execute(db.delete(Story).where(Story.organization_name == bad_org.name)) db.session.execute(db.delete(Project).where(Project.organization_name == bad_org.name)) db.session.execute(db.delete(Organization).where(Organization.name == bad_org.name)) db.session.commit()
def main(org_name=None, org_sources=None): ''' Run update over all organizations. Optionally, update just one. ''' # Keep a set of fresh organization names. organization_names = set() # Retrieve all organizations and shuffle the list in place. orgs_info = get_organizations(org_sources) shuffle(orgs_info) if org_name: orgs_info = [org for org in orgs_info if org['name'] == org_name] # Iterate over organizations and projects, saving them to db.session. for org_info in orgs_info: if not is_safe_name(org_info['name']): error_dict = { "error" : 'ValueError: Bad organization name: "%s"' % org_info['name'], "time" : datetime.now() } new_error = Error(**error_dict) db.session.add(new_error) db.session.commit() continue try: filter = Organization.name == org_info['name'] existing_org = db.session.query(Organization).filter(filter).first() organization_names.add(org_info['name']) # Mark everything in this organization for deletion at first. db.session.execute(db.update(Event, values={'keep': False}).where(Event.organization_name == org_info['name'])) db.session.execute(db.update(Story, values={'keep': False}).where(Story.organization_name == org_info['name'])) db.session.execute(db.update(Project, values={'keep': False}).where(Project.organization_name == org_info['name'])) db.session.execute(db.update(Organization, values={'keep': False}).where(Organization.name == org_info['name'])) # Empty lat longs are okay. if 'latitude' in org_info: if not org_info['latitude']: org_info['latitude'] = None if 'longitude' in org_info: if not org_info['longitude']: org_info['longitude'] = None organization = save_organization_info(db.session, org_info) organization_names.add(organization.name) if organization.rss or organization.website: logging.info("Gathering all of %s's stories." % organization.name) stories = get_stories(organization) if stories: for story_info in stories: save_story_info(db.session, story_info) if organization.projects_list_url: logging.info("Gathering all of %s's projects." % organization.name) projects = get_projects(organization) for proj_info in projects: save_project_info(db.session, proj_info) if organization.events_url: if not meetup_key: logging.error("No Meetup.com key set.") if 'meetup.com' not in organization.events_url: logging.error("Only Meetup.com events work right now.") else: logging.info("Gathering all of %s's events." % organization.name) identifier = get_event_group_identifier(organization.events_url) if identifier: for event in get_meetup_events(organization, identifier): save_event_info(db.session, event) else: logging.error("%s does not have a valid events url" % organization.name) # Get issues for all of the projects logging.info("Gathering all of %s's open GitHub issues." % organization.name) issues, labels = get_issues(organization.name) for i in range(0,len(issues)): save_issue_info(db.session, issues[i], labels[i]) # Remove everything marked for deletion. db.session.query(Event).filter(not Event.keep).delete() db.session.query(Story).filter(not Story.keep).delete() db.session.query(Project).filter(not Project.keep).delete() db.session.query(Issue).filter(Issue.keep == False).delete() db.session.query(Organization).filter(not Organization.keep).delete() except: # Raise the error, get out of main(), and don't commit the transaction. raise else: # Commit and move on to the next organization. db.session.commit() # Stop right here if an org name was specified. if org_name: return # Delete any organization not found on this round. for bad_org in db.session.query(Organization): if bad_org.name in organization_names: continue db.session.execute(db.delete(Event).where(Event.organization_name == bad_org.name)) db.session.execute(db.delete(Story).where(Story.organization_name == bad_org.name)) db.session.execute(db.delete(Project).where(Project.organization_name == bad_org.name)) db.session.execute(db.delete(Organization).where(Organization.name == bad_org.name)) db.session.commit()
# project['github_details']['project_needs'] = [] url = all_github_attributes['issues_url'].replace('{/number}', '') got = get(url, auth=github_auth, params=dict(labels='project-needs')) # Check if GitHub Issues are disabled if all_github_attributes['has_issues']: for issue in got.json(): project_need = dict(title=issue['title'], issue_url=issue['html_url']) project['github_details']['project_needs'].append(project_need) if __name__ == "__main__": # Mark all projects for deletion at first. db.session.execute(db.update(Project, values={Project.keep: False})) # all_projects = [] for organization in get_organizations(): if not organization['projects_list_url']: continue print 'Gathering all of ' + organization['name']+ "'s projects." projects = get_projects(organization['name'], organization['projects_list_url']) for project in projects: # Mark this project for safe-keeping project['keep'] = True
def main(org_name=None): ''' Run update over all organizations. Optionally, update just one. ''' # Keep a set of fresh organization names. organization_names = set() # Retrieve all organizations and shuffle the list in place. orgs_info = get_organizations() shuffle(orgs_info) if org_name: orgs_info = [org for org in orgs_info if org['name'] == org_name] # Iterate over organizations and projects, saving them to db.session. for org_info in orgs_info: try: # Mark everything in this organization for deletion at first. db.session.execute(db.update(Event, values={'keep': False}).where(Event.organization_name == org_info['name'])) db.session.execute(db.update(Story, values={'keep': False}).where(Story.organization_name == org_info['name'])) db.session.execute(db.update(Project, values={'keep': False}).where(Project.organization_name == org_info['name'])) db.session.execute(db.update(Organization, values={'keep': False}).where(Organization.name == org_info['name'])) organization = save_organization_info(db.session, org_info) organization_names.add(organization.name) if organization.rss or organization.website: logging.info("Gathering all of %s's stories." % unidecode(organization.name)) stories = get_stories(organization) if stories: for story_info in stories: save_story_info(db.session, story_info) if organization.projects_list_url: logging.info("Gathering all of %s's projects." % unidecode(organization.name)) projects = get_projects(organization) for proj_info in projects: save_project_info(db.session, proj_info) if organization.events_url: logging.info("Gathering all of %s's events." % unidecode(organization.name)) identifier = get_event_group_identifier(organization.events_url) if identifier: for event in get_meetup_events(organization, identifier): save_event_info(db.session, event) else: logging.error("%s does not have a valid events url" % unidecode(organization.name)) # Remove everything marked for deletion. db.session.execute(db.delete(Event).where(Event.keep == False)) db.session.execute(db.delete(Story).where(Story.keep == False)) db.session.execute(db.delete(Project).where(Project.keep == False)) db.session.execute(db.delete(Organization).where(Organization.keep == False)) except: # Raise the error, get out of main(), and don't commit the transaction. raise else: # Commit and move on to the next organization. db.session.commit() # Stop right here if an org name was specified. if org_name: return # Delete any organization not found on this round. for bad_org in db.session.query(Organization): if bad_org.name in organization_names: continue db.session.execute(db.delete(Event).where(Event.organization_name == bad_org.name)) db.session.execute(db.delete(Story).where(Story.organization_name == bad_org.name)) db.session.execute(db.delete(Project).where(Project.organization_name == bad_org.name)) db.session.execute(db.delete(Organization).where(Organization.name == bad_org.name)) db.session.commit()
def update(uuid, **kwargs): item = get(GalleryItem, uuid=uuid) item = update(item, kwargs) return item.to_dict()
def update_talk(uuid, **kwargs): talk = get(Talk, uuid=uuid) talk = update(talk, kwargs) return talk.to_dict()