Example #1
0
 def test_database_url(self):
     app = Flask(__name__)
     app.config["DATABASE"] = "sqlite:///nugget.db"
     database = FlaskDB(app)
     Model = database.Model
     self.assertTrue(isinstance(Model._meta.database, SqliteDatabase))
     self.assertEqual(Model._meta.database.database, "nugget.db")
Example #2
0
def create_app():
    app = Flask(__name__)
    app.register_blueprint(bp)
    app.config["DEBUG"] = True
    app.config["DATABASE"] = ":memory:"
    app.config["SECRET_KEY"] = "wow"
    db.init_app(app)
    return app
Example #3
0
    def test_database_url(self):
        app = Flask(__name__)
        app.config["DATABASE"] = "sqlite:///nugget.db"
        database = FlaskDB(app)
        Model = database.Model
        self.assertTrue(isinstance(Model._meta.database, SqliteDatabase))
        self.assertEqual(Model._meta.database.database, "nugget.db")

        # If a value is specified, it trumps config value.
        database = FlaskDB(app, "sqlite:///nuglets.db")
        Model = database.Model
        self.assertEqual(Model._meta.database.database, "nuglets.db")
Example #4
0
File: index.py Project: prcek/Quiz
def create_app(config_path):
    global app, conf, database
    conf = ConfigParser.ConfigParser()
    conf.read([config_path])

    app = Flask(
        __name__, static_folder=conf.get("flask", "static_folder"), template_folder=conf.get("jinja", "template_path")
    )
    app.config["DATABASE"] = dict(conf.items("database"))
    database = Database(app)
    import server

    server.init_db()
    # server.load_db()
    # print "load_db"
    return app
Example #5
0
def create_app():
    from redash import handlers
    from redash.admin import init_admin
    from redash.models import db
    from redash.authentication import setup_authentication
    from redash.metrics.request import provision_app

    app = Flask(
        __name__,
        template_folder=settings.STATIC_ASSETS_PATHS[-1],
        static_folder=settings.STATIC_ASSETS_PATHS[-1],
        static_path="/static",
    )

    # Make sure we get the right referral address even behind proxies like nginx.
    app.wsgi_app = ProxyFix(app.wsgi_app, settings.PROXIES_COUNT)
    app.url_map.converters["org_slug"] = SlugConverter

    if settings.ENFORCE_HTTPS:
        SSLify(app, skips=["ping"])

    if settings.SENTRY_DSN:
        from raven.contrib.flask import Sentry
        from raven.handlers.logging import SentryHandler

        sentry = Sentry(app, dsn=settings.SENTRY_DSN)
        sentry.client.release = __version__

        sentry_handler = SentryHandler(settings.SENTRY_DSN)
        sentry_handler.setLevel(logging.ERROR)
        logging.getLogger().addHandler(sentry_handler)

    # configure our database
    settings.DATABASE_CONFIG.update({"threadlocals": True})
    app.config["DATABASE"] = settings.DATABASE_CONFIG
    app.config.update(settings.all_settings())

    provision_app(app)
    init_admin(app)
    db.init_app(app)
    mail.init_app(app)
    setup_authentication(app)
    handlers.init_app(app)

    return app
Example #6
0
monkey.patch_all()
from flask import Flask, request, render_template

from socketio import socketio_manage
from socketio.mixins import BroadcastMixin
from socketio.namespace import BaseNamespace
from socketio.server import SocketIOServer

from pymongo import Connection

import time
import json


app = Flask(__name__, template_folder="views")
app.config["DATABASE"] = "chattr"


conn = Connection(use_greenlets=True)
db = conn[app.config["DATABASE"]]


class ChatNamespace(BaseNamespace, BroadcastMixin):
    def on_chat(self, message):
        message.update({"time": time.time()})
        db.messages.insert(message)
        message.update({"_id": str(message.get("_id"))})
        self.broadcast_event("chat", message)


@app.route("/")
Example #7
0
#!/usr/bin/env/ python

from flask import Flask
from flask.ext.login import LoginManager, AnonymousUserMixin, UserMixin

app = Flask(__name__)
app.config["SECRET_KEY"] = "\xc2\xec\xbd\xcf\xa5\xd4\x87\x8e&\xe1\xa2 \xed\xa73\xfe\xf1\xf5\x15* \x93\xcc\x03E"
app.config["DATABASE"] = "web.db"
app.config.from_object(__name__)

wsgi_app = app.wsgi_app

from routeTest import *
from loginmain import *

if __name__ == "__main__":
    import os

    HOST = os.environ.get("SERVER_HOST", "localhost")
    try:
        PORT = int(os.environ.get("SERVER_POST", "5555"))
    except ValueError:
        PORT = 5555
    app.run(HOST, PORT, debug=True)
Example #8
0
from flask import Flask, request, g, Response, jsonify
from flask.ext.restful import Api, Resource
from werkzeug.exceptions import NotFound, UnsupportedMediaType
import json
import database

# Media type constants:
# http://amundsen.com/media-types/collection/
COLLECTIONJSON = "application/vnd.collection+json"

# Define the application:
app = Flask(__name__)
app.debug = True
app.config["DATABASE"] = database.ServerDatabase(database.DEFAULT_DB_PATH)

# Define the api:
api = Api(app)


def createErrorResponse(status_code, title, message, resource_type=None):
    """Creates a json error response."""
    response = jsonify(title=title, message=message, resource_type=resource_type)
    response.status_code = status_code
    return response


@app.before_request
def set_database():
    """Stores an instance of the database API before each request in flask.g variable accessible only from the app context"""
    g.db = app.config["DATABASE"]
Example #9
0
import os
import sqlite3
import urllib2
import urlparse

BASE_DIR = os.path.dirname(__file__)

from flask import Flask, render_template, request, g, redirect, url_for

app = Flask(__name__)
app.debug = True
app.config["DATABASE"] = os.path.join(BASE_DIR, "data/wiki.db")

# use external config to store google maps key in separate file
external_config_file = os.path.join(BASE_DIR, "config.txt")
if os.path.isfile(external_config_file):
    with open(external_config_file) as f:
        external_config = dict(l.split(":") for l in f)
    app.config.update(external_config)


def nice_str(val):
    my_val = val
    if isinstance(val, unicode):
        my_val = val.encode("ascii")
    return urllib2.unquote(my_val).replace("_", " ").decode("utf8")


def unzip_db():
    print "unzipping geoset database"
    import gzip
Example #10
0
from datetime import date

# from flask_wtf import Form, RecaptchaField
# from wtforms import TextField, HiddenField, ValidationError, RadioField,\
#     BooleanField, SubmitField, IntegerField, FormField, validators
# from wtforms.validators import Required

# initialization

configFile = None

app = Flask(__name__, static_folder="assets")
AppConfig(app, configFile)
app.config["BOOTSTRAP_SERVE_LOCAL"] = True
app.config["DATABASE"] = os.path.join(app.root_path, "tripcost.db")
app.config["SECRET_KEY"] = "jceeJNF42V4j4wJPwc8r"
app.debug = True

# Gravatar initialization
gravatar = Gravatar(app, size=100, rating="g", default="retro", force_default=False, use_ssl=False, base_url=None)

Bootstrap(app)

login_manager = LoginManager()
login_manager.init_app(app)


@app.route("/")
def index():
    is_logged_in = current_user.is_authenticated()
Example #11
0
if __name__ == "__main__":
    option_parser = get_option_parser()
    options, args = option_parser.parse_args()

    if options.config:
        app.config.from_pyfile(options.config)

    if os.environ.get("SCOUT_CONFIG"):
        app.config.from_pyfile(os.environ["SCOUT_CONFIG"])

    if os.environ.get("SCOUT_DATABASE"):
        app.config["DATABASE"] = os.environ["SCOUT_DATABASE"]

    if len(args) == 0 and not app.config.get("DATABASE"):
        panic("Error: missing required path to database file.")
    elif len(args) > 1:
        panic("Error: [%s] only accepts one argument, which is the path " "to the database file." % __file__)
    elif args:
        app.config["DATABASE"] = args[0]

    # Handle command-line options. These values will override any values
    # that may have been specified in the config file.
    if options.api_key:
        app.config["AUTHENTICATION"] = options.api_key

    if options.debug:
        app.config["DEBUG"] = True

    if options.host:
        app.config["HOST"] = options.host
Example #12
0
from sqlalchemy.orm import scoped_session, sessionmaker, relationship
from sqlalchemy.ext.declarative import declarative_base

# FLASK SETUP

ROOT_DIR = os.path.dirname(os.path.abspath(__file__))
STATIC_DIR = os.path.join(ROOT_DIR, "static")

app = Flask(__name__)

# DEFAULT CONFIGURATION

app.config["DEBUG"] = True
app.config["SERVER_HOST"] = "0.0.0.0"
app.config["SERVER_PORT"] = 5000
app.config["DATABASE"] = "sqlite:///recipes.db"
app.config["LANGUAGE"] = "en"
try:
    app.config.from_object("settings")
except ImportError:
    pass

if app.config["DEBUG"]:
    from werkzeug import SharedDataMiddleware

    app.wsgi_app = SharedDataMiddleware(app.wsgi_app, {"/static/": STATIC_DIR})

# AWS SETUP

AWS_CONFIG = Config(signature_version="s3v4", region_name=app.config["AWS_REGION"])
Example #13
0
app.add_url_rule("/legs/<string:leg_name>/knee/", view_func=Knee.as_view("knee"))
app.add_url_rule("/legs/<string:leg_name>/ankle/", view_func=Ankle.as_view("ankle"))

app.add_url_rule("/neck/", view_func=Neck.as_view("neck"))
app.add_url_rule("/torso/", view_func=Torso.as_view("torso"))
# app.add_url_rule("/camera/", view_func=api.Camera.as_view("camera"))

app.add_url_rule("/api/terminate/", view_func=api.Terminate.as_view("terminate"))
app.add_url_rule("/api/speech/", view_func=api.Speech.as_view("speech"))
app.add_url_rule("/api/writing/", view_func=api.Writing.as_view("writing"))
app.add_url_rule("/api/chat/", view_func=api.Chat.as_view("chat"))
app.add_url_rule("/api/status/", view_func=api.Status.as_view("status"))
app.add_url_rule("/api/device_ports/", view_func=api.DevicePorts.as_view("device_ports"))

if __name__ == "__main__":
    app.config["CHATBOT"] = ChatBot()
    app.config["DATABASE"] = Database("settings.db")
    app.config["DEBUG"] = True
    app.config["SECRET_KEY"] = "development"

    if settings_available:
        if hasattr(settings, "GITHUB"):
            app.config["GITHUB"] = GitHub(settings.GITHUB)
        if hasattr(settings, "TWITTER"):
            app.config["TWITTER"] = Twitter(settings.TWITTER)
        if hasattr(settings, "GOOGLE"):
            app.config["GOOGLE"] = settings.GOOGLE
        if hasattr(settings, "DISQUS"):
            app.config["DISQUS"] = settings.DISQUS

    app.run(host="0.0.0.0", port=8000)
Example #14
0
from flask import Flask, render_template, request
from playhouse.flask_utils import FlaskDB, get_object_or_404, object_list
from werkzeug.exceptions import NotFound

from .models import User, db_proxy

# Create app
app = Flask(__name__)
app.config["DATABASE"] = "sqlite:///devdb.sqlite"

# Setup DB
flask_db = FlaskDB(app)
db_proxy.initialize(flask_db.database)

# Create tables
flask_db.database.create_tables([User], safe=True)

# Default route
@app.route("/")
def index():
    return "Hello World!"


# Echo
@app.route("/echo/<word>")
def echo(word):
    return "You said: %s" % word


# Superecho
@app.route("/superecho/<word>")
Example #15
0
        try:
            do_login(request.form["username"].encode("utf-8"), request.form["password"].encode("utf-8"))
        except ValueError:
            error = "Login Failed"
        else:
            return redirect(url_for("show_entries"))
    return render_template("login.html", error=error)


@app.route("/logout")
def logout():
    session.pop("logged_in", None)
    return redirect(url_for("show_entries"))


app.config["DATABASE"] = os.environ.get("DATABASE_URL", "dbname=learning_journal")
app.config["ADMIN_USERNAME"] = os.environ.get("ADMIN_USERNAME", "admin")

app.config["ADMIN_PASSWORD"] = os.environ.get("ADMIN_PASSWORD", pbkdf2_sha256.encrypt("admin"))

app.config["SECRET_KEY"] = os.environ.get("FLASK_SECRET_KEY", "sooperseekritvaluenooneshouldknow")


def connect_db():
    """Return a connection to the configured database"""
    return psycopg2.connect(app.config["DATABASE"])


def init_db():
    """Initialize the database using DB_SCHEMA
Example #16
0
from khome import catalog
from khome.module import path

app = Flask(__name__, static_folder=path.availables_directory())
cache = SimpleCache()

ALLOWED_EXTENSIONS = set(["txt", "pdf", "png", "jpg", "jpeg", "gif"])


def allowed_file(filename):
    return "." in filename and filename.rsplit(".", 1)[1] in ALLOWED_EXTENSIONS


# configure our database
app.config["DATABASE"] = {"name": os.path.join(this_dir, "store.db"), "engine": "peewee.SqliteDatabase"}

# instantiate the db wrapper
db = Database(app)

# write the models


class Rating(db.Model):
    module = CharField()
    value = IntegerField()

    @classmethod
    def average(cls, module_name):
        return cls.get(cls.module == module_name).select(fn.Avg(cls.value).alias("value"))[0].value
Example #17
0
from time import time
from os.path import realpath, dirname
from os import chdir
from base64 import b64encode, b64decode

# changing dir to script directory
chdir(dirname(realpath(__file__)))

app = Flask(__name__)
Bootstrap(app)

# secret key
app.config["SECRET_KEY"] = "CHANGE ME CHANGE ME CHANGE ME"

# sqlite db path
app.config["DATABASE"] = dirname(realpath(__file__)) + "/secret.db"


# form/class for creating the secret
class SecretForm(Form):
    secret_text = TextAreaField("Your secret", validators=[DataRequired()])
    password = PasswordField("Optional password", validators=[Optional()])
    submit = SubmitField("Submit")


# class/form for authenticating if pass protected
class AuthForm(Form):
    password = PasswordField("Secret password", validators=[DataRequired()])
    submit = SubmitField("Submit")

Example #18
0
from boto.s3.key import Key
from fabfile import stack
from flask import Flask, render_template
from flask_peewee.auth import Auth
from flask_peewee.db import Database
from flask_peewee.admin import Admin, ModelAdmin
from models import Slide, SlideSequence, Race, Candidate
from peewee import fn

import app_config
from render_utils import make_context, urlencode_filter, smarty_filter
import static_app

app = Flask(__name__)
app.config["PROPAGATE_EXCEPTIONS"] = True
app.config["DATABASE"] = app_config.DATABASE
app.config["SECRET_KEY"] = "askfhj3r3j"

app.jinja_env.filters["urlencode"] = urlencode_filter
app.jinja_env.filters["smarty"] = smarty_filter
app.register_blueprint(static_app.static_app, url_prefix="/%s" % app_config.PROJECT_SLUG)

file_handler = logging.FileHandler("%s/app.log" % app_config.SERVER_LOG_PATH)
file_handler.setLevel(logging.INFO)
app.logger.addHandler(file_handler)
app.logger.setLevel(logging.INFO)


class SlideAdmin(ModelAdmin):
    exclude = ("slug",)
from flask import Flask

app = Flask(__name__)

app.config["DATABASE"] = "database.db"
app.config["DEBUG"] = True
app.config["SECRET_KEY"] = "like I'd tell you"
app.config["USERNAME"] = "Eric"
app.config["PASSWORD"] = "Schles"

from app import views, models
Example #20
0
from contextlib import closing
from datetime import date, datetime, timedelta
from hashlib import md5
import sqlite3

import config
import forms
from generators import dict_gen

from flask import abort, flash, Flask, g, request, session, redirect, render_template, url_for
from werkzeug import check_password_hash, generate_password_hash

app = Flask(__name__)
app.secret_key = config.SECRET_KEY
app.debug = config.DEBUG
app.config["DATABASE"] = config.DATABASE_URI


def tsformat(value, format="%Y-%d-%m"):
    """ Jinja2 filter, as suggested here:
        http://jinja.pocoo.org/2/documentation/api#custom-filters
    """
    return value.strftime(format)


app.jinja_env.filters["tsformat"] = tsformat


def connect_db():
    """ Connect to SQLite db with support for ISO dates/timestamps.
    
Example #21
0
# Make sure we get the right referral address even behind proxies like nginx.
app.wsgi_app = ProxyFix(app.wsgi_app)

api = Api(app)
init_admin(app)

if settings.SENTRY_DSN:
    from raven.contrib.flask import Sentry

    sentry = Sentry(app, dsn=settings.SENTRY_DSN)
    sentry.client.release = __version__

# configure our database
settings.DATABASE_CONFIG.update({"threadlocals": True})
app.config["DATABASE"] = settings.DATABASE_CONFIG
app.config.update(settings.all_settings())
db.init_app(app)
mail.init_app(app)

from redash.authentication import setup_authentication

setup_authentication(app)


@api.representation("application/json")
def json_representation(data, code, headers=None):
    # Flask-Restful checks only for flask.Response but flask-login uses werkzeug.wrappers.Response
    if isinstance(data, Response):
        return data
    resp = make_response(json.dumps(data, cls=utils.JSONEncoder), code)
Example #22
0
import re
import os
import sqlite3
from flask import Flask, send_from_directory, flash, request, abort
from flask import render_template, redirect, session, url_for, json, g
from werkzeug import secure_filename, generate_password_hash, check_password_hash
from operator import itemgetter
from contextlib import closing

# configuration

app = Flask(__name__)
app.config.from_object(__name__)

app.config["DATABASE"] = os.path.join(app.root_path, "app.db")
app.config["DEBUG"] = True
app.config["SECRET_KEY"] = "I don't know what to keep my secret key"
app.config["UPLOAD_FOLDER"] = os.path.join(app.root_path, "uploads/")
app.config["ALLOWED_EXTENSIONS"] = ["mp3", "ogg", "wav", "aac"]


def connect_db():
    return sqlite3.connect(app.config["DATABASE"])


def init_db():
    with closing(connect_db()) as db:
        with app.open_resource("schema.sql", mode="r") as f:
            db.cursor().executescript(f.read())
        db.commit()
Example #23
0
        raise ValueError("Incorrect database connection URI: {}".format(database_uri))

    database = database_uri[: database_uri.find(split)]

    if database not in LEGAL_DATABASES:
        KeyError('Database "{}" not in allowed list {}'.format(database, LEGAL_DATABASES))

    return database


# Set static assets path
app = Flask(__name__, static_folder="front_end/build", static_url_path="/static")
app.config.from_object(Config)
# Secret key is required for CSRF stuff change this to something more secure
app.secret_key = app.config["SECRET_KEY"]
app.config["DATABASE"] = parse_database_from_uri(app.config["SQLALCHEMY_DATABASE_URI"])
app.logger.debug("I am {}".format(app.config["DATABASE"]))

if app.config["DATABASE"] == "sqlite":
    # Sqlite doesn't enforce Foreign Keys by default. This enables it
    @event.listens_for(Engine, "connect")
    def set_sqlite_pragma(dbapi_connection, connection_record):
        cursor = dbapi_connection.cursor()
        cursor.execute("PRAGMA foreign_keys=ON")
        cursor.close()


db = SQLAlchemy(app)

# Enable Jade templates
app.jinja_env.add_extension("pyjade.ext.jinja.PyJadeExtension")
Example #24
0
    except ImportError:
        logger.debug("Sentry logging disabled. Try pip install raven")

    # Set formatters
    file_handler.setFormatter(formatter)
    console_handler.setFormatter(formatter)

    # add the handlers to the logger
    add_handler_once(logger, file_handler)
    add_handler_once(logger, console_handler)


setup_logger()
LOGGER = logging.getLogger("user_map")

APP = Flask(__name__)

# Load configuration
APP.config["PROJECT_NAME"] = PROJECT_NAME
APP.config["PUBLIC_URL"] = PUBLIC_URL
APP.config["PROJECT_FAVICON_FILE"] = PROJECT_FAVICON_FILE
APP.config.update(MAIL_CONFIG)
mail = Mail(APP)
APP.config["DATABASE"] = SQLITE_DB_PATH
APP.config["USER_ICONS"] = USER_ICONS
# Don't import actual view methods themselves - see:
# http://flask.pocoo.org/docs/patterns/packages/#larger-applications
# Also views must be imported AFTER app is created above.
# noinspection PyUnresolvedReferences
import users.views
Example #25
0
from .views.existinguser import existinguser
from .views.display import display
from .views.controller import controller
from .views.newuser import newuser
from .views.summary import summarize
from .model import User

# accounts={'PREMIER':'PREMIER','ADVANCED':'ADVANCED','SAVINGS':'SAVINGS','TIME DEPOSITS':'TIME DEPOSITS','DSARA GW':'DSARA GROUNDWORKS','DSARA PL':'DSARA PILING','CASH':'CASH','DSARA IN':'DSARA IN'}
currencylist = ["GBP", "MYR"]

# create app
app = Flask(__name__, instance_relative_config=True)
app.config.from_object("config")  # looks for capitalized variables declared
app.config.from_pyfile("config.py")

app.config["DATABASE"] = os.path.join(app.instance_path, "database.db")

app.register_blueprint(existinguser)
app.register_blueprint(display)
app.register_blueprint(controller)
app.register_blueprint(newuser)
app.register_blueprint(summarize)

# session['logged_in']=False
# session.pop('username',None)

# Flask-Login crap
login_manager = LoginManager()
login_manager.init_app(app)
login_manager.login_view = "existinguser.login"
Example #26
0
class DB(FlaskDB):
    def connect_db(self):
        super(DB, self).connect_db()
        if not Book.table_exists():
            Book.create_table()

    def close_db(self, exc):
        # This is only necessary for a sqlite :memory: databases to prevent the
        # database from being destroyed after each request.
        pass


app = Flask(__name__)
app.debug = True
app.config["DATABASE"] = "sqlite://"

db = DB(app)


class Book(db.Model):
    title = CharField(null=True, unique=True)
    year_published = IntegerField()


class BookResource(ModelResource):
    class Meta:
        name = "book"
        model = Book

    class Schema:
Example #27
0
# all the imports
import sqlite3
from flask import Flask, request, session, g, redirect, url_for, abort, render_template, flash
from contextlib import closing


# create our little application :)
app = Flask(__name__)
app.config.from_envvar("FLASKR_SETTINGS", silent=True)

# configuration
app.config["DATABASE"] = "tmp\flaskr.db"
app.config["DEBUG"] = True
app.config["SECRET_KEY"] = "development key"
app.config["USERNAME"] = "admin"
app.config["PASSWORD"] = "default"


def connect_db():
    return sqlite3.connect(app.config["DATABASE"])


def init_db():
    with closing(connect_db()) as db:
        with app.open_resource("schema.sql", mode="r") as f:
            db.cursor().executescript(f.read())
        db.commit()


@app.before_request
def before_request():
Example #28
0
from flask import Flask, url_for, redirect, render_template, request
from mongoengine import *

from flask.ext import superadmin, login, wtf
from flask.ext.superadmin.contrib import mongoenginemodel

# Create application
app = Flask(__name__)

# Create dummy secrey key so we can use sessions
app.config["SECRET_KEY"] = "123456790"

# Database name for Mongo
app.config["DATABASE"] = "dummy_db"


# Create user model. For simplicity, it will store passwords in plain text.
# Obviously that's not right thing to do in real world application.
class User(Document):
    id = StringField(primary_key=True)
    login = StringField(max_length=80, unique=True)
    email = EmailField(max_length=120)
    password = StringField(max_length=64)

    # Flask-Login integration
    def is_authenticated(self):
        return True

    def is_active(self):
        return True
Example #29
0
if ON_OPENSHIFT:
    DATABASE = {
        "name": os.environ["OPENSHIFT_APP_NAME"],
        "engine": "peewee.PostgresqlDatabase",
        "host": os.environ["OPENSHIFT_DB_HOST"],
        "port": os.environ["OPENSHIFT_DB_PORT"],
        "user": os.environ["OPENSHIFT_DB_USERNAME"],
        "password": os.environ["OPENSHIFT_DB_PASSWORD"],
    }
else:
    DATABASE = {"name": "example.db", "engine": "peewee.SqliteDatabase", "check_same_thread": False}

app = Flask(__name__)
app.config.from_object("config")
app.config["SECRET_KEY"] = "123456790"
app.config["DATABASE"] = DATABASE


admin = Admin(app)
# db = Database(app)
db = SqliteDatabase("test.sqlite", check_same_thread=False)


@app.errorhandler(404)
def not_found(error):
    return render_template("404.html"), 404


@app.before_request
def before_request():
    g.db = db
Example #30
0
# imports
from flask import Flask, render_template, request, redirect, g, flash, url_for
from contextlib import closing
import sqlite3

# app
app = Flask(__name__)

# config
app.config["DATABASE"] = "/tmp/flasktodo.db"
app.config["SECRET_KEY"] = "secret key"

app.config.from_envvar("FLASKTODO_SETTINGS", silent=True)

# connect db
def connect_db():
    return sqlite3.connect(app.config["DATABASE"])


# init db
def init_db():
    with closing(connect_db()) as db:
        with app.open_resource("schema.sql", mode="r") as f:
            db.cursor().executescript(f.read())
        db.commit()


@app.before_request
def before_request():
    g.db = connect_db()