def get(self): u = authorize(request) u_id = request.args.get('id',None) username = request.args.get('username',None) # extract information from paramtaters if u_id or username: if u_id and db.exists("USER").where(id=u_id): u_id = int(u_id) elif username and db.exists("USER").where(username=username): u_id = int(db.select("USER").where(username=username).execute()[0]) else: abort(400,'Malformed Request') else: u_id = int(u[0]) # get information u = db.select('USER').where(id=u_id).execute() u_username = u[1] follow_list = text_list_to_set(u[4]) posts_raw = db.select_all('POST').where(author=u_username).execute() posts = [post[0] for post in posts_raw] return { 'username': u[1], 'name': u[2], 'id' : int(u[0]), 'email': u[3], 'following': [int(x) for x in follow_list], 'followed_num': u[5], 'posts': posts }
def get(self): u = authorize(request) u_id = get_request_arg('id', int) username = get_request_arg('username') # extract information from paramtaters if u_id or username: if u_id and db.exists("USER").where(id=u_id): u_id = int(u_id) elif username and db.exists("USER").where(username=username): u_id = int( db.select("USER").where(username=username).execute()[0]) else: abort(404, "User Not Found") else: u_id = int(u[0]) # get information u = db.select('USER').where(id=u_id).execute() u_username = u[1] follow_list = text_list_to_set(u[4]) posts_raw = db.select_all('POST').where(author=u_username).execute() posts = [post[0] for post in posts_raw] return { 'username': u[1], 'name': u[2], 'id': int(u[0]), 'email': u[3], 'following': [int(x) for x in follow_list], 'followed_num': u[5], 'posts': posts }
def activity(activityid): """Render the website's activity page.""" activity = models.Activity.query.filter_by(activityid=activityid).first() event = models.Event.query.filter_by(activityid=activityid).first() total = activitytotal(activityid) allocation = activityallocation(activityid,total) if request.method == "POST": """Get data""" data = request.form if db.session.query(db.exists().where(models.Activity.activityid==activityid)): activity.name = data['name'] activity.statdate = data['startdate'] activity.duration = data['duration'] activity.completed = data['completed'] db.session.add(activity) if db.session.query(db.exists().where(models.Event.activityid==activityid)): event.starttime = data['starttime'] event.endtime = data['endtime'] event.venue = data['endtime'] db.session.add(event) db.commit() if db.session.query(db.exists().where(models.Event.activityid==activityid)).scalar(): return render_template('event.html', event=event, total=total, allocation=allocation) else: return render_template('activity.html', activity=activity, total=total, allocation=allocation)
def titleinfo(titleid): if not db.session.query(db.exists().where(models.Title.titleid==titleid)).scalar(): abort(404) title = db.session.query(models.Title, models.By, models.Author, models.Belongs_to, models.Category,models.Has,models.Phase).join(models.By, models.Title.titleid == models.By.titleid).join(models.Author, models.Author.authorid == models.By.authorid).join(models.Belongs_to, models.Belongs_to.titleid == models.Title.titleid).join(models.Category,models.Category.categoryid == models.Belongs_to.categoryid).join(models.Has,models.Has.titleid == models.Title.titleid).join(models.Phase,models.Phase.phaseid == models.Has.phaseid).filter(models.Title.titleid == titleid,models.Phase.current == True).first() if db.session.query(db.exists().where(models.Publishing.titleid == titleid)).scalar(): pub = models.Publishing.query.filter_by(titleid=titleid).first() else: pub = None if db.session.query(db.exists().where(models.Sales.titleid == titleid)).scalar(): sales = models.Sales.query.filter_by(titleid=titleid).first() else: sales = None if request.method == 'POST': data = request.form if db.session.query(db.exists().where(models.Title.titleid==titleid)).scalar(): title.Title.title = data['title'] title.Title.subtitle = data['subtitle'] title.Title.description = data['description'] title.Title.status = data['status'] db.session.add(title) db.session.commit() return render_template('title.html',title=title, pub=pub,sales=sales)
def get(self): u = get_dummy_user() u_id = request.args.get('id', None) username = request.args.get('username', None) if u_id or username: if u_id and db.exists("USER").where(id=u_id): u_id = int(u_id) elif username and db.exists("USER").where(username=username): u_id = int( db.select("USER").where(username=username).execute()[0]) else: abort(400, 'Malformed Request') else: u_id = int(u[0]) u = db.select('USER').where(id=u_id).execute() u_username = u[1] follow_list = text_list_to_set(u[4]) posts_raw = db.select_all('POST').where(author=u_username).execute() posts = [post[0] for post in posts_raw] return { 'username': u[1], 'name': u[2], 'id': int(u[0]), 'email': u[3], 'following': [int(x) for x in follow_list], 'followed_num': u[5], 'posts': posts }
def task_device_update(nmap_scan): with app.app_context(): devices = device_parser(nmap_scan) for device in devices: if db.session.query(db.exists().where(Devices.ip == device.get('ip'))).scalar() or db.session.query( db.exists().where(Devices.mac == device.get('mac'))).scalar(): pass else: db.session.add(Devices(mac=device.get('mac', 'mac not found'), ip=device.get('ip', 'ip not found'), host=device.get('host', 'ip not found'))) db.session.commit()
def student_add_mac(): form = StudentForm() if form.validate_on_submit(): mac_addresses = form.mac_addresses.data email = form.email.data name = form.name.data if ',' in mac_addresses: mac_addresses_array = mac_addresses.split(',') else: mac_addresses_array = [mac_addresses] for mac_address in mac_addresses_array: if db.session.query( db.exists().where(Student.email == email)).scalar(): student = db.session.query(Student).filter( Student.email == email).first() SID = student.id new_mac = Mac(mac_address=mac_address, student_id=SID) db.session.add(new_mac) db.session.commit() else: new_student = Student(email=email, name=name) db.session.add(new_student) db.session.commit() SID = new_student.id new_mac = Mac(mac_address=mac_address, student_id=SID) db.session.add(new_mac) db.session.commit() flash('Mac Address has been updated!') return redirect(url_for('student_add_mac')) return render_template('studentaddmac.html', title='Student', form=form)
def admin_add_receiver(): try: form = ReceiverForm() if form.validate_on_submit(): name = form.name.data location = form.location.data if db.session.query( db.exists().where(Location.venue == location)).scalar(): location = db.session.query(Location).filter( Location.venue == location).first() LID = location.id else: new_location = Location(venue=location) db.session.add(new_location) db.session.commit() LID = new_location.id new_receiver = Receiver(name=name, location_id=LID) db.session.add(new_receiver) db.session.commit() flash('Receiver has been updated!') return redirect(url_for('admin_add_receiver')) return render_template('adminaddreceiver.html', title='Admin', form=form) except Exception as e: redirect(url_for('admin_add_receiver')) return (str(e))
def result(movie: Tuple[str, str]) -> str: """Get page with review analysis information.""" correct_title, movie_id = movie if db.session.query( db.exists().where(MovieInfo.title == correct_title)).scalar(): movie = (MovieInfo.query.order_by( MovieInfo.movie_id.desc()).filter_by(title=correct_title).first()) if (datetime.today() - movie.search_date).days < 30: new_movie = MovieInfo( title=correct_title, positive_percent=movie.positive_percent, negative_percent=movie.negative_percent, amount_positive_reviews=movie.amount_positive_reviews, amount_negative_reviews=movie.amount_negative_reviews, ) else: predictions = get_predictions(movie_id) positive_percent, negative_percent = get_sentiments_percent( predictions) new_movie = MovieInfo( title=correct_title, positive_percent=positive_percent, negative_percent=negative_percent, amount_positive_reviews=get_amount_positive(predictions), amount_negative_reviews=get_amount_negative(predictions), ) db.session.add(new_movie) db.session.commit() create_history_pdf() return render_template("result.html", movie=new_movie)
def gen(): chars = string.ascii_letters + string.digits length = 5 code = ''.join(choice(chars) for x in range(length)) exists = db.session.query(db.exists().where(Url.new == code)).scalar() if not exists: return code
def resourcelist(activityid): resList = db.session.query(models.Resource, models.Uses).join(models.Uses, models.Resource.resourceid == models.Uses.resourceid).filter(models.Uses.activityid == activityid).all() if request.method == 'GET': h = [] m = [] for resource in resList: human = models.HumanResource.query.filter_by(resourceid=resource.Resource.resourceid).first() if db.session.query(db.exists().where(models.HumanResource.resourceid==resource.Resource.resourceid)).scalar(): h.append({'name':human.name, 'duration':human.duration, 'rate':human.rate, 'total': human.duration * human.rate}) else: material = models.MaterialResource.query.filter_by(resourceid=resource.Resource.resourceid).first() m.append({'name':material.name,'qty':material.qty, 'unitcost':material.unitcost, 'total': material.unitcost * material.qty}) data = {'human':h,'material':m} out = {'error':None, 'data':data, 'message':'Success'} return jsonify(out)
def sales(titleid): """Render the website's sales page.""" if request.method == "POST": """Get data""" data = request.form if db.session.query(db.exists().where(models.Sales.titleid==titleid)).scalar(): record = models.Sales.query.filter_by(titleid == titleid).first() if 'localsales' in data and data['localsales'] != '': record.localsales = data['localsales'] if 'internationalsales' in data and data['internationalsales'] != '': record.internationalsales = data['internationalsales'] if 'regionalsales' in data and data['regionalsales'] != '': record.regionalsales = data['regionalsales'] record.totalsales = record.localsales + record.regionalsales + record.internationalsales db.session.add(record) db.session.commit() return redirect(url_for('titleinfo',titleid=titleid))
def index(): body = request.get_json() alias = body.get('alias') origin = body.get('origin') if request.method == 'POST' and alias is not None: exists = db.session.query( db.exists().where(Url.alias == alias)).scalar() if exists: return {'code': 410, 'message': 'Alias repeat'}, 410 if request.method == 'POST' and alias is None: def gen(): chars = string.ascii_letters + string.digits length = 6 alias = ''.join(choice(chars) for x in range(length)) exists = db.session.query( db.exists().where(Url.alias == alias)).scalar() if not exists: return alias alias = gen() while alias is None: alias = gen() if request.method == 'POST' and alias is not None: if origin is not None: url = Url(alias=alias, origin=origin) db.session.add(url) db.session.commit() else: return {'code': 400, 'message': 'Validation Failed'}, 400 return {'code': 200, 'message': 'ok.'}
def test_registerOrganization1(self): """ register new profile """ email = "*****@*****.**" response = test_app.post( '/register_organization', data=dict( email=email, password="******", phone_number="9173634115", organization_website="newspark.us", organization_name="newspark", organization_description="an online donation platform", organization_street_address="21 East 90th St.", organization_city="New York", organization_state="New York", organization_country="United States", organization_type="nonprofit", year_established=2000 ) ) self.assertEqual(response.status_code, 200) # Check if the database actual contains the new info exists = db.session.query(db.exists().where(Organization.email == email)).scalar() self.assertEqual(exists, True) # Delete entry from database db.session.delete(Organization.query.filter_by(email=email).first()) db.session.commit()
def attendance(): form = AttendanceForm() if form.validate_on_submit(): course_code = form.course_code.data attendance_type = form.attendance_type.data # check if it is a valid course input from the user if db.session.query( db.exists().where(Course.course_code == course_code)).scalar(): course = db.session.query(Course).filter( Course.course_code == course_code).first() course_code = course.course_code course_id = course.id if attendance_type == 'current': return redirect( url_for('displayLiveAttendance', course_code=course_code, course_id=course_id)) else: return redirect( url_for('AttendanceOverview', course_code=course_code, course_id=course_id)) else: flash('Please enter a valid course code!') return render_template('attendance.html', title='Attendance', form=form) return render_template('attendance.html', title='Attendance', form=form)
def GSCO_saving(): form = GSCOSearchForm() if form.validate_on_submit: selected_team = flask.request.values.get('gsco_team') session['selected_team'] = selected_team # check if stats are already in DB name_exists = db.session.query( db.exists().where(GSCO_teams.TEAM_NAME == selected_team)).scalar() if not name_exists: token = "c7eXV50z6g4Y5wKV9o2j0LZLP76AJoR-OE9jIwOeg19XCGB6YaY" url_2 = "https://api.pandascore.co/csgo/teams?token={}".format( token) response_teams = requests.request("GET", url_2) teams_json = response_teams.json() df_teams = pd.DataFrame(teams_json) df_teams = df_teams.dropna(how='any', subset=['image_url']) new_df_teams = df_teams[['id', 'name', 'image_url']] selected_team_logo = new_df_teams.loc[ new_df_teams['name'] == selected_team]['image_url'].values[0] selected_team_id = new_df_teams.loc[new_df_teams['name'] == selected_team]['id'].values[0] gsco_name = GSCO_teams(TEAM_NAME=selected_team, team_logo=selected_team_logo, team_id=str(selected_team_id)) db.session.add(gsco_name) db.session.commit() return redirect(url_for('gsco_display'))
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 site_data_agent(sitename): # no POST of data to this url, handled by jquery to endpoint below. site = Site.query.filter_by(name=sitename).one() form = SiteAgentConfigForm() ## access_key = { "is_enabled": False, "access_key_id": None, "secret_access_key": None } uploader_exists = db.session.query( db.exists().where(SiteDataUploader.site_id == site.id)).one()[0] if uploader_exists: uploader = SiteDataUploader.query.filter_by(site_id=site.id).one() access_key["is_enabled"] = uploader.enabled access_key["access_key_id"] = uploader.aws_access_key_id access_key["secret_access_key"] = uploader.aws_secret_access_key else: uploader = None if request.method == 'GET': # return (str(site) + str(uploader)) return render_template('site_settings/site_data_agent.html', site=site, access_key=access_key)
def get_projects(): """ Returns all projects associated with an organization from a JWT :params: JWT token :return: json object: organization name, projects (without ones that have been deleted, all_projects """ organization_email = get_jwt_identity() # check if already in database exists = db.session.query(db.exists().where(Organization.email == organization_email)).scalar() if exists: organization_name = Organization.query.filter_by(email=organization_email)[0].organization_name projects = [p.serialize() for p in Project.query.filter_by(organization_id=organization_email)] projects_filtered = [p for p in projects if not p['removed']] project_names = set() unique_projects = [] for project in projects_filtered: # print(project['removed']) project_name = project['project_name'] if project_name not in project_names: project_names.add(project_name) unique_projects.append(project) unique_projects.reverse() return jsonify(organization_name=organization_name, projects=unique_projects, all_projects=projects) else: return jsonify("Organization Does Not Exist")
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 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 is_uploaded(book): first, second = False, False exists = db.session.query( db.exists().where(Books.name == (book + '.txt'))).scalar() if not exists: first = True exists = db.session.query( db.exists().where(Books.name == (book + '.epub'))).scalar() if not exists: second = True if first and second: return True else: return False
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 Tereya(): charid = '7' url = "https://the-office.p.rapidapi.com/{}".format(charid) headers = { 'x-rapidapi-host': "the-office.p.rapidapi.com", 'x-rapidapi-key': "666103d036msh1131169c5b9c02bp13d3ecjsna3964c136807" } response = requests.request("GET", url, headers=headers) resp_json = response.json() id = resp_json['id'] name = resp_json['name'] realname= resp_json['realname'] seasons= resp_json['seasons'] # if name does not exist add to table name_exists = db.session.query(db.exists().where(Characters.name == name)).scalar() if not name_exists: char_input = Characters(id=id, name=name, realname=realname, seasons=seasons) db.session.add(char_input) db.session.commit() return render_template('Tereya.html', title='Tereya')
def validate_new(form, field): new = field.data if '/' in new: raise validators.ValidationError("Links may not contain /") if db.session.query(db.exists().where( new == Url.new)).scalar() or (new in forbidden_routes): raise validators.ValidationError("URL already taken.")
def genMOL(csid): stmt = db.session.query(db.exists().where(Chemcmpd.csid==csid)).scalar() if stmt: result = [(cn,sm) for cn,sm in db.session.query(Chemcmpd.cname,Chemcmpd.smi).filter_by(csid=csid)] mol = pybel.readstring('smi',result[0][1]) return mol else: return (f'<strong>{csid} does not exist in the ChemSpider DB!</strong>')
def check_if_group_already_has_eleve_with_qcm(id_groupe: int): q = db.session.query( Utilisateurs, QcmEleve).filter(QcmEleve.id_eleve == Utilisateurs.id).filter( Utilisateurs.id_groupe == id_groupe).first() res = db.session.query( db.exists().where(Utilisateurs.id_groupe == id_groupe)).scalar() return q
def saving(): form = SearchForm() if form.validate_on_submit: fav_short_team = flask.request.values.get('team') url = "https://api-nba-v1.p.rapidapi.com/teams/shortName/{}".\ format(fav_short_team) headers = { 'x-rapidapi-host': "api-nba-v1.p.rapidapi.com", 'x-rapidapi-key': "5a64743a7bmsh79b17ce5d033775p102796jsneae2a4334407" } # API Call response = requests.request("GET", url, headers=headers) # API Response as JSON team_json = response.json() # Find Name and Logo team_logo = team_json['api']['teams'][0]['logo'] team_name = team_json['api']['teams'][0]['fullName'] session['team_name'] = team_name # Find Average Ticket Price CLIENT_ID = "MTg1MDQzOTB8MTU2OTQ1MDUzNC40" # Format input correctly for request formatted_team_name = team_name.replace(" ", "+") # Send a request to seatgeek querying for events involving "team" and authenticating with "CLIENT_ID" # They will send back a json file with all of the information r = requests.get( "https://api.seatgeek.com/2/events?q=" + \ formatted_team_name + "&taxonomies.name=sports&type=nba&client_id=" + CLIENT_ID) x = json.loads(r.content) average_cost = 0 games = 0 for event in x["events"]: average_cost = (average_cost + int(event["stats"]["average_price"])) games = (games + 1) cost_per_game = "{0:.2f}".format(average_cost / games) #check if stats are already in DB name_exists = db.session.query( db.exists().where(NBAStats.TEAM_NAME == team_name)).scalar() if not name_exists: nba_name = NBAStats(TEAM_NAME=team_name, team_logo=team_logo, avg_price=cost_per_game) db.session.add(nba_name) db.session.commit() return redirect(url_for('display'))
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 gen(): chars = string.ascii_letters + string.digits length = 3 code = ''.join(choice(chars) for x in range(length)) print("verifying", code) exists = db.session.query(db.exists().where(Url.new == code)).scalar() if not exists: print("Your new code is:", code) return code
def updateInformation(): form = AdminForm() if form.validate_on_submit(): course_code = form.course_code.data course_code = form.course_code.data start_time = form.start_time.data end_time = form.end_time.data start_date = form.start_date.data end_date = form.end_date.data location = form.location.data student_array = [] student_details = form.student_details.data # filename = secure_filename(student_details.filename) contents = student_details.read() # contents = contents.decode() contents_stripped = contents.rstrip("\r\n") contents_split = contents_stripped.split("\r\n") first_row = True for content in contents_split: if first_row == True: first_row = False else: data = content.split(",") new_name = data[0] new_email = data[1] if not db.session.query(db.exists().where( Student.email == new_email)).scalar(): new_student = Student(email=new_email, name=new_name) db.session.add(new_student) student_array.append(new_student) if db.session.query(Location).filter( Location.venue == location).first() == True: new_location = db.session.query(Location).filter( Location.venue == location).first() else: new_location = Location(venue=location) db.session.add(new_location) db.session.commit() new_course = Course(course_code=course_code, start_time=start_time, end_time=end_time, start_date=start_date, end_date=end_date, location_id=new_location.id, students=student_array) db.session.add(new_course) db.session.commit() flash('Course information has been updated!') return redirect(url_for('updateInformation')) return render_template('updateinformation.html', title='Admin', form=form)
def generate_access_keys(site_id): """ generates AWS user and access key for site data agent, writes to DB, returns values to client via jquery """ # create IAM object from AWS utils iam = AwsIamManager(site_id) # get enabled state of site data agent from client over ajax is_enabled_ajax = request.args.get('isChecked', 0, type=int) # jquery ajax var isChecked sends int 0 as False and int 1 as True if is_enabled_ajax == 0: is_enabled = False else: is_enabled = True ######## # SECURITY: need to protect this endpoint with a pre-generated token ######## # delete IAM user and access keys before generating a new set resp = iam.delete_access_key() resp = iam.delete_user() # check if site data agent is enabled if is_enabled: resp = iam.create_user() resp = iam.create_access_key() access_key_id = iam.access_key_id secret_access_key = iam.secret_access_key else: access_key_id = None secret_access_key = None # get record from sitedatauploader table or instantiate a new one if none # check if record for site exists in sitedatauploader table uploader_exists = db.session.query( db.exists().where(SiteDataUploader.site_id == site_id)).one()[0] if uploader_exists: uploader = SiteDataUploader.query.filter_by(site_id=site_id).one() else: # if doesnt exist already, create record uploader = SiteDataUploader() uploader.site_id = site_id uploader.aws_username = iam.aws_s3_uploader_iam_username db.session.add(uploader) uploader.enabled = is_enabled uploader.aws_username = iam.aws_s3_uploader_iam_username uploader.aws_access_key_id = access_key_id uploader.aws_secret_access_key = secret_access_key db.session.commit() return jsonify(accessKeyId=access_key_id, secretAccessKey=secret_access_key, isEnabled=str(is_enabled))
def user_register(): form = RegisterForm(request.form) if form.validate_on_submit(): login_taken = db.session.query(db.exists().where(User.nickname == form.nickname.data)).scalar() email_taken = db.session.query(db.exists().where(User.email == form.email.data)).scalar() if login_taken or email_taken: if login_taken: form.nickname.errors.append(u'Nickname already taken. Please try another one') if email_taken: form.email.errors.append(u'E-mail already registered. Please try another one') else: user = User(form.nickname.data, form.password.data, form.email.data) db.session.add(user) db.session.commit() login_user(user) return redirect(url_for('global_index')) return render_template('user_register.html', form=form)
def authorize(r): t = r.headers.get('Authorization',None) if not t: abort(403,'Unsupplied Authorization Token') try: t = t.split(" ")[1] except: abort(403,'Invalid Authorization Token') if not db.exists("USER").where(curr_token=t): abort(403,'Invalid Authorization Token') return db.select("USER").where(curr_token=t).execute()
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 row_exists(col, value): """Check to see if a given row exists in a table. Args: col: The column to check, in the form of a db Model attribute, e.g. `Index.name` or `Packet.sku`. value: The value of the row to check for. Returns: bool: True if row exists, False if not. """ return db.session.query(db.exists().where(col == value)).scalar()
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 delete(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() if p[1] != u[1]: abort(403,'You Are Unauthorized To Make That Request') comment_list = text_list_to_set(p[7]) [db.delete('COMMENT').where(id=c_id).execute() for c_id in comment_list] db.delete('POST').where(id=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 = 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 post(self): if not request.json: abort(400,'Malformed Request') (un,ps,em,n) = unpack(request.json,'username','password','email','name') if db.exists('USER').where(username=un): abort(409, 'Username Taken') if ps == '': abort(400, 'Malformed Request') t = gen_token() db_r = db.insert('USER').with_values( curr_token=t, username=un, password=ps, email=em, name=n ) db_r.execute() return { 'token': t }
def update_score(): try: if not request.form['bow-select'] or \ not request.form['archer-select'] or \ not request.form['round-select'] or \ not request.form['event-select'] or \ not request.form['category-select'] or \ not request.form['date-input'] or \ not request.form['score-hits'] or \ not request.form['score-score'] or \ not request.form['score-golds'] or \ not request.form['score-id'] or \ not request.form['origin']: flash('Incomplete score', 'submission') return redirect(request.form['origin']) except KeyError: flash('Incomplete score', 'submission') return redirect(url_for('.dashboard')) if 'score-xs' in request.form: if not request.form['score-xs']: flash('Incomplete score', 'submission') return redirect(request.form['origin']) if not is_integer(request.form['bow-select']) or \ not is_integer(request.form['archer-select']) or \ not is_integer(request.form['round-select']) or \ not is_integer(request.form['event-select']) or \ not is_category(request.form['category-select']) or \ not is_date(request.form['date-input']) or \ not is_integer(request.form['score-hits']) or \ not is_integer(request.form['score-score']) or \ not is_integer(request.form['score-golds']) or \ not is_integer(request.form['score-id']): flash('Unexpected score information type', 'submission') return redirect(request.form['origin']) if 'score-xs' in request.form: if not is_integer(request.form['score-xs']): flash('Unexpected score information type', 'submission') return redirect(request.form['origin']) if not db.session.query(db.exists().where(Archers.id == request.form['archer-select'])).scalar(): flash('Archer doesn\'t exist', 'submission') return redirect(request.form['origin']) archer = Archers.query.get(request.form['archer-select']) if not db.session.query(db.exists().where(Rounds.id == request.form['round-select'])).scalar(): flash('Round doesn\'t exist', 'submission') return redirect(request.form['origin']) score_round = Rounds.query.get(request.form['round-select']) if not db.session.query(db.exists().where(Events.id == request.form['event-select'])).scalar(): flash('Event doesn\'t exist', 'submission') return redirect(request.form['origin']) event = Events.query.get(request.form['event-select']) if not db.session.query(db.exists().where(BowTypes.id == request.form['bow-select'])).scalar(): flash('Bow type doesn\'t exist', 'submission') return redirect(request.form['origin']) bow_type = BowTypes.query.get(request.form['bow-select']) if int(request.form['score-hits']) not in range(0, score_round.max_hits + 1): flash('Incorrect number of hits', 'submission') return redirect(request.form['origin']) hits = int(request.form['score-hits']) if int(request.form['score-golds']) not in range(0, score_round.max_hits + 1): flash('Incorrect number of golds', 'submission') return redirect(request.form['origin']) golds = int(request.form['score-golds']) if 'score-xs' in request.form: if int(request.form['score-xs']) not in range(0, golds + 1): flash('Incorrect number of Xs', 'submission') return redirect(request.form['origin']) else: if score_round.r_type is 'Clout' or 'Indoors' in score_round.r_type: xs = None else: xs = int(request.form['score-xs']) else: if score_round.r_type is 'Clout' or 'Indoors' in score_round.r_type: xs = None else: xs = 0 if int(request.form['score-score']) not in range(0, score_round.max_score + 1): flash('Incorrect score', 'submission') return redirect(request.form['origin']) score = int(request.form['score-score']) category = category_map(request.form['category-select']) score_date = date.fromtimestamp(mktime(strptime(request.form['date-input'], '%Y-%m-%d'))) try: new_score = 'new' in request.form['score-status'] except KeyError: new_score = False if new_score: score_obj = Scores(archer.id, score_round.id, event.id, bow_type.id, category, score, hits, golds, xs, score_date) db.session.add(score_obj) flash('Added new score successfully', 'submission') else: old_score = Scores.query.get(int(request.form['score-id'])) if not old_score: flash('Original score doesn\'t exist', 'submission') return redirect(request.form['origin']) old_score.archer_id = archer.id old_score.round_id = score_round.id old_score.event_id = event.id old_score.bow_type = bow_type.id old_score.category = category old_score.score = score old_score.num_hits = hits old_score.num_golds = golds old_score.num_xs = xs old_score.date = score_date flash('Updated score successfully', 'submission') db.session.commit() if new_score: return redirect(url_for('admin.add_score')) else: try: return redirect(request.form['origin']) except KeyError: return redirect(url_for('.dashboard'))
def is_exists(column, value): return db.session.query(db.exists().where(column == value)).scalar()
def existsData(id): return db.session.query(db.exists().where(Data.id == id)).scalar()
def gen_token(): token = secrets.token_hex(32) while db.exists("USER").where(curr_token=token): token = secrets.token_hex(32) return token