def insert_standings(standings): try: id_competition = queries.fetch("competitions", ["id"], "name='%s'" % standings['league_name'])[0][0] id_team = queries.fetch("teams", ["id"], "name='%s'" % standings['team'])[0][0] data = {} data['id_competition'] = str(id_competition) data['id_team'] = str(id_team) data['win'] = str(standings['wins']) data['lost'] = str(standings['losses']) data['draw'] = str(standings['draws']) data['goals'] = str(standings['goals']) data['points'] = str(standings['points']) data['year'] = str(standings['year']) id = queries.fetch("standings", ["id"], "id_competition='{}' and id_team='{}' and year='{}' ".format(data['id_competition'],data['id_team'], data['year'])) if id: queries.update("standings", data, "id = '{}'".format(id[0][0])) print("Success update standings - competition - team " + standings['league_name'] + standings['team'], "\n") else: queries.save("standings", data) print("Success saving standings - competition - team " + standings['league_name'] + standings['team'], "\n") except Exception as e: print("GRESKA - insert_standings - ", e, "\n")
def update(self, queryfunc, changes, subpath=None) : """Updates the database by running the query and then running each of the instructions in 'changes'. The update can be restricted to a portion of the database using the 'subpath' argument. The 'changes' argument is a list of path/value pairs. Each value is run with the variable of the queryfunc bound to one of the results of running the queryfunc on the database, and that path in the object is updated to the result of the value.""" queryfunc = util.assert_type(queryfunc, queries.Func) self.lock.write_lock.acquire() try : data = self.data if subpath is not None and assert_type(subpath, queries.Path) : data = subpath.get(data) queries.update(data, queryfunc, changes) except queries.InconsistentData : self.rollback() raise except : # no changes made raise else : self.lock.read_lock.acquire() finally : self.lock.write_lock.release() self.commit() self.lock.read_lock.release()
def update_event(old_data, new_data): try: id_competition = queries.fetch("competitions", ["id"], "name='%s'" % old_data['tournament_part'])[0][0] id_team1 = queries.fetch("teams", ["id"], "name='%s'" % old_data["home"])[0][0] id_team2 = queries.fetch("teams", ["id"], "name='%s'" % old_data["away"])[0][0] if ":" and " " in old_data['time']: old_data['time'] = old_data['time'].split(" ")[0]+str(datetime.datetime.now().year) time = datetime.datetime.strptime(old_data['time'], "%d.%m.%Y") event = queries.fetch("events", ["id"], "time_started='{}' and id_team1={} and id_team2={} and id_competition='{}'".format(old_data['time'], id_team1, id_team2, id_competition)) time = str(time).split(" ")[0] if data['statistics']: update_statistics(old_data['home'], old_data['away'], old_data['time'], old_data['statistics']) if data['summary']: update_summary(old_data['home'], old_data['away'], old_data['time'], old_data['summary']) if event: queries.update("events", new_data, "id = '{}'".format(event[0][0])) print("Success updating event - time - teams " + str(time) + " - " + str(old_data['home']) + " - " + str(old_data['away']), "\n") else: pass print("Cant find Event to update") except Exception as e: print("\nGRESKA - event update - ", e, "\n")
def admin_edit_competition_page(id): form = EditCompetitionForm() imageForm = UploadImageForm() imageFolderPath = os.path.join(os.getcwd(), 'static/images/competitions') if (request.method == 'POST' and form.submit_competition.data or form.validate()): name = form.name.data date = form.date.data country = form.country.data description = form.description.data reward = form.reward.data image = imageForm.image.data filename = select("logo", "competition", "id={}".format(id)) if (image): extension = image.filename.split('.')[1] current_date = time.gmtime() filename = secure_filename("{}_{}.{}".format( id, current_date[0:6], extension)) filePath = os.path.join(imageFolderPath, filename) images = os.listdir(imageFolderPath) digits = int(math.log(int(id), 10)) + 1 for im in images: if (im[digits] == '_' and im[0:digits] == str(id)): os.remove(os.path.join(imageFolderPath, im)) image.save(filePath) elif (image): flash('Please upload a file in JPG format', "danger") print("Before update: ", date) update( "competition", "name='{}', date=DATE('{}'), country='{}', description='{}', reward='{}',logo='{}'" .format(name, date, country, description, reward, filename), "id={}".format(id)) return redirect( url_for('admin_edit.admin_edit_competition_page', id=id)) else: if (session.get('auth_type') != 'Team leader'): flash('No admin privileges...', 'danger') return redirect(url_for('home.home_page')) result = select('id,name,date,country,description,reward', 'competition, logo', 'id={}'.format(id))[0] form.description.data = result[4] return render_template('admin_edit_competition_page.html', form=form, result=result, imgName=result[5], uploadImg=imageForm) return render_template('admin_edit_competition_page.html', form=form, result=result, imgName=result[5], uploadImg=imageForm)
def member_edit_design_page(design_id): auth = session.get('auth_type') if (auth != "Team leader"): flash("Not an authorized person") return redirect(url_for("home.home_page")) typs = select("vehicle_type.id,vehicle_type.name", "vehicle_type") team_id = session.get('team_id') member_id = session.get('member_id') form = EditDesignForm() form.typ.choices = typs if (request.method == 'POST' and form.submit_edit_design.data or form.validate()): name = form.name.data year = form.year.data maxspeed = form.maxspeed.data weight = form.weight.data duration = form.duration.data is_autonomous = form.is_autonomous.data typ = form.typ.data update( "design", "name='{}',year='{}',maxspeed='{}',weight='{}',duration='{}', is_autonomous='{}', team_id='{}', type_of_vehicle = '{}'" .format(name, year, maxspeed, weight, duration, is_autonomous, team_id, typ), where="id={}".format(design_id)) return redirect( url_for("visitor.visitor_teaminfo_page", team_id=team_id)) else: result = select( "design.name,year,maxspeed,weight,duration,is_autonomous,vehicle_type.id", "design join vehicle_type on design.type_of_vehicle=vehicle_type.id", "design.id={}".format(design_id)) print(result) form.name.data = result[0] form.year.data = result[1] form.maxspeed.data = result[2] form.weight.data = result[3] form.duration.data = result[4] form.is_autonomous.data = result[5] form.typ.data = result[6] return render_template("member_edit_design_page.html", form=form, result=result)
def up_del_user(operation): id = request.args['id'] fields = request.json method = request.method if operation == "edit" and method == "PUT": return quer.update("user", id, fields) else if operation == "remove" and method == "DELETE": return quer.delete("user", id) else: return {"status": "error: improper operation"}
def update_summary(team1, team2, time, summary_data): try: id_team1 = queries.fetch("teams", ["id"], "name='%s'" % team1)[0][0] id_team2 = queries.fetch("teams", ["id"], "name='%s'" % team2)[0][0] if ":" and " " in time: time = time.split(" ")[0]+str(datetime.datetime.now().year) time = datetime.datetime.strptime(time, "%Y-%m-%d") event_id = queries.fetch("events", ["id"], "time_started='{}' and id_team1='{}' and id_team2='{}'".format(time, id_team1, id_team2))[0][0] summary={} for i in summary_data: summary["{}".format(i.lower().replace(" ", "_"))] = json.dumps(summary_data[i]).replace('"','\\"') queries.update("summary", summary, "id = '{}'".format(event_id)) print("Success updating summary " + str(summary), "\n") except Exception as e: print("\nGRESKA - summary update - ", e, "\n")
def update_statistics(team1, team2, time, statistics_data): try: id_team1 = queries.fetch("teams", ["id"], "name='%s'" % team1)[0][0] id_team2 = queries.fetch("teams", ["id"], "name='%s'" % team2)[0][0] if ":" and " " in time: time = time.split(" ")[0]+str(datetime.datetime.now().year) time = datetime.datetime.strptime(time, "%Y-%m-%d") event = queries.fetch("events", ["id"], "time_started='{}' and id_team1='{}' and id_team2='{}'".format(time, id_team1, id_team2))[0][0] statistics={} for i in statistics_data: if i.lower().replace(" ","_") in ["yellow_cards", "red_cards", "ball_possession", "shots_on_goal", "shots_off_goal", "corner_kicks", "free_kicks", "fouls", "offsides"]: statistics["team1_{}".format(i.lower().replace(" ", "_"))] = statistics_data[i]["team1"].replace("%", "") statistics["team2_{}".format(i.lower().replace(" ", "_"))] = statistics_data[i]["team2"].replace("%", "") queries.update("statistics", statistics, "id = '{}'".format(event)) print("Success updating statistics " + str(statistics), "\n") except Exception as e: print("\nGRESKA - statistics update - ", e, "\n")
def forgot_page(): active = queries.run("""SELECT current_user""") if active[0][0] == None: active.pop(0) form = LoginForm() active_num = (len(active)) psychologistt = queries.select("name", "psychologist", asDict=True) patientt = queries.select("name", "patient", asDict=True) total_user = len(psychologistt) + len(patientt) if form.validate_on_submit(): queries.update("patient", "password = {}".format(form.password.data), where="mail = '{}'".format(form.mail.data)) return render_template('forgot_page.html', session_id=(session["id"]), session_type=session["type"], form=form, active_num=active_num, total_user=total_user)
def update(conn, asset_id, asset): """ Update an asset in the database. Returns the asset. Asset's asset_id and is_active field is updated before returning. """ del asset['asset_id'] if 'is_active' in asset: asset.pop('is_active') with db.commit(conn) as c: c.execute(queries.update(asset.keys()), asset.values() + [asset_id]) asset.update({'asset_id': asset_id}) asset.update({'is_active': is_active(asset)}) return asset
def up_del(object, operation): id = request.args['id'] fields = request.json method = request.method if object not in {"book", "author"}: return {"status": "error: improper endpoint"} else if operation == "edit" and method == "PUT": return quer.update(object, id, fields) else if operation == "remove" and method == "DELETE": return quer.delete(object, id) else if operation == "create" and method == "POST": return quer.add(object, id, fields) else: return {"status": "error: improper operation"}
def update(conn, asset_id, asset): """ Update an asset in the database. Returns the asset. Asset's asset_id and is_active field is updated before returning. """ del asset['asset_id'] if 'is_active' in asset: asset.pop('is_active') with db.commit(conn) as c: c.execute(queries.update(asset.keys()), asset.values() + [asset_id]) asset.update({'asset_id': asset_id}) if 'start_date' in asset: asset.update({'is_active': is_active(asset)}) return asset
def member_edit_schedule_page(schedule_id): auth = session.get('auth_type') print(auth) if (auth != "Team leader" and auth != "Subteam leader"): flash("Not an authorized person") return redirect(url_for("home.home_page")) member_id = session.get('member_id') form = EditScheduleForm() if (request.method == 'POST' and form.submit_edit_schedule.data or form.validate()): name = form.name.data deadline = form.deadline.data done = form.done.data description = form.description.data budget = form.budget.data update( "schedule", "name='{}',deadline='{}',done='{}',description='{}',budget='{}', member_id='{}'" .format(name, deadline, done, description, budget, member_id), where="id={}".format(schedule_id)) return redirect(url_for("team.team_schedule_page")) else: result = select("schedule.name,deadline,done,description,budget", "schedule", "schedule.id={}".format(schedule_id)) print(result) form.name.data = result[0] form.deadline.data = result[1] form.done.data = result[2] form.description.data = result[3] form.budget.data = result[4] return render_template("member_edit_schedule_page.html", form=form, result=result)
def update(conn, asset_id, asset): """ Update an asset in the database. Returns the asset. Asset's asset_id and is_active field is updated before returning. """ del asset["asset_id"] if "is_active" in asset: asset.pop("is_active") with db.commit(conn) as c: c.execute(queries.update(asset.keys()), asset.values() + [asset_id]) asset.update({"asset_id": asset_id}) if "start_date" in asset: asset.update({"is_active": is_active(asset)}) return asset
def update(): if session.get('logged_in'): if request.form['submit'] == 'Save Changes': conn = queries.getConn('c9') name = request.form.get('username') email = request.form.get('email') phone = request.form.get('phone') bnumber = request.form.get('bnumber') residence = request.form.get('residence') avail = request.form.get('avail') try: updated = queries.update(conn, name, email, phone, residence, avail) except: flash('Unable to Update info') return redirect(url_for('profile')) else: try: bnumber = request.form['bnumber'] # may throw error f = request.files['pic'] mime_type = imghdr.what(f) if mime_type.lower() not in ['jpeg', 'gif', 'png', 'jpg']: raise Exception( 'Not a JPEG, GIF, JPG or PNG: {}'.format(mime_type)) filename = secure_filename('{}.{}'.format(bnumber, mime_type)) pathname = os.path.join(app.config['UPLOADS'], filename) f.save(pathname) flash('Upload successful') conn = queries.getConn('c9') curs = conn.cursor() curs.execute( '''insert into picfile(bnumber,filename) values (%s,%s) on duplicate key update filename = %s''', [bnumber, filename, filename]) return redirect(url_for('profile')) except Exception as err: flash('Upload failed {why}'.format(why=err)) return redirect(url_for('profile')) else: return redirect(request.referrer)
def update(): '''Updates information about current_user''' if session.get('logged_in'): conn = queries.getConn('c9') username = request.form.get('username') print(username) email = request.form.get('email') phone = request.form.get('phone') bnumber = request.form.get('bnumber') residence = request.form.get('residence') avail= request.form.get('availability') print(avail) try: updated = queries.update(conn, bnumber, username, email, phone, residence, avail) print(updated) except: flash('Unable to Update info') return redirect(url_for('profile')) else: return redirect(request.referrer)
def psychologist_page(id): print("AA" * 23, request.form) global adds active = queries.run("""SELECT current_user""") if active[0][0] == None: active.pop(0) active_num = (len(active)) psychologistt = queries.select("name", "psychologist", asDict=True) patientt = queries.select("name", "patient", asDict=True) total_user = len(psychologistt) + len(patientt) if (request.method == "POST"): if ("comment" in request.form): requests = dict(list(request.form.items())) queries.insert( "comment", "patient_id,psychologist_id,comment", "'{}','{}','{}'".format(session["id"], id, requests["comment_content"])) elif ("point" in request.form): requests = dict(list(request.form.items())) selected = queries.select( "id", "point", "patient_id = {} AND psychologist_id = {}".format( session["id"], id)) print("SEEEELELLLLLLLEEEECCCCCTTEEEEEDDDDDDDD") print(selected) if (len(selected) == 0): queries.insert( "point", "point,patient_id,psychologist_id", "'{}','{}','{}'".format(requests["point"], session["id"], id)) else: print("UPDATINGGGGG") queries.update( "point", "point = {}".format(requests["point"]), "patient_id = {} AND psychologist_id = {}".format( session["id"], id)) elif ("give_Add" in request.form): adds.append(id) elif (list(request.form.items())[0][1] == "delete"): com_id = list(request.form.items())[0][0] queries.delete("comment", "comment.id = {}".format(com_id)) elif ("Cancel" in list(request.form.items())[0]): requests = dict(list(request.form.items())) delete_one = list(requests.keys())[0] queries.delete("appointment", "appointment.id={}".format(delete_one)) else: print("HA" * 30, list(request.form.items())) queries.update( "comment", "comment = '{}'".format(list(request.form.items())[0][1]), "id = {}".format(list(request.form.items())[1][0])) queries.update( "comment", "comment = '{}'".format(list(request.form.items())[1][1]), "id = {}".format(list(request.form.items())[0][0])) psychologist = queries.select("id,name,mail,address", "psychologist", "id={}".format(id), asDict=True) point = queries.select("point", "point", "psychologist_id = {}".format(id), asDict=False) sum_ = 0 for i in range(len(point)): sum_ += point[i][0] if (len(point) != 0): sum_ = sum_ / float(len(point)) point = sum_ appointments = queries.select("id,day,time,patient_id,psychologist_id", "appointment", "appointment.psychologist_id={}".format(id), asDict=True) patients = queries.select("name,id", "patient", asDict=True) if isinstance(appointments, dict): appointments = [appointments] comments = queries.select("id,patient_id,psychologist_id,comment", "comment", "comment.psychologist_id = {}".format( psychologist["id"]), asDict=True) if isinstance(comments, dict): comments = [comments] sql = "SELECT appointment.id, appointment.day,appointment.time, patient.name,psychologist.name,psychologist.id FROM patient INNER JOIN appointment ON patient.id = appointment.patient_id INNER JOIN psychologist ON appointment.psychologist_id = psychologist.id WHERE psychologist.id = {};".format( id) joined = queries.run(sql) return render_template("psychologist_page.html", joined=joined, active_num=active_num, total_user=total_user, point=point, comments=comments, psychologist=psychologist, appointments=appointments, patients=patients, session_id=session["id"], session_type=session["type"], asDict=True)
def admin_edit_team_page(id): auth = session.get('auth_type') if (auth != 'admin' and (auth != 'Team leader' and id != session.get('team_id'))): flash('No admin privileges...', 'danger') return redirect(url_for('home.home_page')) form = EditTeamForm() competitions = select("id,name", "competition") form.competition.choices = competitions imgForm = UploadImageForm() imgFolder = os.path.join(os.getcwd(), 'static/images/team') if (request.method == 'POST' and form.submit_team.data or form.validate()): name = form.name.data members = form.memberCtr.data year = form.year.data email = form.email.data address = form.address.data competition = form.competition.data image = imgForm.image.data if (image and '.jpg' in image.filename or '.jpeg' in image.filename or '.png' in image.filename): date = time.gmtime() extension = image.filename.split('.')[1] filename = secure_filename("{}_{}.{}".format( id, date[0:6], extension)) filePath = os.path.join(imgFolder, filename) images = os.listdir(imgFolder) digits = int(math.log(int(id), 10)) + 1 for im in images: if (im[digits] == '_' and im[0:digits] == str(id)): os.remove(os.path.join(imgFolder, im)) image.save(filePath) update("team", "logo='{}'".format(filename), "id={}".format(id)) elif (image): flash("Please upload a file in JPG format", 'danger') update( "team", "name='{}', num_members={}, found_year='{}', email='{}', adress='{}', competition_id={}" .format(name, members, year, email, address, competition), where="id={}".format(id)) return redirect(url_for('admin_edit.admin_edit_team_page', id=id)) else: result = select( columns= "team.name,team.num_members,team.found_year,team.email,team.adress,team.logo,competition.id", table= "team left outer join competition on team.COMPETITION_ID=competition.id", where="team.id={}".format(id)) print("EDIT TEAM RESULT", result) form.name.data = result[0] form.memberCtr.data = result[1] form.year.data = result[2] form.email.data = result[3] form.address.data = result[4] img_name = result[5] form.competition.data = result[6] return render_template('admin_edit_team_page.html', form=form, result=result, uploadImg=imgForm, imgName=img_name) return render_template('admin_edit_team_page.html', form=form, result=result, uploadImg=imgForm, imgName=img_name)
def admin_edit_member_page(person_id): # TODO:: Alter table to include social accounts links in person database. auth = session.get('auth_type') if (auth != 'admin'): flash("No admin", 'danger') return redirect(url_for("home.home_page")) form = EditMemberForm() subteams = select( "subteam.id,subteam.name", "subteam join team on subteam.team_id=team.id join person on person.team_id=team.id", "person.id={}".format(person_id)) form.subteam.choices = subteams majors = select("major.id,major.name", "major") form.major.choices = majors auth_types = select("id,name", "auth_type") form.auth_type.choices = auth_types cvForm = UploadCVForm() cvPath = None cvFolder = os.path.join(os.getcwd(), 'static/cv') imgForm = UploadImageForm() imgPath = None imgFolder = os.path.join(os.getcwd(), 'static/images/person') member_id = select("member.id", "member join person on person.id=member.person_id", where="person.id={}".format(person_id))[0] if form.validate_on_submit(): team = form.team.data subteam = form.subteam.data role = form.role.data auth_type = form.auth_type.data email = form.email.data name = form.name.data address = form.address.data active = form.active.data age = form.age.data phone = form.phone.data clas = form.clas.data major = form.major.data cv = cvForm.cv.data image = imgForm.image.data if (cv and '.pdf' in cv.filename): date = time.gmtime() filename = secure_filename("{}_{}.pdf".format( person_id, date[0:6])) cvPath = os.path.join(cvFolder, filename) cvs = os.listdir(cvFolder) digits = int(math.log(int(person_id), 10)) + 1 for c in cvs: if (c[digits] == '_' and c[0:digits] == str(person_id)): os.remove(os.path.join(cvFolder, c)) cv.save(cvPath) update("person", "cv='{}'".format(filename), "id={}".format(person_id)) session['person_id'] = person_id elif (cv): flash("Upload a PDF file.", 'danger') if (image and '.jpg' in image.filename or '.jpeg' in image.filename or '.png' in image.filename): date = time.gmtime() extension = image.filename.split('.')[1] filename = secure_filename("{}_{}.{}".format( person_id, date[0:6], extension)) imgPath = os.path.join(imgFolder, filename) images = os.listdir(imgFolder) digits = int(math.log(int(person_id), 10)) + 1 for im in images: if (im[digits] == '_' and im[0:digits] == str(person_id)): os.remove(os.path.join(imgFolder, im)) image.save(imgPath) update("member", "picture='{}'".format(filename), "id={}".format(member_id)) elif (image): flash("Please upload a file in JPG format", 'danger') teamID = select(columns="id", table="team", where="name='{}'".format(team))[0] majorID = select(columns="id", table="major", where="id='{}'".format(major))[0] update("member", "role='{}', active={}, address='{}'".format( role, active, address), where="id={}".format(member_id)) update("person", "name='{}', age='{}', phone='{}',email='{}', \ class={}, auth_type={}, team_id={}, subteam_id={}, major_id={}".format( name, age, phone, email, clas, auth_type, teamID, subteam, majorID), where="id={}".format(person_id)) return redirect( url_for('admin_edit.admin_edit_member_page', person_id=person_id, cvPath=person_id)) else: result = select( "person.name,person.email,team.name,subteam.id,member.role,member.active, \ member.entrydate,auth_type.id,member.address,person.phone,major.id, \ person.class,person.age,person.cv,member.picture", "person join member on member.person_id=person.id \ join team on person.team_id=team.id \ join subteam on person.subteam_id=subteam.id \ join auth_type on person.auth_type=auth_type.id \ join major on person.major_id=major.id ", "person.id={}".format(person_id)) form.name.data = result[0] form.email.data = result[1] form.team.data = result[2] form.subteam.data = result[3] form.role.data = result[4] form.active.data = result[5] form.entry.data = result[6] form.auth_type.data = result[7] form.address.data = result[8] form.phone.data = result[9] form.major.data = result[10] form.clas.data = result[11] form.age.data = result[12] cvPath = result[13] img_name = result[14] return render_template('admin_edit_member_page.html', form=form, uploadImg=imgForm, uploadCV=cvForm, cvPath=cvPath, imgName=img_name)
def member_edit_member_page(person_id): auth = session.get('auth_type') if (auth != 'Team leader'): flash("Not authorized", 'danger') return redirect(url_for("home.home_page")) form = EditMemberForm() team_id = session.get("team_id") print("Teamid", team_id) subteams = select("subteam.id,subteam.name", "subteam join team on subteam.team_id=team.id", "team.id={}".format(team_id)) current_auth = select("auth_type", "person", "id={}".format(person_id)) majors = select("id,name", "major") auths = select("id,name", "auth_type") form.subteam.choices = subteams form.major.choices = majors form.auth_type.choices = auths form.auth_type.data = current_auth if (request.method == 'POST' and form.submit_member.data or form.validate()): subteam = form.subteam.data role = form.role.data auth_type = form.auth_type.data email = form.email.data name = form.name.data address = form.address.data active = form.active.data age = form.age.data phone = form.phone.data clas = form.clas.data major = form.major.data memberID = select( columns="member.id", table="member join person on member.person_id=person.id", where="person.id={}".format(person_id)) memberID, auth_type = memberID[0], auth_type[0] print("Updating...") update("member", "role='{}', active={}, address='{}'".format( role, active, address), where="id={}".format(memberID)) update("person", "name='{}', age='{}', phone='{}', email='{}', \ class={}, auth_type={}, subteam_id={}, major_id={}".format( name, age, phone, email, clas, auth_type, subteam, major), where="id={}".format(person_id)) return redirect( url_for('member_edit.member_edit_member_page', person_id=person_id)) else: if (session.get('auth_type') != 'Team leader'): flash('No admin privileges...', 'danger') return redirect(url_for('home.home_page')) else: columns = """person.name,person.email,team.name,subteam.id,\ member.role,member.active,member.entrydate,auth_type.id, \ member.address,person.phone,major.id,person.class,person.age,member.id,member.picture""" table = """member join person on member.person_id=person.id \ join major on person.major_id=major.id \ join team on person.team_id=team.id \ join subteam on person.subteam_id=subteam.id \ join auth_type on person.auth_type=auth_type.id""" where = "person.id={}".format(person_id) result = select(columns, table, where) form.name.data = result[0] form.email.data = result[1] form.team.data = result[2] form.subteam.data = result[3] form.role.data = result[4] form.active.data = result[5] form.entry.data = result[6] form.auth_type.data = result[7] form.address.data = result[8] form.phone.data = result[9] form.major.data = result[11] form.clas.data = result[12] form.age.data = result[13] img_name = result[14] return render_template('member_edit_member_page.html', form=form, result=result, imgName=img_name) return render_template('member_edit_member_page.html', form=form)
def member_profile_page(): auth = session.get('auth_type') if (auth != 'Member' and auth != 'Team leader' and auth != 'Subteam leader'): flash("Not authorized...", "danger") return redirect(url_for("home.home_page")) form = EditProfileForm() majors = select("major.id,major.name", "major") auth_types = select("id,name", "auth_type") form.major.choices = majors form.auth_type.choices = auth_types imgForm = UploadImageForm() cvForm = UploadCVForm() team_id = session.get('team_id') member_id = session.get('member_id') person_id = select("person.id", "person join member on member.person_id=person.id", "member.id={}".format(member_id))[0] cvPath = None cvFolder = os.path.join(os.getcwd(), 'static/cv') imgPath = None imgFolder = os.path.join(os.getcwd(), 'static/images/person') if (request.method == 'POST' and form.submit_edit_profile.data or form.validate()): name = form.name.data email = form.email.data address = form.address.data phone = form.phone.data major = form.major.data clas = form.clas.data age = form.age.data cv = cvForm.cv.data image = imgForm.image.data if (cv and '.pdf' in cv.filename): date = time.gmtime() filename = secure_filename("{}_{}.pdf".format( person_id, date[0:6])) cvPath = os.path.join(cvFolder, filename) cvs = os.listdir(cvFolder) digits = int(math.log(int(person_id), 10)) + 1 for c in cvs: if (c[digits] == '_' and c[0:digits] == str(person_id)): os.remove(os.path.join(cvFolder, c)) cv.save(cvPath) update("person", "cv='{}'".format(filename), "id={}".format(person_id)) session['person_id'] = person_id # update persons cv file name elif (cv): flash("Upload a PDF file.", 'danger') if (image and '.jpg' in image.filename or '.jpeg' in image.filename or '.png' in image.filename): date = time.gmtime() extension = image.filename.split('.')[1] filename = secure_filename("{}_{}.{}".format( person_id, date[0:6], extension)) imgPath = os.path.join(imgFolder, filename) images = os.listdir(imgFolder) digits = int(math.log(int(person_id), 10)) + 1 for im in images: if (im[digits] == '_' and im[0:digits] == str(person_id)): os.remove(os.path.join(imgFolder, im)) image.save(imgPath) update("member", "picture='{}'".format(filename), "id={}".format(member_id)) elif (image): flash("Please upload a file in JPG format", 'danger') majorID = select("major.id", "major", "id='{}'".format(major))[0] print("MAJORRRR", majorID) update( "person", "name='{}', email='{}',phone='{}', class={}, age={}, major_id={}". format(name, email, phone, clas, age, majorID), "id={}".format(person_id)) update("member", "address='{}'".format(address), "id={}".format(member_id)) return redirect(url_for("member_edit.member_profile_page")) else: result = select( "person.name,person.email,team.name,subteam.name,member.role,member.active, \ member.entrydate,auth_type.id,member.address,person.phone,major.id, \ person.class,person.age,person.cv,member.picture", "person join member on member.person_id=person.id \ join team on person.team_id=team.id \ join subteam on person.subteam_id=subteam.id \ join auth_type on person.auth_type=auth_type.id \ join major on person.major_id=major.id ", "member.id={}".format(member_id)) form.name.data = result[0] form.email.data = result[1] form.team.data = result[2] form.subteam.data = result[3] form.role.data = result[4] form.active.data = result[5] form.entry.data = result[6] form.auth_type.data = result[7] form.address.data = result[8] form.phone.data = result[9] form.major.data = result[10] form.clas.data = result[11] form.age.data = result[12] cvPath = result[13] imgPath = result[14] return render_template("member_profile_page.html", form=form, imgForm=imgForm, cvForm=cvForm, cvPath=cvPath, imgPath=imgPath)
def member_edit_sponsor_page(sponsor_id): auth = session.get('auth_type') sponsortypechoices = select("sponsortype.id,sponsortype.name", "sponsortype") form = EditSponsorForm() form.typ.choices = sponsortypechoices imageForm = UploadImageForm() imageFolderPath = os.path.join(os.getcwd(), 'static/images/sponsors') if (auth != "Team leader"): flash("Not an authorized person") return redirect(url_for("home.home_page")) if (request.method == 'POST' and form.submit_edit_sponsor.data or form.validate()): name = form.name.data description = form.description.data address = form.address.data field = form.field.data country = form.country.data type_id = form.typ.data image = imageForm.image.data filename = "-1.png" if (image and '.jpg' in image.filename or '.jpeg' in image.filename): date = time.gmtime() filename = secure_filename("{}_{}.jpg".format( sponsor_id, date[0:6])) filePath = os.path.join(imageFolderPath, filename) images = os.listdir(imageFolderPath) digits = int(math.log(int(sponsor_id), 10)) + 1 for im in images: if (im[digits] == '_' and im[0:digits] == str(sponsor_id)): print("deleting", im) os.remove(os.path.join(imageFolderPath, im)) image.save(filePath) elif (image): flash("Please upload a file in JPG format", 'danger') print(name, description, address, field, country, type_id) update( "sponsor", "name='{}',description='{}',field='{}',country='{}',logo='{}',address='{}',type_id={}" .format(name, description, field, country, filename, address, type_id), where="id={}".format(sponsor_id)) return redirect(url_for("visitor.visitor_sponsors_page")) else: result = select( "sponsor.name,description,field,country,logo,address,type_id", "sponsor join sponsortype on sponsor.type_id=sponsortype.id", "sponsor.id={}".format(sponsor_id)) print(result) form.name.data = result[0] form.description.data = result[1] form.field.data = result[2] form.country.data = result[3] form.address.data = result[5] form.typ.data = sponsortypechoices[result[6]] return render_template("member_edit_sponsor_page.html", form=form, uploadImg=imageForm, result=result, imgName=img_name)
def member_edit_tutorial_page(id): form = EditTutorialForm() imageForm = UploadImageForm() imageFolderPath = os.path.join(os.getcwd(), 'static/images/tutorial') if (request.method == 'POST' and form.submit_edit_tutorial.data or form.validate()): name = form.name.data area = form.area.data description = form.description.data link = form.link.data isvideo = form.isvideo.data member_id = session.get('member_id') image = imageForm.image.data filename = select("picture", "tutorial", "id={}".format(id))[0] if (image): extension = image.filename.split('.')[1] current_date = time.gmtime() filename = secure_filename("{}_{}.{}".format( id, current_date[0:6], extension)) filePath = os.path.join(imageFolderPath, filename) images = os.listdir(imageFolderPath) digits = int(math.log(int(id), 10)) + 1 for im in images: if (im[digits] == '_' and im[0:digits] == str(id)): os.remove(os.path.join(imageFolderPath, im)) image.save(filePath) elif (image): flash('Please upload a file in JPG format', "danger") update( "tutorial", "name='{}', area='{}', description='{}', picture='{}',link='{}', isvideo={}" .format(name, area, description, filename, link, isvideo), where="id={}".format(id)) return redirect(url_for('visitor.visitor_tutorials_page')) else: if (session.get('auth_type') == 'Member' or session.get('auth_type') == 'Team leader' or session.get('auth_type') == 'Subteam leader'): result = select( columns= "tutorial.name,tutorial.area,tutorial.description,tutorial.link,tutorial.isvideo,tutorial.picture,tutorial.member_id", table="tutorial", where="tutorial.id={}".format(id)) print("QUERY-", result) form.name.data = result[0] form.area.data = result[1] form.description.data = result[2] form.link.data = result[3] form.isvideo.data = result[4] img_name = result[5] else: flash('Not an authorized person', 'danger') return redirect(url_for('visitor.visitor_tutorials_page')) return render_template('member_edit_tutorial_page.html', form=form, result=result, uploadImg=imageForm) return render_template('member_edit_tutorial_page.html', form=form, result=result, uploadImg=imageForm, imgName=img_name)
def member_edit_equipment_page(equipment_id): auth = session.get('auth_type') if (auth != "Team leader" and auth != "Subteam leader"): flash("Not an authorized person") return redirect(url_for("home.home_page")) team_id = session.get("team_id") subteams = select("subteam.id,subteam.name", "subteam join team on subteam.team_id=team.id", "team.id={}".format(team_id)) form = EditEquipmentForm() form.subteam.choices = subteams imageForm = UploadImageForm() imageFolderPath = os.path.join(os.getcwd(), 'static/images/equipments') if (request.method == 'POST' and form.submit_edit_equipment.data or form.validate()): name = form.name.data link = form.link.data purchasedate = form.purchasedate.data available = form.available.data subteam_id = form.subteam.data image = imageForm.image.data filename = select("picture", "equipment", "id={}".format(equipment_id))[0] if (image and '.jpg' in image.filename or '.jpeg' in image.filename or '.png' in image.filename): date = time.gmtime() extension = image.filename.split('.')[1] filename = secure_filename("{}_{}.{}".format( equipment_id, date[0:6], extension)) filePath = os.path.join(imageFolderPath, filename) images = os.listdir(imageFolderPath) digits = int(math.log(int(equipment_id), 10)) + 1 for im in images: if (im[digits] == '_' and im[0:digits] == str(equipment_id)): os.remove(os.path.join(imageFolderPath, im)) image.save(filePath) elif (image): flash("Please upload a file in JPG format", 'danger') update( "equipment", "name='{}',link='{}',purchasedate='{}',available='{}', picture='{}',team_id='{}',subteam_id={}" .format(name, link, purchasedate, available, filename, team_id, subteam_id), where="id={}".format(equipment_id)) return redirect(url_for("team.team_equipments_page")) else: img_name = None for img in os.listdir(imageFolderPath): if (equipment_id in img[0:len(equipment_id)] and (img[len(equipment_id)] == '_' or img[len(equipment_id)] == '.')): img_name = img result = select( "equipment.name,link,purchasedate,available,subteam.id", "equipment join subteam on equipment.subteam_id=subteam.id", "equipment.id={}".format(equipment_id)) print(result) form.name.data = result[0] form.link.data = result[1] form.purchasedate.data = result[2] form.available.data = result[3] form.subteam.data = result[4] return render_template("member_edit_equipment_page.html", form=form, uploadImg=imageForm, result=result, imgName=img_name)