import sqlite3

try:
    from flask import _app_ctx_stack as stack
except ImportError:
    from flask import _request_ctx_stack as stack

class DBConfigurator():

    def __init__(self, app=None):
        if app is not None:
            self.app = app
            self.init_app(self.app)
        else:
            self.app = None

    def init_app(self, app):
        app.config['CONFIG_DATABASE'] = "/tmp/" + app.name + ".db"
        # Use the newstyle teardown_appcontext if it's available,
        # otherwise fall back to the request context
        if hasattr(app, 'teardown_appcontext'):
            app.teardown_appcontext(self.teardown)
        else:
            app.teardown_request(self.teardown)

    def connect(self):
        return sqlite3.connect(self.app.config['CONFIG_DATABASE'])

    @property
    def connection(self):
        ctx = stack.top
        if ctx is not None:
            if not hasattr(ctx, 'configuration_db'):
                ctx.configuration_db = self.connect()
            return ctx.configuration_db

    def configuration_available(self):
        query = "SELECT * FROM configuration_data"
        self.app.logger.debug("Checking for existing configuration data...")
        try:
            connection.cursor().execute(query)
            results = connection.cursor().fetchall()
            connection.cursor().close()
        except sqlite3.OperationalError:
            self.app.logger.debug("Nope.")
            return False

        self.app.logger.debug("Found!")
        return True

    def setup_config_table(self):
        query = "CREATE TABLE configuration_data (var_name text, value text)"
        self.app.logger.debug("Setting up configuration table...")
        try:
            connection.cursor().execute(query)
            results = connection.cursor().fetchall()
            connection.cursor().close()
            connection.commit()
        except sqlite3.OperationalError as e:
            self.app.logger.error("An error occured while setting up configuration table: " + str(e))
            return False

        self.app.logger.debug("Configuration table setup successfully!")
        return True

    def configure_from_db(self):
        query = "SELECT * FROM configuration_data"
        config = {}
        self.app.logger.debug("Loading app configuration from table...")
        try:
            for row in connection.cursor().execute(query):
                config[row[0]] = row[1]
            connection.cursor().close()
        except sqlite3.OperationalError:
            self.app.logger.error("A DB error occured while loading configuration.")
            return

        for k, v in config.iteritems():
            self.app.config[k] = v

        self.app.logger.debug("Loaded %s configuration variables." % len(config))

    def set_configuration_data(self, var_name, value):
        find_query = "SELECT * FROM configuration_data WHERE var_name = '%s'" % (var_name)
        insert_query = "INSERT INTO configuration_data VALUES ('%s', '%s')" % (var_name, value)
        update_query = "UPDATE configuration_data SET value='%s' WHERE var_name='%s'" % (value, var_name)
        self.app.logger.debug("Setting app configuration from table...")
        try:
            rows = connection.cursor().execute(find_query).fetchall()
            if len(rows) == 0:
                connection.cursor().execute(insert_query)
            else:
                connection.cursor().execute(update_query)
            connection.cursor().close()
        except sqlite3.OperationalError:
            self.app.logger.error("A DB error occured while setting configuration.")
            return

        self.app.logger.debug("Configuration set successfully: %s=%s" % (var_name, value))

@@ -792,16 +792,162 @@
 ASE'%5D)%0A%0A
+    def teardown(self, exception):%0A        ctx = stack.top%0A        if hasattr(ctx, 'configuration_db'):%0A            ctx.configuration_db.close()%0A%0A
     @pro
@@ -1176,16 +1176,64 @@
 ation_db
+%0A        else:%0A            return self.connect()
 %0A%0A    de
@@ -1410,32 +1410,37 @@
 ry:%0A            
+self.
 connection.curso
@@ -1472,32 +1472,37 @@
       results = 
+self.
 connection.curso
@@ -1520,48 +1520,8 @@
 l()%0A
-            connection.cursor().close()%0A
     
@@ -1784,20 +1784,32 @@
 ame 
-text
+TEXT PRIMARY KEY
 , value 
 text
@@ -1804,20 +1804,20 @@
 , value 
-text
+TEXT
 )%22%0A     
@@ -1895,32 +1895,37 @@
 ry:%0A            
+self.
 connection.curso
@@ -1961,24 +1961,29 @@
   results = 
+self.
 connection.c
@@ -2017,48 +2017,13 @@
     
-connection.cursor().close()%0A            
+self.
 conn
@@ -2519,16 +2519,21 @@
  row in 
+self.
 connecti
@@ -2604,48 +2604,8 @@
 %5B1%5D%0A
-            connection.cursor().close()%0A
     
@@ -2738,32 +2738,59 @@
         return%0A%0A
+        print(str(config))%0A
         for k, v
@@ -2991,99 +2991,8 @@
 e):%0A
-        find_query = %22SELECT * FROM configuration_data WHERE var_name = '%25s'%22 %25 (var_name)%0A
     
@@ -3018,16 +3018,27 @@
 %22INSERT 
+OR REPLACE 
 INTO con
@@ -3098,114 +3098,8 @@
 ue)%0A
-        update_query = %22UPDATE configuration_data SET value='%25s' WHERE var_name='%25s'%22 %25 (value, var_name)%0A
     
@@ -3199,16 +3199,21 @@
  rows = 
+self.
 connecti
@@ -3236,12 +3236,14 @@
 ute(
-f
 in
-d
+sert
 _que
@@ -3273,198 +3273,30 @@
     
-if len(rows) == 0:%0A                connection.cursor().execute(insert_query)%0A            else:%0A                connection.cursor().execute(update_query)%0A            connection.cursor().close
+self.connection.commit
 ()%0A 

use the variable name as the primary key