def pontlista_valtozas(): if 'logged_in' not in session or not session['logged_in']: log_event('pontlista_valtozas called with invalid login!') return render_template('login_required.html') if request.method == 'GET': orszag_id = request.args.get('orszag_id', type=int) limit = request.args.get('limit', default=5, type=int) log_event('pontlista_valtozas called by {} to {}'.format( session['username'], orszag_id)) print('Received content: {}'.format(orszag_id)) column_headers, lists = lemu_pontlista.get_pontlista_valtozas( orszag_id, limit=limit) # TODO: Error message #flash(result) else: log_error('Invalid call for pontlista_valtozas (not GET)') # TODO: Create pontlista_valtozas.html? But why if same solution will be done with pontlista.html return render_template('pontlista.html', title='Pontlista Változás', column_headers=column_headers, lists=lists)
def pontlista_feltoltes(): if 'logged_in' not in session or not session['logged_in']: log_event('pontlistafeltoltes called with invalid login!') return render_template('login_required.html') form = PontlistaFeltoltesForm() pontlista_data_list = None if request.method == 'POST': if form.validate(): content = request.form['content'] print('Received content: ' + content) result, pontlista_data_list = lemu_pontlista_feltoltes.process_and_upload_pontlista( content) log_event('pontlista_feltoltes called') if isinstance(result, list): for msg in result: flash(msg) else: flash('Result: ' + result) else: log_error('CSRF ERROR') return render_template('pontlistafeltoltes.html', title='Pontlista feltöltés', form=form, pontlista_data_list=pontlista_data_list)
def piac(): if 'logged_in' not in session or not session['logged_in']: log_event('piac called with invalid login!') return render_template('login_required.html') form = PiacFeltoltesForm() log_event('piac called: {}'.format(session['username'])) piac_column_headers, piac_data_list = lemu_piac.get_piac() if request.method == 'POST': if form.validate(): content = request.form['content'] print('Received content: ' + content) result = lemu_piac.process_and_upload_piac(content) log_event('piac called uploaded') if isinstance(result, list): for msg in result: flash(msg) else: flash('Result: ' + result) else: log_error('CSRF ERROR') return render_template('piac.html', title='Piac', form=form, piac_column_headers=piac_column_headers, piac_data_list=piac_data_list)
def kronika(): if 'logged_in' not in session or not session['logged_in']: log_event('kronika called with invalid login!') return render_template('login_required.html') form = KronikaFeltoltesForm() log_event('kronika called: {}'.format(session['username'])) kronika_column_headers, kronika_data_list = lemu_kronika.get_kronika() if request.method == 'POST': if form.validate(): content = request.form['content'] print('Received content: ' + content) result = lemu_kronika.process_and_upload_kronika(content) log_event('kronika uploaded') if isinstance(result, list): for msg in result: flash(msg) else: flash('Result: ' + result) else: log_error('CSRF ERROR') return render_template('kronika.html', title='Krónika', form=form, column_headers=kronika_column_headers, data_list=kronika_data_list)
def gombfeltoltes(): if 'logged_in' not in session or not session['logged_in']: return render_template('login_required.html') form = GombFeltoltesForm() print('Gombfeltoltes form: {}'.format(request.form)) if request.method == 'POST': if form.validate(): content = request.form['content'] print('Received content: ' + content) log_event('gombfeltoltes called by {}'.format(session['username'])) lemu_process_gomb_result = lemu_gombfeltoltes.process_and_upload_gomb( content) if isinstance(lemu_process_gomb_result, list): for msg in lemu_process_gomb_result: flash(msg) else: flash('Result: ' + lemu_process_gomb_result) else: log_error('CSRF ERROR') return render_template('gombfeltoltes.html', title='Gömb feltöltés', form=form)
def felmeres_kereses(orszag): result = '' mydb = lemu_database.database_connection() mycursor = mydb.cursor() print('Connected to MySQL') sql = 'SELECT * from lemu_felmeresek ' \ 'WHERE LOWER(orszag_nev) LIKE "%{finding}%" ' \ 'or orszag_id LIKE "%{finding}%" ' \ 'ORDER BY datum_created DESC'.format(finding=orszag.strip().lower()) print('Execute SQL command: ' + sql) try: mycursor.execute(sql) result = mycursor.fetchall() except Exception as ex: err_msg = '[ERROR]: Exception at felmeres kereses: ' + str(ex) eventlog.log_error(err_msg) result = err_msg print('SQL result: ' + str(result)) return result
def felmeresfeltoltes(): if 'logged_in' not in session or not session['logged_in']: log_event('felmeresfeltoltes called with invalid login!') return render_template('login_required.html') form = FelmeresFeltoltesForm() if request.method == 'POST': if form.validate(): content = request.form['content'] print('Received content: ' + content) log_event('felmeresfeltoltes called by {}'.format( session['username'])) lemu_process_result = lemu_felmeres.process_and_upload_felmeres( content) flash('Result: ' + lemu_process_result) else: log_error('CSRF ERROR') else: # First call, put default data form.content.data = lemu_felmeres.felmeres_default_inited() return render_template('felmeresfeltoltes.html', title='Felmérés feltöltés', form=form)
def test_log_log_error(self): """Test that log_error convenience function logs if enabled.""" with LogCapture() as l: event = log_error("label", "message", self.user, extra=self.extra) m = ('eventlog', 'ERROR', "0000000000000001 label (user: johndoe) - message {'key2': 'value2', 'key': 'value'}") l.check(m) event = log_error("label", "message", self.user, extra=self.extra, django_log=False) l.check(m)
def validate_felmeres(content, datum_result): new_content = {} is_ok = True date_now = datetime.now().strftime(FORMAT_DATE_EXPECTED) new_content['orszag_nev'] = content['orszag_nev'] if new_content['orszag_nev'].strip() == '': is_ok = False err_msg = 'Felmérés: Invalid orszag_nev parsed' eventlog.log_error(err_msg) new_content = err_msg return new_content, is_ok new_content['orszag_id'] = int(content['orszag_id']) if datum_result: try: # Mode 1: normal datum datum_result = datetime.strptime(datum_result, FORMAT_DATE_EXPECTED) new_content['datum_created'] = datum_result except ValueError: # Mode 2: msg used datum format date_converted = datetime.strptime(datum_result, FORMAT_DATE_MSG_ACCEPTED) new_content['datum_created'] = date_converted.strftime( FORMAT_DATE_EXPECTED) else: new_content['datum_created'] = date_now new_content['felmeres_tipus'] = content['felmeres_tipus'].replace( 'krónikája', 'krónika') # Only for krónika felmérés extension new_content['content'] = content['content'] # Handle the "Szövetségfelmérés" content_birodalom = content['content_birodalom'] if hasattr( content, 'content_birodalom') else None if content_birodalom: new_content['content'] = content_birodalom + content['content'] print('"szovetseg felmeres"') else: print('Not "szovetseg felmeres"') new_content['other_datum_uploaded'] = date_now new_content['other_who_uploaded'] = user.get_username() new_content['other_comment'] = '-' # TODO return new_content, is_ok
def upload_gomb(content): result = '' mydb = lemu_database.database_connection() mycursor = mydb.cursor() print('Connected to MySQL') sql = 'INSERT INTO lemu_orszagok (orszag_nev, orszag_id, sarkanykod, ' \ 'birodalom_nev, birodalom_id, korszak, ' \ 'sziget, gyalogsag, ostromgep, nep, vedo, elit_vedo, ' \ 'rang, tamado, elit_tamado, harci_kedv, hajok, terulet, ' \ 'lakos, magia, mana, ' \ 'munkanelkuli_munkas, munkanelkuli_bolcs, runa, hit, ' \ 'alvilag, armany, hangulat, dekadencia, denar, termeny, ' \ 'pontszam, hirnev, helyezes_1, helyezes_2, datum_created, ' \ 'other_datum_uploaded, other_who_uploaded, other_comment' \ ') VALUES (%s, %s, %s, ' \ '%s, %s, %s, ' \ '%s, %s, %s, %s, %s, %s, ' \ '%s, %s, %s, %s, %s, %s, ' \ '%s, %s, %s, ' \ '%s, %s, %s, %s, ' \ '%s, %s, %s, %s, %s, %s, ' \ '%s, %s, %s, %s, %s, ' \ '%s, %s, %s)' val = list(content.values()) print('Execute SQL command: ' + sql) try: mycursor.execute(sql, val) mydb.commit() result = str(mycursor.rowcount) + ' record inserted.' except mysql.connector.errors.IntegrityError: result = 'Duplicated, has not not re-uploaded' except Exception as ex: err_msg = '[ERROR] Exception at gombfeltoltes: ' + str(ex) eventlog.log_error(err_msg) result = err_msg mydb.close() print(result) return result
def test_convenience_log_error(self): """Test the log_error convenience function.""" event = log_error("label", "message", self.user, extra=self.extra) self.assertTrue(event.id) self.assertEqual(event.label, "label") self.assertEqual(event.message, "message") self.assertEqual(event.user, self.user) self.assertEqual(event.extra, self.extra) self.assertEqual(event.level, logging.ERROR)
def upload_pontlista(content): mydb = lemu_database.database_connection() mycursor = mydb.cursor() print('Connected to MySQL') # Cross-check from previous pontszam data pontlista_checker_result, pontlista_data = pontlista_previous_checker(mycursor, content) # NOTE: Be careful, that is order dependent! sql = 'INSERT INTO lemu_pontlista (orszag_nev, orszag_id, helyezes,' \ 'szabi, ved, tilt, sarkanykod, ' \ 'sziget, hirnev, pontszam, ' \ 'tav, ' \ 'datum_created, magved, ' \ 'other_datum_uploaded, other_who_uploaded, other_comment, ' \ 'pontlista_type, torolt' \ ') VALUES (%s, %s, %s, ' \ '%s, %s, %s, %s, ' \ '%s, %s, %s, ' \ '%s, ' \ '%s, %s, ' \ '%s, %s, %s, ' \ '%s, %s);' val = list(content.values()) print('Execute SQL command: ' + sql) try: mycursor.execute(sql, val) mydb.commit() pontlista_checker_result += ' # ' + str(mycursor.rowcount) + 'record inserted.' except mysql.connector.errors.IntegrityError: pontlista_checker_result += 'Duplicated, has not not re-uploaded' except Exception as ex: err_msg = '[ERROR]: Execption at pontlista feltoltes:' + str(ex) eventlog.log_error(err_msg) pontlista_checker_result += err_msg mydb.close() print(pontlista_checker_result) return pontlista_checker_result, pontlista_data
def gombmegjelenito(): if 'logged_in' not in session or not session['logged_in']: log_event('gombmegjelenito called with invalid login!') return render_template('login_required.html') if request.method == 'GET': orszag_id = request.args.get('orszag_id', type=int) limit = request.args.get('limit', default=5, type=int) log_event('gombmegjelenito called by {} to {}'.format( session['username'], orszag_id)) print('Received content: {}'.format(orszag_id)) lemu_gombkereso_result, orszaginfolist = lemu_gombkereso.gomb_kereses_interface( orszag_id, limit=limit) flash(lemu_gombkereso_result) else: log_error('Invalid call for gombmegjelenito (not GET)') return render_template('gombmegjelenito.html', title='Gömb', orszaginfolist=orszaginfolist)
def gombkereso(): if 'logged_in' not in session or not session['logged_in']: log_event('gombkereso called with invalid login!') return render_template('login_required.html') form = GombKeresoForm() orszaginfolist = [] # Should be initialized for empty search page if request.method == 'POST': if form.validate(): orszag_kereses = request.form['orszag_kereses'] log_event('gombkereso called by {} to {}'.format( session['username'], orszag_kereses)) print('Received content: ' + orszag_kereses) lemu_gombkereso_result, orszaginfolist = lemu_gombkereso.gomb_kereses_interface( orszag_kereses) flash(lemu_gombkereso_result) else: log_error('CSRF ERROR') return render_template('gombkereso.html', title='Gömb kereső', form=form, orszaginfolist=orszaginfolist)
def felmereskereso(): if 'logged_in' not in session or not session['logged_in']: log_event('felmereskereso called with invalid login!') return render_template('login_required.html') form = FelmeresKeresoForm() if request.method == 'POST': if form.validate(): orszag_kereses = request.form['orszag_kereses'] log_event('felmereskereso called by {} to {}'.format( session['username'], orszag_kereses)) print('Received content: ' + orszag_kereses) lemu_felmereskereso_result, felmeres = lemu_felmeres.felmeres_kereses_interface( orszag_kereses) flash(lemu_felmereskereso_result) if felmeres: form.felmeres = felmeres else: log_error('CSRF ERROR') return render_template('felmereskereso.html', title='Felmérés kereső', form=form)
def upload_felmeres(content): result = '' mydb = lemu_database.database_connection() mycursor = mydb.cursor() print('Connected to MySQL') print('Precheck uploaded felmérések') # Dublicate checker sql = 'SELECT * from lemu_felmeresek ' \ 'WHERE LOWER(orszag_nev) = "{orszag_nev}" ' \ ' AND orszag_id = {orszag_id} ' \ ' AND felmeres_tipus LIKE "{felmeres_tipus}" ' \ ' AND datum_created between ' \ ' DATE_SUB("{datum_created}", INTERVAL 3 HOUR) ' \ ' AND DATE_ADD("{datum_created}", INTERVAL 3 HOUR); ' \ ''.format( orszag_nev=content['orszag_nev'].lower().strip(), orszag_id=content['orszag_id'], felmeres_tipus=content['felmeres_tipus'], datum_created=content['datum_created'] ) # SELECT DATE_SUB("2017-06-15", INTERVAL 10 DAY); # where date(game_date) between date('2012-11-03') and date('2012-11-05') print('Execute SQL command: ' + sql) duplicate_check_result = [ ] # 0 length is a trick for the condition at below try: mycursor.execute(sql) duplicate_check_result = mycursor.fetchall() except Exception as ex: err_msg = '[ERROR]: ' + str(ex) result += err_msg + ' | ' eventlog.log_error(err_msg) if len(duplicate_check_result) != 0: print('Duplicate check SQL result: ' + str(duplicate_check_result)) result = 'Seems duplicated, has not re-uploaded: {}\n'.format( duplicate_check_result) else: sql = 'INSERT INTO lemu_felmeresek (' \ 'orszag_nev, orszag_id, ' \ 'datum_created, ' \ 'felmeres_tipus, content, ' \ 'other_datum_uploaded, other_who_uploaded, other_comment' \ ') VALUES (%s, %s, ' \ '%s,' \ '%s, %s,' \ '%s, %s, %s)' val = list(content.values()) print('Execute SQL command: ' + sql) try: mycursor.execute(sql, val) mydb.commit() result += 'Felmeres uploaded: "{}" with type: "{}" with date "{}", {} record inserted'.format( content['orszag_nev'], content['felmeres_tipus'], content['datum_created'], str(mycursor.rowcount)) except mysql.connector.errors.IntegrityError: result += 'Duplicated, has not not re-uploaded' except Exception as ex: err_msg = '[ERROR]: ' + str(ex) eventlog.log_error(err_msg) result += err_msg print('Result: ' + str(result)) mydb.close() return result
def unknown_page(name): log_error('Unknown page request: {}'.format(name)) return 'This is not exists! {}! Please go to the index page! <a href="index">index</a>'.format( name)
def pontlista_previous_checker(mycursor, content): pontlista_data = {} pontlista_data['other_difference'] = [] pontlista_data['orszag_nev'] = content['orszag_nev'] pontlista_data['orszag_id'] = content['orszag_id'] result = '' # NOTE: Be careful, that is order dependent! sql = """ SELECT * FROM lemu_pontlista WHERE lemu_pontlista.orszag_id = {orszag_id} #GROUP BY lemu_pontlista.orszag_id ORDER BY lemu_pontlista.datum_created DESC LIMIT 1; """.format(orszag_id=content['orszag_id']) print('Execute SQL command: ' + sql) try: mycursor.execute(sql) result = mycursor.fetchall() except mysql.connector.errors.IntegrityError: err_msg = '[ERROR]: Failed previous checker - IntegrityError' pontlista_data['other_difference'].append(err_msg) result = err_msg return result, pontlista_data except Exception as ex: err_msg = '[ERROR]: ' + str(ex) pontlista_data['other_difference'].append(err_msg) eventlog.log_error(err_msg) result = err_msg return result, pontlista_data if len(result) == 0: pontlista_data['other_difference'].append('Nem volt előző pontszám információ, nincs mivel összehasonlítani!') result = 'Skip check' return result, pontlista_data result = result[0] # Statusok last_status_szabi = result[mycursor.column_names.index('szabi')] last_status_ved = result[mycursor.column_names.index('ved')] last_status_tilt = result[mycursor.column_names.index('tilt')] last_status_sarkanykod = result[mycursor.column_names.index('sarkanykod')] actual_status_szabi = content['szabi'] actual_status_ved = content['ved'] actual_status_tilt = content['tilt'] actual_status_sarkanykod = content['sarkanykod'] # Pontszám last_pontszam = result[mycursor.column_names.index('pontszam')] actual_pontszam = content['pontszam'] pontszam_compare_limit_low = actual_pontszam * 0.005 pontszam_compare_limit_high = actual_pontszam * 0.01 pontszam_diff_abs = abs(last_pontszam - actual_pontszam) if pontszam_diff_abs > pontszam_compare_limit_low: print('Sokat változott a pontszáma: {}-ról {}-ra'.format(last_pontszam, actual_pontszam)) diff_sign = ('+' if (actual_pontszam > last_pontszam) else '-') * (2 if (pontszam_diff_abs > pontszam_compare_limit_high) else 1) diff_msg = '{} {} --> {} '.format(diff_sign, last_pontszam, actual_pontszam) pontlista_data['pontszam_difference'] = [diff_msg] elif content['szabi'] and pontszam_diff_abs != 0: # at 'szabadsag' print always the difference diff_msg = '{} --> {} '.format(last_pontszam, actual_pontszam) pontlista_data['pontszam_difference'] = [diff_msg] if not last_status_szabi: pontlista_data['other_difference'].append('Szabadság alatt változott a pontszáma!') # else: printed at below # Hírnév hirnev_change_per_hours = 5 last_datetime = result[mycursor.column_names.index('datum_created')] # Here last_datetime is datetime object actual_datetime = datetime.strptime(content['datum_created'], '%Y-%m-%d %H:%M:%S') last_hirnev = result[mycursor.column_names.index('hirnev')] actual_hirnev = content['hirnev'] diff_datetime_in_hours = divmod((last_datetime - actual_datetime).total_seconds(), 60*60)[0] # tuple first value is Hour! hirnev_diff = abs(last_hirnev - actual_hirnev) hirnev_diff_limit_low = abs(hirnev_change_per_hours * diff_datetime_in_hours) hirnev_diff_limit_high = hirnev_diff_limit_low * 2 if hirnev_diff > hirnev_diff_limit_low: print('Sokat változott a hírneve: {}-ról {}-ra'.format(last_hirnev, actual_hirnev)) diff_sign = ('+' if (actual_hirnev > last_hirnev) else '-') * (2 if (hirnev_diff > hirnev_diff_limit_high) else 1) diff_msg = '{} {} --> {} '.format(diff_sign, last_hirnev, actual_hirnev) pontlista_data['hirnev_difference'] = [diff_msg] elif content['szabi'] and hirnev_diff != 0: # at 'szabadsag' print always the difference diff_msg = '{} --> {} '.format(last_hirnev, actual_hirnev) pontlista_data['hirnev_difference'] = [diff_msg] if not last_status_szabi: pontlista_data['other_difference'].append('Szabadság alatt változott a hírneve!') # else: printed at below # Status messages if last_status_szabi != actual_status_szabi: pontlista_data['other_difference'].append('Szabi státusz változása') elif last_status_szabi: pontlista_data['other_difference'].append('Szabin volt') if last_status_ved != actual_status_ved: pontlista_data['other_difference'].append('VED státusz változása') elif last_status_ved: pontlista_data['other_difference'].append('VED volt') if last_status_tilt != actual_status_tilt: pontlista_data['other_difference'].append('Tilt státusz változása') elif last_status_tilt: pontlista_data['other_difference'].append('Tilt volt') if last_status_sarkanykod != actual_status_sarkanykod: pontlista_data['other_difference'].append('Sárkányköd változása') elif last_status_sarkanykod: pontlista_data['other_difference'].append('Sárkányköd volt') # If too long time ago there was no pontszam ('mélyszabi') if diff_datetime_in_hours > 24 * 7: pontlista_data['other_difference'].append('Nem volt pontszám információ nagyon régóta!') result = 'Successfully checked' return result, pontlista_data