From b3ced12130a50a6cd7eae56aa7b83c09e9cd7b12 Mon Sep 17 00:00:00 2001
From: jonasled <jonas@jonasled.de>
Date: Fri, 21 Feb 2020 11:27:00 +0100
Subject: [PATCH] replaced some imports

---
 api.py                |  4 ++--
 clonedb.py            | 10 +++++-----
 deletelink.py         |  4 ++--
 githubcallback.py     |  6 +++---
 importHelper.py       |  1 -
 main.py               | 34 +++++++++++++++++-----------------
 makeqr.py             | 10 +++++-----
 newurl.py             |  4 ++--
 redirectShortenURL.py |  4 ++--
 table_check.py        |  8 ++++----
 userprofile.py        |  4 ++--
 11 files changed, 44 insertions(+), 45 deletions(-)

diff --git a/api.py b/api.py
index 8f5630c..96648ca 100644
--- a/api.py
+++ b/api.py
@@ -1,5 +1,5 @@
 from flask import jsonify, render_template
-import sqlite3
+from sqlite3 import connect
 from makeqr import makeQR
 
 def apiGet(request, url_scheme, s, sAPI):
@@ -41,7 +41,7 @@ def apiPost(request, url_scheme, domain, sAPI):
             message="domain for short link is not in allowed domain list"
         )
     
-    with sqlite3.connect('db/urls.db') as conn: #Check if another user already used the short link
+    with connect('db/urls.db') as conn: #Check if another user already used the short link
         cursor = conn.cursor()
         res = cursor.execute('SELECT LONG_URL FROM WEB_URL WHERE SHORT_URL=?', [short])
         try:
diff --git a/clonedb.py b/clonedb.py
index 136e2dd..d1c2946 100644
--- a/clonedb.py
+++ b/clonedb.py
@@ -2,7 +2,7 @@
 # This script will clone all entries from the database. I ised this to show what happens with extreme database sizes.
 #The output will be in excel-style CSV (";" instead of "," as column seperator.)
 
-import sqlite3
+from sqlite3 import connect, OperationalError
 from tqdm import tqdm
 
 create_table = """
@@ -11,18 +11,18 @@ create_table = """
     LONG_URL TEXT NOT NULL, SHORT_URL TEXT NOT NULL
     );
     """
-with sqlite3.connect('db/urls.db') as conn:
+with connect('db/urls.db') as conn:
     cursor = conn.cursor()
     try: #Try making the database structure, if succeeded, exit, because there can't be any data.
         cursor.execute(create_table)
         raise Exception('No database Found', "Can't find the database ==> No data to clone")
-    except sqlite3.OperationalError:
+    except OperationalError:
         pass
 
-conn = sqlite3.connect('db/urls.db')
+conn = connect('db/urls.db')
 cursor = conn.cursor()
 res = cursor.execute('SELECT LONG_URL, SHORT_URL FROM WEB_URL WHERE 1') #read all data from database
-with sqlite3.connect('db/urls.db') as conn2:
+with connect('db/urls.db') as conn2:
     cursor2 = conn2.cursor()
     for entries in tqdm(res.fetchall()):
         cursor2.execute( #Insert the data in the SQL table
diff --git a/deletelink.py b/deletelink.py
index 9ee137a..454a4ff 100644
--- a/deletelink.py
+++ b/deletelink.py
@@ -1,4 +1,4 @@
-import sqlite3
+from sqlite3 import connect
 from flask import redirect, abort
 
 def deleteLink(request, s):
@@ -10,7 +10,7 @@ def deleteLink(request, s):
         return redirect("/user/login") # if user is not logged in redirect him to the login page
     linkToDelete = request.args.get('link') #get the link, which the user want's to delete from the parameter in the url.
 
-    with sqlite3.connect('db/urls.db') as conn:
+    with connect('db/urls.db') as conn:
         cursor = conn.cursor()
         try:
             cursor.execute('DELETE FROM WEB_URL WHERE SHORT_URL=? AND USERNAME=?', [linkToDelete, userID]) #Delete the entrie
diff --git a/githubcallback.py b/githubcallback.py
index 429107d..8c18ade 100644
--- a/githubcallback.py
+++ b/githubcallback.py
@@ -1,6 +1,6 @@
 from flask import make_response, redirect
 from requests import post, get
-import json #used for github oauth
+from json import loads #used for github oauth
 
 def githubCallback(request, GITHUB_CLIENT_SECRET, GITHUB_CLIENT_ID, s):
     try:
@@ -11,8 +11,8 @@ def githubCallback(request, GITHUB_CLIENT_SECRET, GITHUB_CLIENT_ID, s):
 
         headers = {'Authorization': 'token ' + oauth_token,} #Useragent doesn't matters, but is set here
         githubResponse = get("https://api.github.com/user", headers=headers).text
-        userID = str(json.loads(githubResponse)['id'])
-        username = str(json.loads(githubResponse)['login'])
+        userID = str(loads(githubResponse)['id'])
+        username = str(loads(githubResponse)['login'])
 
         resp = make_response(redirect('/')) #redirect the user at the end back to the main page
         resp.set_cookie('userID', s.dumps("github_" + userID)) #set the cookies with username and userid
diff --git a/importHelper.py b/importHelper.py
index 49f7534..5e39142 100644
--- a/importHelper.py
+++ b/importHelper.py
@@ -1,5 +1,4 @@
 #!/usr/bin/env python3
-import os
 
 lines = []
 print("ready to recive data, please paste your data to import and press ENTER")
diff --git a/main.py b/main.py
index 818f380..ecfcd43 100644
--- a/main.py
+++ b/main.py
@@ -1,10 +1,10 @@
 #!/usr/bin/env python3
 from waitress import serve #Used as webserver (Production)
 from flask import Flask, request, redirect, make_response #Used to prepare the dynamic pages
-import os #Used for getting the enviorement variables
+from os import environ #Used for getting the enviorement variables
 from itsdangerous import URLSafeSerializer #used for signing the cookies
-import random #used for signing the cookies
-import string #used for signing the cookies
+from random import choice#used for signing the cookies
+from string import ascii_lowercase #used for signing the cookies 
 from table_check import table_check #import the table check file
 from makeqr import makeQR #Qr code generation tool
 from grecaptcha_verify import grecaptcha_verify #Tool to verify the google recaptcha response
@@ -23,12 +23,12 @@ app = Flask(__name__)
 domain_to_index = {}
 
 try:
-    domain = os.environ["domains"].split(";") #Get the domains from the enviorement variable. If no enviorement variable is set it will be set to 127.0.0.1:5000 (for testing)
+    domain = environ["domains"].split(";") #Get the domains from the enviorement variable. If no enviorement variable is set it will be set to 127.0.0.1:5000 (for testing)
 except:
     domain = ["localhost:5000", "127.0.0.1:5000"]
 
 try:
-    if(os.environ["show_build_date"] == "1"): #If you want to see the builddate you can enable this enviorement variable
+    if(environ["show_build_date"] == "1"): #If you want to see the builddate you can enable this enviorement variable
         builddate = open("builddate.txt", "r").read()
     else:
         builddate = ""
@@ -36,7 +36,7 @@ except:
     builddate = "" #If the enviorement Variable is not set also skip the builddate
 
 try:
-    if(os.environ["show_version"] == "1"): #If you want to see the builddate you can enable this enviorement variable
+    if(environ["show_version"] == "1"): #If you want to see the builddate you can enable this enviorement variable
         version = open("VERSION", "r").read()
     else:
         version = ""
@@ -44,8 +44,8 @@ except:
     version = "" #If the enviorement Variable is not set also skip the version
 
 try:
-    recaptchaPrivateKey = os.environ["recaptcha_private"] #Get the recaptcha keys, if not set set skipRecaptcha to true to skip the check. If the publicKey is not set the user also will not get the code needed for recaptcha delivered in the page.
-    recaptchaPublicKey = os.environ["recaptcha_public"]
+    recaptchaPrivateKey = environ["recaptcha_private"] #Get the recaptcha keys, if not set set skipRecaptcha to true to skip the check. If the publicKey is not set the user also will not get the code needed for recaptcha delivered in the page.
+    recaptchaPublicKey = environ["recaptcha_public"]
     if(recaptchaPrivateKey != "") and (recaptchaPublicKey != ""): #If the variables are empty also skip the captcha
         skipCaptcha = False
     else:
@@ -57,7 +57,7 @@ except:
     skipCaptcha = True
 
 try:
-    if(os.environ["production"] == "1"): #If you use this in production, please set this to 1, because the Flask Testserver is not very secure (e.g. shows error on Website)
+    if(environ["production"] == "1"): #If you use this in production, please set this to 1, because the Flask Testserver is not very secure (e.g. shows error on Website)
         production = True
     else:
         production = False
@@ -65,26 +65,26 @@ except:
     production = False
 
 try: #If you use https with a proxy afterwards you can set this to https and internal redirects will be https not http. This is to prevent bugs with modern browsers, bacause they block http content if the main page is loaded via https.
-    url_scheme = os.environ["url_scheme"]
+    url_scheme = environ["url_scheme"]
 except:
     url_scheme = "http"
 
 try:
-    host=os.environ["host"]
+    host=environ["host"]
 except:
     host="127.0.0.1"
 
 try: #Try to get the oauth keys, if it fails, abort and print a message to console
-    GITHUB_CLIENT_ID = os.environ['GITHUB_CLIENT_ID']
-    GITHUB_CLIENT_SECRET = os.environ['GITHUB_CLIENT_SECRET']
-    GOOGLE_CLIENT_ID = os.environ['GOOGLE_CLIENT_ID']
-    GOOGLE_CLIENT_SECRET = os.environ['GOOGLE_CLIENT_SECRET']
+    GITHUB_CLIENT_ID = environ['GITHUB_CLIENT_ID']
+    GITHUB_CLIENT_SECRET = environ['GITHUB_CLIENT_SECRET']
+    GOOGLE_CLIENT_ID = environ['GOOGLE_CLIENT_ID']
+    GOOGLE_CLIENT_SECRET = environ['GOOGLE_CLIENT_SECRET']
 except:
     print("please set the oauth keys and run again.")
     exit()
 
 try: #check, if admin wants to show a cookie notice to the user. 
-    if(os.environ["cookieNotice"] == 1):
+    if(environ["cookieNotice"] == 1):
         cookieNotice = True
     else:
         cookieNotice = False
@@ -94,7 +94,7 @@ except:
 try: #The secret key is used to crypt the auth cookie. There will be a seccond key to make the api key.
     secretKey = open("db/secretKey.txt", "r").read()
 except:
-    secretKey = ''.join(random.choice(string.ascii_lowercase) for i in range(100)) #If we can't find the secret key(first run) we generate it in this step and write it to a file
+    secretKey = ''.join(choice(ascii_lowercase) for i in range(100)) #If we can't find the secret key(first run) we generate it in this step and write it to a file
     print("generated secret Key. Key is: " + secretKey)
     f = open("db/secretKey.txt", "w")
     f.write(secretKey)
diff --git a/makeqr.py b/makeqr.py
index 3ce8b53..058324c 100644
--- a/makeqr.py
+++ b/makeqr.py
@@ -1,12 +1,12 @@
-import qrcode #Used to generate the QR
-import base64 #Used to encode the generated QR as base64, to directly insert it into the HTML
+from qrcode import QRCode, constants #Used to generate the QR
+from base64 import b64encode #Used to encode the generated QR as base64, to directly insert it into the HTML
 from io import BytesIO #Needed for base64 encoding of the image
 from PIL import Image #Needed for QR generation
 
 def makeQR(text): #This function is used to create a QR code and encode it base64, if you make a new shortlink
-    qr = qrcode.QRCode( #QR generation variables
+    qr = QRCode( #QR generation variables
         version=1,
-        error_correction=qrcode.constants.ERROR_CORRECT_L,
+        error_correction=constants.ERROR_CORRECT_L,
         box_size=10,
         border=1,
     )
@@ -16,4 +16,4 @@ def makeQR(text): #This function is used to create a QR code and encode it base6
     img = qr.make_image(fill_color="black", back_color="white") #Encode the WR as base 64
     with BytesIO() as buffer:
         img.save(buffer, 'jpeg')
-        return base64.b64encode(buffer.getvalue()).decode()
\ No newline at end of file
+        return b64encode(buffer.getvalue()).decode()
\ No newline at end of file
diff --git a/newurl.py b/newurl.py
index 0f0d07b..2034fb6 100644
--- a/newurl.py
+++ b/newurl.py
@@ -1,6 +1,6 @@
 from grecaptcha_verify import grecaptcha_verify
 from flask import render_template
-import sqlite3
+from sqlite3 import connect
 from makeqr import makeQR
 
 def newurl(request, skipCaptcha, recaptchaPrivateKey, recaptchaPublicKey, builddate, version, domain_prepared, domain_to_index, showDomainSelect, cookieNotice, s, url_scheme):
@@ -20,7 +20,7 @@ def newurl(request, skipCaptcha, recaptchaPrivateKey, recaptchaPublicKey, buildd
     shorturl = (request.form.get('domain') + "/" + request.form.get('short')).lower()
 
     url = request.form.get('url')
-    with sqlite3.connect('db/urls.db') as conn: #Check if another user already used the short link
+    with connect('db/urls.db') as conn: #Check if another user already used the short link
         cursor = conn.cursor()
         res = cursor.execute('SELECT LONG_URL FROM WEB_URL WHERE SHORT_URL=?', [shorturl])
         try:
diff --git a/redirectShortenURL.py b/redirectShortenURL.py
index 99f1eae..6d95925 100644
--- a/redirectShortenURL.py
+++ b/redirectShortenURL.py
@@ -1,10 +1,10 @@
 from flask import redirect, abort
-import sqlite3
+from sqlite3 import connect
 
 def redirectShortenURL(request, short_url):
     host = request.headers['Host']
     url = ""
-    with sqlite3.connect('db/urls.db') as conn: #Get the original URL from the database
+    with connect('db/urls.db') as conn: #Get the original URL from the database
         cursor = conn.cursor()
         res = cursor.execute('SELECT LONG_URL FROM WEB_URL WHERE SHORT_URL=?', [host + "/" + short_url.lower()])
         try:
diff --git a/table_check.py b/table_check.py
index f502d97..329f34f 100644
--- a/table_check.py
+++ b/table_check.py
@@ -1,4 +1,4 @@
-import sqlite3
+from sqlite3 import connect, OperationalError
 
 def table_check(): #This function is used on start to make a new Database if not already exists.
     create_table_data = """
@@ -14,13 +14,13 @@ def table_check(): #This function is used on start to make a new Database if not
             CALLS INT DEFAULT 1
         )
     """
-    with sqlite3.connect('db/urls.db') as conn:
+    with 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_data)
-        except sqlite3.OperationalError:
+        except OperationalError:
             pass
         try: #Try making the database structure, if fails Database was already created.
             cursor.execute(create_table_analytics)
-        except sqlite3.OperationalError:
+        except OperationalError:
             pass
\ No newline at end of file
diff --git a/userprofile.py b/userprofile.py
index 7180973..c4ca18a 100644
--- a/userprofile.py
+++ b/userprofile.py
@@ -1,4 +1,4 @@
-import sqlite3
+from sqlite3 import connect
 from flask import redirect, abort, render_template
 from html import escape #This is used to escape characters, if they are send in the url
 
@@ -19,7 +19,7 @@ def userProfile(request, cookieNotice, s, pageNumber, url_scheme):
     except:
         abort(404)
 
-    with sqlite3.connect('db/urls.db') as conn:
+    with connect('db/urls.db') as conn:
         cursor = conn.cursor()
         res = cursor.execute('SELECT LONG_URL, SHORT_URL FROM WEB_URL WHERE USERNAME=?', [userID]) #Get all entries from the database, that are created by this user
         response = '<table id="t01">\n<tr>\n<th>Long URL</th>\n<th>Short URL</th>\n<th>Views</th>\n<th>Action</th>\n</tr>\n' #This is the layout of the table
-- 
GitLab