def admin(): if current_user.admin == True: form = Admin() try: if form.validate_on_submit(): query = request.form.get('query') db.raw_query(query) result = None try: result = db.fetch_all() except Exception as e: print(e) if result == None: flash(f'Successful query. Your query was: ' + query, 'success') db.commit() return render_template('admin.html', form=form, result=[]) else: flash(f'Successful query. Your query was: ' + query, 'success') db.commit() return render_template('admin.html', form=form, result=result) except Exception as e: flash( 'The following error ocurred when executing your query: ' + str(e), 'danger') db.close() db.new_connection() return render_template('admin.html', form=form, result=[]) return render_template('admin.html', form=form, result=[]) else: abort(404)
def getUserInfo(): user={} # 打开数据库连接 db = pymysql.connect(host='13.231.165.68', port=33070, user='******', passwd='880309jQl', db='tfs', charset='utf8') # 使用cursor()方法获取操作游标 cursor = db.cursor() sql = "SELECT * FROM user" try: # 执行SQL语句 cursor.execute(sql) # 获取所有记录列表 results = cursor.fetchall() for row in results: user[row[0]]=row[5] # print(len(results)) except: print("Error: unable to fecth user data") # 关闭数据库连接 db.close() return user;
def register(): if current_user.is_authenticated: return redirect(url_for('index')) account_details = {} form = RegistrationForm() try: user = User() if form.validate_on_submit(): account_details['first_name'] = request.form.get('first_name') account_details['middle_name'] = request.form.get('middle_name', default='NULL') account_details['last_name'] = request.form.get('last_name') account_details['username'] = request.form.get('username') account_details['password'] = request.form.get('password') account_details['street_number'] = request.form.get( 'street_number') account_details['street_name'] = request.form.get('street_name') account_details['apt_number'] = request.form.get('apt_number', default='NaN') account_details['postal_code'] = request.form.get('postal_code') account_details['date_of_birth'] = request.form.get( 'date_of_birth') account_details['country'] = request.form.get('country') account_details['province'] = request.form.get('province') account_details['email'] = request.form.get('email') account_details['phone_number'] = request.form.get('phone_number') #deal with weird cases for optional (can be null) arguments db.valid_country(account_details['country']) country_count = db.fetch_one() if not country_count[0]: raise Exception( 'Sorry, we are not operating in that country yet!') if account_details['middle_name'] == "": account_details['middle_name'] = "NULL" if account_details['apt_number'] == "": account_details['apt_number'] = "NaN" if account_details['country'] == "-1" or len( account_details['province']) == 0: raise Exception('Please enter a country or province') db.create_user( account_details['first_name'], account_details['middle_name'], account_details['last_name'], account_details['username'], account_details['password'], account_details['street_number'], account_details['street_name'], account_details['apt_number'], account_details['postal_code'], account_details['date_of_birth'], account_details['country'], account_details['province'], account_details['email'], account_details['phone_number']) flash(f'Account created for {form.username.data}!', 'success') db.commit() return redirect(url_for('index')) except Exception as e: db.close() db.new_connection() print(e) flash('Error: ' + str(e), 'danger') return render_template('register.html', title='Register', form=form) return render_template('register.html', title='Register', form=form)
def shutdown(): def shutdown_server(): func = request.environ.get('werkzeug.server.shutdown') if func is None: raise RuntimeError('Not running with the Werkzeug Server') func() shutdown_server() db.close() return "Server shutting down..."
def assign_employee_to_property(): try: if (current_user.title == "Branch Manager"): assign_map = {} form = AssignEmployeeToProperty() if form.validate_on_submit(): assign_map['employeeusername'] = request.form.get( 'employeeusername') assign_map['propertyname'] = request.form.get('propertyname') #ensure employee and property are from this branch manager's branch (country) db.get_property_country(assign_map['propertyname']) property_country = db.fetch_one() db.get_employee_country(assign_map['employeeusername']) employee_country = db.fetch_one() if employee_country == None: raise Exception("This user is not an employee!") if property_country == None: raise Exception("This property is not part of your branch") property_country = property_country[0] employee_country = employee_country[0] if (current_user.country != property_country): raise Exception( "This property is not part of your branch!") if (current_user.country != employee_country): raise Exception( "This employee is not part of your branch!") db.assign_employee_to_property(assign_map['employeeusername'], assign_map['propertyname']) db.commit() flash( 'Success! ' + assign_map['employeeusername'] + ' has been assigned to the property ' + assign_map['propertyname'], 'success') return render_template('assign_employee_to_property.html', form=form) else: abort(404) except Exception as e: db.close() db.new_connection() print(e) flash('Error: ' + str(e), 'danger') return render_template('assign_employee_to_property.html', form=form) return render_template('assign_employee_to_property.html', form=form)
def csv_to_model(): with open(CWD + '/farm_data.csv', 'r') as file: cur = db.cursor() for line in file: sql = None parsed = Parser(line) if parsed == 'Farm': farm = Farms() farm.create(**parsed.get_dictionary()) sql = farm.sql_insert_statement() elif parsed == 'Farmers Market': farmers_market = FarmersMarkets() farmers_market.create(**parsed.get_dictionary()) sql = farmers_market.sql_insert_statement() if sql != None: cur.execute(sql) db.commit() cur.close() db.close()
def add_payment_method(): payment_method = {} form = PaymentMethod() try: if form.validate_on_submit(): payment_method['username'] = current_user.id payment_method['card_type'] = request.form.get('card_type').lower() payment_method['first_name'] = request.form.get('first_name') payment_method['last_name'] = request.form.get('last_name') payment_method['card_number'] = request.form.get('card_number') payment_method['card_expiration'] = request.form.get( 'card_expiration') payment_method['cvv'] = str(request.form.get('cvv')) payment_method['billing_country'] = request.form.get( 'billing_country') #there's a hidden 'province' field here cuz of country.js btw if payment_method['billing_country'] in ["-1", None]: raise Exception('Please enter a country or province') db.create_payment_method( payment_method['username'], payment_method['card_type'], payment_method['first_name'], payment_method['last_name'], payment_method['card_number'], payment_method['card_expiration'], payment_method['cvv'], payment_method['billing_country']) flash(f'Payment method created!', 'success') db.commit() return redirect(url_for('your_payment_method')) except Exception as e: db.close() db.new_connection() print(e) flash('Please enter your billing country', 'danger') return render_template('add_payment_method.html', title='Add Payment Method', form=form) return render_template('add_payment_method.html', title='Add Payment Method', form=form)
def teardown_request(response): db.close() return response
def _db_close(exc): if not db.is_closed(): db.close()
def shutdown_session(exception=None): db.close()
@app.route('/register',methods=['GET','POST']) def register(): if request.method =='POST': if len(request.form['username']) > 8: error = "username is too long!" return render_template('register.html',error=error) if len(request.form['username']) < 3: error = "username was too short!" return render_template('register.html',error=error) if ue(request.form['username']) == True: error = "username was uesd!" return render_template('register.html',error=error) anu(request.form['username'],request.form['passwd'],UPLOAD_FOLDER+request.form['username']+'/') flash('You were just register!') os.mkdir(UPLOAD_FOLDER+request.form['username']) return redirect(url_for('login')) return render_template('register.html') @app.errorhandler(413) def error413(e): return render_template('413.html'), 413 if __name__ == '__main__': app.run(host='0.0.0.0') db.close()
def individual_property(propertyname): property_columns = [ 'propertyname', 'street_number', 'street_name', 'apt_number', 'province', 'postal_code', 'rent_rate', 'type', 'max_guests', 'number_beds', 'number_baths', 'accesible', 'pets_allowed', 'country', 'hostusername', 'picture' ] db.get_property(propertyname) property_rows = db.fetch_one() if property_rows == None: abort(404) return property_map = {} for i, column in enumerate(property_rows, 0): property_map[property_columns[i]] = column host_username = property_map['hostusername'] db.get_picture(host_username) host_picture = db.fetch_one()[0] form = AvailableDates() if request.method == 'POST': try: available_dates = {} available_dates['start_date'] = request.form.get('start_date') available_dates['end_date'] = request.form.get('end_date') if available_dates['start_date'] in [None, ""]: raise Exception("Please choose a Start Date") if available_dates['end_date'] in [None, ""]: raise Exception("Please choose an End Date") start_month, start_day, start_year = [ int(x) for x in str(available_dates['start_date']).split('/') ] end_month, end_day, end_year = [ int(x) for x in str(available_dates['end_date']).split('/') ] start_date = datetime.date(start_year, start_month, start_day) end_date = datetime.date(end_year, end_month, end_day) if start_date > end_date: raise Exception("Start date cannot be greater than end date!") date_difference = end_date - start_date if date_difference.days > 13: raise Exception( "You can only stay at one property for a maximum of 14 days!" ) delta = datetime.timedelta(days=1) dates = [] while start_date <= end_date: dates.append(start_date) start_date += delta taken_dates = db.check_dates(property_map['propertyname'], dates) if len(taken_dates) == 0: flash('The property is available during those dates!', 'success') else: error_message = "" for date in taken_dates: error_message += date.strftime('%Y-%m-%d') + ", " flash( 'Sorry, the property is not available on the following dates: ' + error_message, 'danger') except Exception as e: db.close() db.new_connection() flash('Error: ' + str(e), 'danger') return render_template('property.html', property_map=property_map, host_picture=host_picture, form=form)
def add_property(): property_details = {} form = CreateProperty() try: if form.validate_on_submit(): property_details['hostusername'] = current_user.id property_details['property_name'] = request.form.get( 'property_name') property_details['street_number'] = request.form.get( 'street_number', default='NULL') property_details['street_name'] = request.form.get('street_name') property_details['apt_number'] = request.form.get('apt_number') property_details['postal_code'] = request.form.get('postal_code') property_details['rent_rate'] = request.form.get('rent_rate') property_details['country'] = request.form.get('country') property_details['province'] = request.form.get('province') property_details['property_type'] = request.form.get( 'property_type').lower() property_details['max_guests'] = request.form.get('max_guests') property_details['number_beds'] = request.form.get('number_beds') property_details['number_baths'] = request.form.get('number_baths') property_details['accessible'] = request.form.get('accessible') property_details['pets_allowed'] = request.form.get('pets_allowed') property_details['picture'] = request.form.get('picture') #deal with weird cases for optional (can be null) arguments if property_details['apt_number'] == "": property_details['apt_number'] = "NaN" if property_details['postal_code'] == "": property_details['postal_code'] = "NULL" if property_details['accessible'] == "n": property_details['accessible'] = "False" else: property_details['accessible'] = "True" if property_details['pets_allowed'] == "n": property_details['pets_allowed'] = "False" else: property_details['pets_allowed'] = "True" if property_details['country'] == "-1" or len( property_details['province']) == 0: raise Exception('Please enter a country or province') picture_file = save_property_picture(form.picture.data) db.create_property( property_details['property_name'], property_details['street_number'], property_details['street_name'], property_details['apt_number'], property_details['postal_code'], property_details['rent_rate'], property_details['country'], property_details['province'], property_details['property_type'], property_details['max_guests'], property_details['number_beds'], property_details['number_baths'], property_details['accessible'], property_details['pets_allowed'], property_details['hostusername'], picture_file) flash(f'Property created for {form.property_name.data}!', 'success') db.commit() return redirect(url_for('your_properties')) except Exception as e: db.close() db.new_connection() print(e) flash('Please enter your country/province', 'danger') return render_template('add_property.html', title='Add Property', form=form) return render_template('add_property.html', title='Add Property', form=form)
def after_request(response): database.close() return response
def after_request(response): db.close() return response
import logging import sys from setup import logger from PyQt5 import QtWidgets from app.main_window import MainWindow from db import db if __name__ == "__main__": logger.setLevel(logging.DEBUG) logger.info('App start') app = QtWidgets.QApplication(sys.argv) main_window = None try: db.connect() db.create_tables([]) # fixme main_window = MainWindow(app) main_window.show() sys.exit(app.exec()) except Exception as e: logger.exception(e) finally: db.close() # todo check if main_window: main_window.stop() logger.info('App close')
def init_data(): db.init_data() db.close()
import MySQLdb from db import db, cursor query = "UPDATE settings SET value='Idle' WHERE setting='utility_status'" cursor.execute(query) db.commit() query = ("INSERT INTO utility_log (level,status) VALUES " "('Error','facade-worker.py manually reset')") cursor.execute(query) db.commit() # If for whatever reason the last run failed and we couldn't drop the stale # cache tables, the rename will fail. So we do this just in case. query = ("DROP TABLE IF EXISTS pmc_old, " "pac_old, " "rmc_old, " "rac_old, " "uc_old, " "pmc, " "pac, " "rmc, " "rac, " "uc") cursor.execute(query) db.commit() cursor.close() db.close()
def search(): property_columns = [ 'propertyname', 'street_number', 'street_name', 'apt_number', 'province', 'postal_code', 'rent_rate', 'type', 'max_guests', 'number_beds', 'number_baths', 'accesible', 'pets_allowed', 'country', 'hostusername', 'picture' ] form = SearchProperty() property_details = {} if form.validate_on_submit(): try: property_details['hostusername'] = request.form.get('hostusername', default='null') property_details['propertyname'] = request.form.get('propertyname', default='null') property_details['rent_rate'] = request.form.get('rent_rate', default='-1') property_details['country'] = request.form.get('country', default='null') property_details['province'] = request.form.get('province', default='null') property_details['property_type'] = request.form.get( 'property_type', default='null').lower() property_details['max_guests'] = request.form.get('max_guests', default='-1') property_details['number_beds'] = request.form.get('number_beds', default='-1') property_details['number_baths'] = request.form.get('number_baths', default='-1') property_details['accessible'] = request.form.get('accessible', default='null') property_details['pets_allowed'] = request.form.get('pets_allowed', default='null') #deal with weird cases for optional (can be null) arguments for key in property_details: if property_details[key] in ['null', '-1', 'None', ""]: property_details[key] = key else: property_details[key] = "'" + str( property_details[key]) + "'" properties = [] db.get_search_properties(property_details['hostusername'], property_details['propertyname'], property_details['rent_rate'], property_details['country'], property_details['province'], property_details['property_type'], property_details['max_guests'], property_details['number_beds'], property_details['number_baths'], property_details['accessible'], property_details['pets_allowed']) property_rows = db.fetch_all() for row in property_rows: property_map = {} for k in range(len(property_columns)): property_map[property_columns[k]] = row[k] properties.append(property_map) for prop in properties: db.get_picture(prop['hostusername']) picture = db.fetch_one()[0] prop['profile_picture'] = picture flash('Successful search. Here are your results:', 'success') return render_template("search_results.html", properties=properties) except Exception as e: db.close() db.new_connection() print(e) flash('Opps, something went wrong. Try again.', 'danger') return render_template("search.html", form=form)