diff --git a/main.py b/main.py index 4c053053d54d3a68e6f41064b073e74197259a1e..4baa1ee8efa304ddf7d28f36fc4f471cdcadc898 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')