From b15ed3778b898caad31c35e2f787821dc2bc1a23 Mon Sep 17 00:00:00 2001 From: jonasled <jonas@jonasled.de> Date: Fri, 17 Jan 2020 16:04:33 +0100 Subject: [PATCH] implemented counter --- main.py | 36 +++++++++++++++++++++++++++--------- 1 file changed, 27 insertions(+), 9 deletions(-) diff --git a/main.py b/main.py index 4c05305..4baa1ee 100644 --- a/main.py +++ b/main.py @@ -116,17 +116,27 @@ else: def table_check(): #This function is used on start to make a new Database if not already exists. - create_table = """ + create_table_data = """ CREATE TABLE WEB_URL( - LONG_URL TEXT NOT NULL, - SHORT_URL TEXT NOT NULL, - USERNAME TEXT + LONG_URL TEXT NOT NULL, + SHORT_URL TEXT NOT NULL, + USERNAME TEXT ); """ + create_table_analytics = """ + CREATE TABLE ANALYTICS( + SHORT_URL TEXT NOT NULL, + CALLS INT DEFAULT 1 + ) + """ with sqlite3.connect('db/urls.db') as conn: cursor = conn.cursor() try: #Try making the database structure, if fails Database was already created. - cursor.execute(create_table) + cursor.execute(create_table_data) + except sqlite3.OperationalError: + pass + try: #Try making the database structure, if fails Database was already created. + cursor.execute(create_table_analytics) except sqlite3.OperationalError: pass @@ -232,10 +242,18 @@ def redirect_short_url(short_url): except Exception as e: #If there happens an error, print the exception to the console and throw a 500 error print(e) #Print a debug Message to the console abort(500) #Throw a 500 error. This means internal Server error. - if not error_404: #If there was no 404 error before, redirect the user. If not throw a 404 error - return redirect(url) - else: - abort(404) + if not error_404: #If there was no 404 error before, redirect the user. If not throw a 404 error + res = cursor.execute('SELECT CALLS FROM ANALYTICS WHERE SHORT_URL=?', [host + "/" + short_url.lower()]) + try: + calls = res.fetchone()[0] + 1 + cursor.execute('UPDATE ANALYTICS SET CALLS = ? WHERE SHORT_URL=?', (str(calls), host + "/" + short_url.lower())) + except: + print(Exception) + cursor.execute('INSERT INTO ANALYTICS (SHORT_URL) VALUES ("' + host + "/" + short_url.lower() + "\")") + + return redirect(url) + else: + abort(404) @app.route('/user/login') -- GitLab