def db_add_cin_hall(req: "flask_request") -> None: with UseDatabase(app.config["dbconfig"]) as cursor: _SQL = """insert into cin_halls (name, location) values (%s, %s)""" cursor.execute(_SQL, (req.form["name"], req.form["location"])) _SQL = """select max(id) as max_id from cin_halls""" cin_hall_id = db_request(_SQL)[0][0] #This seems not safe new_table_name = "cin_hall_" + str(cin_hall_id) #For now I'm assuming that rows contain equal numbers of seats seats = [] for i in range(int(req.form["row_num"])): for j in range(int(req.form["seats_in_row"])): seats.append(f"({i + 1}, {j + 1})") #There shold be a more safe and elegant way to do this with UseDatabase(app.config["dbconfig"]) as cursor: _SQL = f"""create table {new_table_name} ( id int primary key auto_increment, row_num tinyint, seat tinyint ); insert into {new_table_name} (row_num, seat) values """ + ", ".join(seats) results = cursor.execute(_SQL, multi=True) for cur in results: print("\n", cur.statement, "\n")
def log_in() -> 'html': if request.method == 'GET': return render_template('log_in.html') else: with UseDatabase(app.config['database']) as cursor: query = """SELECT login, password FROM users WHERE login = '******' and password = '******'""".format( request.form['login'], request.form['password']) cursor.execute(query) response = cursor.fetchall() if len(response) == 0: return render_template('fail_log_in.html') else: with UseDatabase(app.config['database']) as cursor: query = """SELECT first_name, last_name, login, password FROM users WHERE login = '******' and password = '******'""".format( request.form['login'], request.form['password']) cursor.execute(query) response = cursor.fetchall() app.config['current_user']['first_name'] = response[0][0] app.config['current_user']['last_name'] = response[0][1] app.config['current_user']['login'] = response[0][2] app.config['current_user']['password'] = response[0][3] return render_template( 'successful_log_in.html', login=app.config['current_user']['login'], first_name=app.config['current_user']['first_name'], last_name=app.config['current_user']['last_name'], password=app.config['current_user']['password'])
def login() -> 'html': msg = "" if request.method == 'POST' and 'email' in request.form and 'password' in request.form: email = request.form['email'] password = request.form['password'] ip = request.remote_addr client = request.user_agent.browser salt = "!.+^mk-3@" password += salt password = hashlib.md5(password.encode()) password = password.hexdigest() with UseDatabase(dbconfig) as cursor: cursor.execute( 'select * from account where email=%s and password=%s', (email, password)) account = cursor.fetchone() if account: session['logged_in'] = True session['id'] = account[0] session['username'] = account[1] parentID = account[0] with UseDatabase(dbconfig) as cursor: cursor.execute( "insert into browser_info values(NULL, %s, %s, %s)", (ip, client, parentID)) return redirect(url_for('home')) else: msg = "Incorrect username/password" return render_template('login.html', msg=msg)
def character(): error_add = None success_add = None error = None if request.method == 'POST': if request.form["action"] == "new_hero": id_hero = request.form['heroType'] heroname_form = request.form['hero_name'] id_user = str(session['userId']) print([id_hero, heroname_form, id_user]) try: with UseDatabase(app.config['dbconfig']) as cur: _SQL2 = """SELECT COUNT(1) FROM heroes WHERE name=(%s)""" cur.execute(_SQL2, (heroname_form, )) if cur.fetchone()[0]: raise ServerError('Nazwa bohatera jest już zajęta.') else: _SQL = """INSERT INTO heroes VALUES (%s, %s, %s, %s, %s)""" cur.execute( _SQL, ("", id_user, id_hero, heroname_form, None)) flash('Twój nowy bohater został dodany') return redirect(url_for('hero')) except ConnectionError as err: print('Nie ma połączenia z bazą ', str(err)) except SQLError as err: print('Błędne zapytanie ', str(err)) except ServerError as e: error_add = str(e) except Exception as err: print('Coś poszło źle ', str(err)) return 'Błąd' try: with UseDatabase(app.config['dbconfig']) as cursor: _SQL = """ select id, type, points from hero_types""" cursor.execute(_SQL) characterTypes = cursor.fetchall() except ConnectionError as err: print('add_hero nie ma połączenia z bazą ', str(err)) except SQLError as err: print('Błędne zapytanie w add_hero ', str(err)) except Exception as err: print('Coś poszło źle w add_hero', str(err)) return render_template("character.html", the_title='Stwórz bohatera', characterTypes=characterTypes, error_add=error_add, error=error, success_add=success_add)
def tickets(): with UseDatabase(app.config['dbconfig']) as cursor: _SQL="""select booking_id from pass_details""" cursor.execute(_SQL) data=cursor.fetchall() while(True): book_id = random.randint(1,999999) if book_id in data: pass else: break no_tickets=str(session.get('no_tickets')) print(no_tickets) no_tickets=int(no_tickets) l_age=[] l_name_age=[] for i in range(0,no_tickets): n='name'+str(i) a='age'+str(i) l_name_age.append((request.form[n],request.form[a])) # l_name_age.append(request.form[a]) l_age.append(int(request.form[a])) with UseDatabase(app.config['dbconfig']) as cursor: _SQL = """insert into pass_details(booking_id,name,age) values (%s,%s,%s)""" cursor.execute(_SQL,(book_id,request.form[n],request.form[a])) session['my_l_name_age']=l_name_age session['my_book_id']=book_id my_date = session.get('my_date') my_fare = int(session.get('my_fare')) discounted_fare = (my_fare) * 0.25 total_fare = 0.0 Accompanied_By_Adult=False for pas in l_age: if pas >= 18: Accompanied_By_Adult=True if no_tickets == 1 and l_age[0]<12: return render_template('invalidtime.html',the_title='Children below 12 years age cannnot travel alone') if no_tickets > 1: for passenger in l_age: if passenger < 10 and Accompanied_By_Adult: total_fare+=discounted_fare else: total_fare+=my_fare grand_total = no_tickets * my_fare dis=grand_total-total_fare with UseDatabase(app.config['dbconfig']) as cursor: _SQL = """insert into book_details(booking_id,book_fare,discount,book_date,no_of_pass) values (%s,%s,%s,%s,%s)""" cursor.execute(_SQL,(book_id,total_fare,dis,my_date,no_tickets)) my_source = session.get('my_source') my_dest = session.get('my_dest') session['my_total_fare']=total_fare session['my_dis_fare']=dis print(l_name_age) return render_template('conf_book.html',the_title='BOOKING CONFIRMATION',the_tickets=no_tickets,the_source=my_source.upper(),the_dest=my_dest.upper(),the_date=my_date,the_name_age=l_name_age,the_fare=total_fare,the_discount=dis)
def get_jxzyxxzx(): #获取中学,小学信息 idList = ['xx', 'zx'] for id in idList: print(id) url = base_url + id print(url) resp = requests.get(url, headers=headers).json() # print(resp) for i in resp: print(i['categoryId']) placeid = i['placeId'] url_info = 'https://map.beijing.gov.cn/place?placeId=' + placeid + '&categoryId=' + id print(url_info) cont = requests.get(url_info, headers=headers).text # print(cont) soup = BeautifulSoup(cont, 'lxml') try: infos = soup.find('table', {'class': 'nxq_ctab'}) #获取简介 ever_name = infos.find_all('td')[1].get_text() #曾用名称 cbrq = infos.find_all('td')[2].get_text() #本校址创办日期 sfjs = infos.find_all('td')[5].get_text() #是否有寄宿 xxlb = infos.find_all('td')[6].get_text() #学校种类 desc = infos.find_all('td')[7].get_text() #办学规模和主要特色 with UseDatabase(dbconfig) as cursor: _SQL = """insert into jxzy2 (学校名称,办公地址,曾用名称,校址创办日期,邮编,电话,类型,区域,是否有寄宿,学校类别,办学规模主要特色) values (%s, %s, %s, %s,%s,%s,%s,%s,%s,%s,%s)""" cursor.execute( _SQL, (i['placeName'], i['addr'], ever_name, cbrq, i['postcode'], i['tel'], i['categoryId'], switch_case(int(i['regionId'])), sfjs, xxlb, desc)) except Exception as e: print(e) infos = soup.find('table', {'class': 'nxq_ctab'}) #获取简介 cbrq = infos.find_all('td')[-6].get_text() #本校址创办日期 sfjs = infos.find_all('td')[-3].get_text() #是否有寄宿 xxlb = infos.find_all('td')[-2].get_text() #学校种类 desc = infos.find_all('td')[-1].get_text() #办学规模和主要特色 with UseDatabase(dbconfig) as cursor: _SQL = """insert into jxzy2 (学校名称,办公地址,曾用名称,校址创办日期,邮编,电话,类型,区域,是否有寄宿,学校类别,办学规模主要特色) values (%s, %s, %s, %s,%s,%s,%s,%s,%s,%s,%s)""" cursor.execute( _SQL, (i['placeName'], i['addr'], 'null', cbrq, i['postcode'], i['tel'], i['categoryId'], switch_case(int(i['regionId'])), sfjs, xxlb, desc))
def get_jxzy(): # idList = ['3','2','15','9','12','8','28','16','30','31','29','32','33','34','17','35'] idList = ['gbyey', 'zyjyxx', 'tsjyxx', 'gdyx'] for id in idList: print(id) url = base_url + id print(url) resp = requests.get(url, headers=headers).json() # print(resp) for i in resp: print(i['categoryId']) placeid = i['placeId'] url_info = 'https://map.beijing.gov.cn/place?placeId=' + placeid + '&categoryId=' + id # print(url_info) cont = requests.get(url_info, headers=headers).text # print(cont) soup = BeautifulSoup(cont, 'lxml') try: infos = soup.find('table', { 'class': 'nxq_ctab' }).find_all('td')[3].get_text() #获取简介 # print(infos) with UseDatabase(dbconfig) as cursor: _SQL = """insert into jxzx (placename, addr, postcode, tel,introduce,categoryid,reginid) values (%s, %s, %s, %s,%s,%s,%s)""" cursor.execute(_SQL, (i['placeName'], i['addr'], i['postcode'], i['tel'], infos, i['categoryId'], switch_case(int(i['regionId'])))) except Exception as e: print(e) with UseDatabase(dbconfig) as cursor: _SQL = """insert into JXZX (placename, addr, postcode, tel,introduce,categoryid,reginid) values (%s, %s, %s, %s,%s,%s,%s)""" cursor.execute( _SQL, ( i['placeName'], i['addr'], i['postcode'], i['tel'], 'null', #有的简介为空 i['categoryId'], switch_case(int(i['regionId']))))
def view_the_log() -> 'html': # contents = [] # with open('vsearch.log') as log: # for line in log: # contents.append([]) # for item in line.split('|'): # contents[-1].append(escape(item)) # titles = ('Form Data', 'Remote_addr', 'User_agent', 'Results') # return render_template('logi.html', # the_title='View Log', # the_row_titles=titles, # the_data=contents, ) try: with UseDatabase(app.config['dbconfig']) as cursor: _SQL = """select phrase, letters, ip, browser_string, results from log""" cursor.execute(_SQL) contents = cursor.fetchall() titles = ('Phrase', 'Letter', 'Remote_addr', 'User_agent', 'Results') return render_template( 'logi.html', the_title='Логи', the_row_titles=titles, the_data=contents, ) except CredentialsError as err: print('User-id/Password issues. Error: ', str(err)) except SQLError as err: print('Is your query correct? Error:', str(err)) except ConnectionError as err: print('Is your database switched on? Error:', str(err)) except Exception as err: print('***Возникла ошибка: ', str(err)) return 'Error'
def record(x, y): with UseDatabase(dbconfig) as cursor: _SQL = """insert into time_log(title, summary)values(%s,%s) """ cursor.execute(_SQL, (x, y)) print(x, y)
def view_log() -> 'html': titles = ('Phrase', 'Letters', 'Remote address', 'User Agent', 'Results') contents = [] with UseDatabase(app.config['db']) as cursor: _SQL = """ SELECT phrase, letters, ip, browser_string, results FROM logs """ cursor.execute(_SQL) rows = cursor.fetchall() for row in rows: log = { 'phrase': row[0], 'letters': row[1], 'remote_addr': row[2], 'user_agent': row[3], 'res': row[4] } contents.append(log) return render_template('viewlog.html', the_title='View Log', the_row_titles=titles, the_data=contents,)
def log_request(req: 'flask_request', res: str) -> None: sleep(15) with UseDatabase(app.config['dbconfig']) as cursor: _SQL = """insert into log (phrase, letters, ip, browser_string,results) values (%s,%s,%s,%s,%s)""" cursor.execute(_SQL, ( req.form['phrase'], req.form['letters'], req.remote_addr, req.user_agent.browser, res, )) phrase = request.form['phrase'] letters = request.form['letters'] title = 'here are your results:' results = str(letter_tallys(phrase, letters)) try: t = Thread(target=log_request, args=(request, results)) t.start() except Exception as err: print('*****Logging failed with this error:', str(err)) return render_template( 'results.html', the_phrase=phrase, the_letters=letters, the_title=title, the_results=results, )
def hero(): titles = ('Name', 'Typ', 'punkty') contents = [] try: with UseDatabase(app.config['dbconfig']) as cursor: _SQL = """select h.id, h.name, ht.type, ht.points from heroes h join hero_types ht on h.hero_type_id=ht.id join users u on h.user_id=u.id where u.username = %s """ username = str(session['username']) cursor.execute(_SQL, (username, )) contents = cursor.fetchall() except ConnectionError as err: print('view_hero nie ma połączenia z bazą ', str(err)) except SQLError as err: print('Błędne zapytanie w view_hero', str(err)) except Exception as err: print('Coś poszło źle w view_hero', str(err)) return 'Błąd' return render_template('hero.html', the_title='Lista Twoich Bohaterów', the_row_titles=titles, the_data=contents)
def view_the_log() -> 'html': try: """ view the logs of request and response """ with UseDatabase(app.config['dbconfig']) as cursor: _SQL = """ select phrase,letters,ip,browser_string,results to log """ cursor.execute(_SQL) contents = cursor.fetchall() # Hard coded titles titles = ('Phrase','Letters','Remote_addr','User_agent','Results') return render_template('viewlog.html', the_title='View Log', the_row_titles=titles, the_data=contents,) except ConnectionError as err: print('Is your database switched on? Error:', str(err)) except CredentialError as err: print('UserId/Pwd issue. Error:', str(err)) except SQLError as err: print('Is your query correct? Error:', str(err)) except Exception as err: print('Something went wrong:', str(err)) return 'Error'
def logged_in(): res = () try: with UseDatabase(app.config['dbconfig']) as cursor: _sql = '''select * from user_info where user_name = %(uname)s and password = %(pass)s;''' cursor.execute( _sql, {'uname': request.form['username'], 'pass': request.form['password']}) user = cursor.fetchall() if user: if user[0][2] == request.form['password']: session['username'] = user[0][1] return render_template('Ecolife.html') else: return render_template('sign-in.html', invalid=True) except ConnectionError as err: print('Is your Database switched on? Error: ', str(err)) except CredentialError as err: print('User-id/Password issues. Error: ', err) except SQLError as err: print('Is your Query correct? Error: ', err) except Exception as err: print('Something went wrong: ', err)
def get_tasks(): """Обрабатываем запрос GET и выдаем в JSON все данные из базы""" #Подключаемся к базе with UseDatabase(app.config['dbconf']) as all: all_db = all.gettasks(app.config['db_tab']['t1']) #Отвечаем на запрос return jsonify({'info': all_db})
def view_the_log() -> str: """ Display the content of the log file as a HTML Table""" try: with UseDatabase(app.config["dbconfig"]) as cursor: _SQL = """select phrase, letters, ip, browser_string, results from log""" cursor.execute(_SQL) contents = cursor.fetchall() titles = ("Form Data", "Remote_addr", "User_agent", "Results") return render_template( "viewlog.html", the_title="View Log", the_row_titles=titles, the_data=contents, ) except ConnectionError as err: print("Is your database switched on ? Error: ", str(err)) except CredentialsError as err: print("User-id/Password issues. Error: ", str(err)) except SQLError as err: print("Is Your Query Correct? Error: ", str(err)) except Exception as err: print("Something Went wrong: ", str(err), " ", type(err)) traceback.print_exc() return "Error"
def view_the_log() -> 'html': """Wyświetla zawartość pliku logu w tabeli HTML.""" try: with UseDatabase(app.config['dbconfig']) as cursor: _SQL = """select phrase, letters, ip, browser_string, results from logerror""" cursor.execute(_SQL) contents = cursor.fetchall() # raise Exception("Jakiś nieznany wyjątek.") titles = ('Fraza', 'Litery', 'Adres klienta', 'Agent użytkownika', 'Wyniki') return render_template( 'viewlog.html', the_title='View Log', the_row_titles=titles, the_data=contents, ) except ConnectionError as err: print('Czy Twoja baza danych jest włączona? Błąd:', str(err)) except CredentialsError as err: print( 'Problemy z identyfikatorem użytkownika lub hasłem dostępu. Błąd:', str(err)) except SQLError as err: print('Czy Twoje zapytanie jest poprawne? Błąd:', str(err)) except Exception as err: print('Coś poszło źle:', str(err)) return 'Błąd'
def view_the_log() -> 'html': try: with UseDatabase(app.config['dbconfig']) as cursor: _SQL = """Select phrase, letters, ip, browser_string, results FROM log""" cursor.execute(_SQL) contents = cursor.fetchall() titles = ('Phrase', 'Letters', 'Remote_addr', 'User_agent', 'Results') return render_template( 'viewlog.html', the_title='View Log', the_row_titles=titles, the_data=contents, ) except ConnectionError as err: print('Is your database switched on? Error: ', str(err)) except CredentialsError as err: print('User-id/Password issues. Error: ', str(err)) except SQLErrors as err: print('Is your query Correct? Error :', str(err)) except Exception as err: print('Something went wrong:', str(err)) return 'Error'
def view_the_log() ->'html': with UseDatabase(app.config['dbconfig']) as cursor: _SQL = """ select phrase, letters, ip, browser_string, results from log """ cursor.execute(_SQL) contents = cursor.fetchall() titles = ('Phrase', 'Letters', 'Remote_addr', 'User_agent', 'Results') return render_template('viewlog.html', the_title='View Log', the_row_titles= titles,the_data= contents)
def log_request(req: 'flask_request', res: str) -> None: """Log details of the web request and the results.""" # This function is decorated with flask's copy_current_request_context which makes the request and results # variables available even after the do_search() has completed its processing # Artificial delay to simulate DB connection delay sleep(2) try: with UseDatabase(app.config['dbconfig']) as cursor: # insert statement (with data placeholders) _SQL_INSERT = """insert into log (phrase, letters, ip, browser_string, results) values (%s, %s, %s, %s, %s) """ # data to be logged to the database insert_values = (req.form['phrase'], req.form['letters'], req.remote_addr, req.user_agent.browser, res) cursor.execute(_SQL_INSERT, insert_values) except ConnectionError as err: print('Is your database switched on? Error: ', str(err)) except CredentialsError as err: print('Database User-id/Password issues. Error: ', str(err)) except SQLError as err: print('Is your query correct? Error:', str(err)) except Exception as err: print('Something went wrong: ', str(err)) return 'Error'
def log_request(req: 'Flask_request',res: str) -> None: """ log request and response to my sql db """ sleep(15) with UseDatabase(app.config['dbconfig']) as cursor: _SQL = """ insert into log (phrase,letters,ip,browser_string,results) values (%s,%s,%s,%s,%s) """ sql_parameters = (req.form['phrase'],req.form['letters'],req.remote_addr,req.user_agent.browser,res,) cursor.execute(_SQL,sql_parameters) phrase = request.form['phrase'] letters = request.form['letters'] results = str(search4letters(phrase,letters)) title = 'Here are your results:' try: # log the results to the MySql Db in separate thread t = Thread(target=log_request,args=(request,results)) t.start() except Exception as err: print("**** Logging results failed with the error", str(err)) return render_template('results.html', the_pharse=phrase, the_letters=letters, the_title=title, the_results=results,)
def log_request(req: 'flask_request', res: str) -> None: """Log details of the web request and the results.""" # raise Exception('Something awful just happened.') sleep(15) # This makes log_request really slow... try: with UseDatabase(app.config['dbconfig']) as cursor: _SQL = """insert into log (phrase, letters, ip, browser_string, results) VALUES (%s, %s, %s, %s, %s)""" cursor.execute(_SQL, ( req.form['phrase'], req.form['letters'], req.remote_addr, req.user_agent.browser, res, )) except ConnectionError as error: print('Is your database switched on? Error:', str(error)) except CredentialError as error: print('User-ID/Password issues. Error:', str(error)) except SQLError as error: print('Is your query correct? Error:', str(error)) except Exception as error: print('Something went wrong:', str(error))
def view_the_log() -> 'html': """Display the contents of the log file as a HTML table.""" # contents = [] # with open('vsearch.log') as log: # for line in log: # contents.append([]) # for item in line.split('|'): # contents[-1].append(escape(item)) # titles = ('Form Data', 'Remote_addr', 'User_agent', 'Results') try: with UseDatabase(dbconfig) as cursor: _SQL = """select phrase, letters, ip, browser_string, results from log""" cursor.execute(_SQL) contents = cursor.fetchall() titles = ('Phrase', 'Letters', 'Remote_addr', 'User_agent', 'Results') return render_template( 'viewlog.html', the_title='View Log', the_row_titles=titles, the_data=contents, ) except ConnectionError as err: print('Is your database switched on? Error:', str(err)) except CredentialsError as err: print('User-id/Password issues. Error:', str(err)) except SQLError as err: print('Is your query correct? Error:', str(err)) except Exception as err: print('something went wrong: ', str(err))
def log_request(req: 'flask_request', res: str) -> None: #테스트를 위해 일부로 지연시간 만듬 #sleep(15) try: with UseDatabase(app.config['dbconfig']) as cursor: _SQL = """insert into log (phrase, letters, ip, browser_string, results) values (%s, %s, %s, %s, %s)""" cursor.execute(_SQL, ( req.form['phrase'], req.form['letters'], req.remote_addr, req.user_agent.browser, res, )) except ConnectionError as err: print('Is your database switched on? Error: ', str(err)) except CredentialsError as err: print('User-id/Password issues. Error: ', str(err)) except SQLError as err: print('Is your query correct? Error :', str(err)) except Exception as err: print('Something went wrong :', str(err)) return 'Error'
def library_app() -> 'html': if request.method == 'GET': return render_template('library_app.html', login=app.config['current_user']['login']) else: with UseDatabase(app.config['database']) as cursor: query = """SELECT Title, Author, Type, Year, Status FROM books WHERE Title='{}'""".format( request.form['book_title']) cursor.execute(query) response = cursor.fetchall() if len(response) == 0: return render_template('library_app.html', title='Unfortunately', author='There is no book', genre='With the title', year=request.form['book_title'].title(), status='In your library :(') else: return render_template('library_app.html', title=response[0][0], author=response[0][1], genre=response[0][2], year=response[0][3], status=response[0][4])
def view_the_log() -> 'html': """Access the database to fetch the logged data""" try: with UseDatabase(app.config['dbconfig']) as cursor: _SQL_SELECT = """select ts, phrase, letters, ip, browser_string, results from log""" cursor.execute(_SQL_SELECT) contents = cursor.fetchall() titles = ('Time Stamp', 'Phrase', 'Letters', 'Remote_addr', 'User_agent', 'Results') return render_template('viewlog.html', the_title='View Log', the_row_titles=titles, the_data=contents) except ConnectionError as err: print('Is your database switched on? Error: ', str(err)) except CredentialsError as err: print('Database User-id/Password issues. Error: ', str(err)) except SQLError as err: print('Is your query correct? Error:', str(err)) except Exception as err: print('Something went wrong: ', str(err)) return 'Error'
def view_the_log() -> 'html': """Display the contents of the log file as a HTML table.""" try: with UseDatabase(app.config['dbconfig']) as cursor: _SQL = """select phrase, letters, ip, browser_string, results from log""" cursor.execute(_SQL) contents = cursor.fetchall() titles = ('Phrase', 'Letters', 'Remote_addr', 'User_agent', 'Results') return render_template( 'viewlog.html', the_title='View Log', the_row_titles=titles, the_data=contents, ) except ConnectionError as e: print("Is your database switched on? Error:", str(e)) except CredentialsError as e: print("Perrmision denied, Error:", str(e)) except SQLError as e: print("Is your query correct? Error:", str(e)) except Exception as e: print("Something went wrong:", str(e)) return "Error"
def ranking(): titles = ('Name', 'Typ', 'punkty', "Użytkownik") contents = [] try: with UseDatabase(app.config['dbconfig']) as cursor: _SQL = _SQL = """select h.name, ht.type, ht.points, u.username from heroes h join hero_types ht on h.hero_type_id=ht.id join users u on h.user_id=u.id order by ht.points """ cursor.execute(_SQL, ) contents = cursor.fetchall() except ConnectionError as err: print('view_hero nie ma połączenia z bazą ', str(err)) except SQLError as err: print('Błędne zapytanie w view_hero', str(err)) except Exception as err: print('Coś poszło źle w view_hero', str(err)) return 'Błąd' return render_template('ranking.html', the_title='Ranking Bohaterów', the_row_titles=titles, the_data=contents)
def view_the_log() -> 'html': """Display the contents of the log table as a HTML table.""" try: with UseDatabase(app.config['dbconfig']) as cursor: _SQL = """select phrase, letters, ip, browser_string, results from log""" cursor.execute(_SQL) contents = cursor.fetchall() # raise Exception('Some unknown exception.') titles = ('Phrase', 'Letters', 'Remote_addr', 'User_agent', 'Results') return render_template( 'viewlog.html', the_title='View Log', the_row_titles=titles, the_data=contents, ) except ConnectionError as err: print('Is your database switched on? Error:', str(err)) except CredentialError as err: print('User-ID/Password issues. Error:', str(err)) except SQLError as err: print('Is your query correct? Error:', str(err)) except Exception as err: print('Something went wrong:', str(err)) return 'Error'
def viem_the_log() -> 'html': """Выводит содержимое файла журнала в виде HTML-таблицы""" try: with UseDatabase(app.config['dbconfig']) as cursor: _SQL = """select phrase, letters, ip, browser_string, results from log""" cursor.execute(_SQL) contens = cursor.fetchall( ) #fetchall возвращает как список кортежей # raise Exception("Some unkniwn exception") titles = ('Phrase', 'Letters', 'Remote_addr', 'User_agent', 'Results') return render_template( 'viewlog.html', the_tltle='Viem Log', the_row_titles=titles, the_data=contens, ) except ConnectionError as err: print('Is your database switched on? Error:', str(err)) except CredentialsError as err: print('User-id/Password issues. Error:', str(err)) except SQLError as err: print('Is your query correct? Error:', str(err)) except Exception as err: print('Something went wrong:', str(err)) return 'Error'