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 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 #3
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
def create_app(configfile=None):
    # We are using the "Application Factory"-pattern here, which is described
    # in detail inside the Flask docs:
    # http://flask.pocoo.org/docs/patterns/appfactories/

    app = Flask(__name__, static_url_path='')

    # We use Flask-Appconfig here, but this is not a requirement
    AppConfig(app, configfile)

    # Kludges for heroku
    if 'DYNO' in os.environ:
        # HerokuConfig is only needed if you do smtp etc. but whatever.
        from flask_appconfig import HerokuConfig
        HerokuConfig(app)
        from flask_sslify import SSLify
        sslify = SSLify(app, permanent=True)
        app.config['PREFERRED_URL_SCHEME'] = 'https'
        stdout_logging(app)
        app.config['DATABASE'] = os.environ.get('DATABASE_URL')

    database.init_app(app)

    BabelByUrl(app)

    ## Note: if you remove roles, they *don't* get removed from
    # an existing datastore (flask_security doens't support that),
    # If you *really* need this, start from a fresh db.
    # USER_ROLES are hardwired in code, because without code changes
    # they're meaningless ;)
    # Also note that you don't need to explicitly mention 'admin'.
    app.config['USER_ROLES'] = ['editor']
    init_auth(app)

    init_models(app)

    app.config['BOOTSTRAP_SERVE_LOCAL'] = True  # CDNs are cancer
    Bootstrap(app)

    Misaka(app)

    init_custom_nav_renderer(app)
    nav.init_app(app)

    app.register_blueprint(frontend, template_folder='templates')
    app.register_blueprint(backend, url_prefix='/editors')
    app.register_blueprint(useradmin, url_prefix='/useradmin', template_folder='sitepack/templates')

    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)
    limiter.init_app(app)

    return app
Example #6
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(
Example #7
0
DB_INSERT_ENTRY = """
INSERT INTO entries (title, text, created) VALUES (%s, %s, %s)
"""
DB_SELECT_ENTRIES_LIST = """
SELECT id, title, text, created FROM entries ORDER BY created DESC
"""
DB_SELECT_ENTRY = """
SELECT * FROM entries WHERE id = %s
"""
DB_UPDATE_ENTRY = """
UPDATE entries SET title = %s, text = %s WHERE id = %s
"""

app = Flask(__name__)
app.config['DATABASE'] = os.environ.get(
    'DATABASE_URL', 'dbname=gqscrapings user=charlesgust'
    )
# add the following two settings just below
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'
)


class GQStore():
    def __init__():
Example #8
0
app.config.from_object('chalicepoints.config.DefaultConfig')
app.config['SECRET_KEY'] = os.getenv('APP_SECRET_KEY', app.config['SECRET_KEY'])

if app.config['SECRET_KEY'] is None:
  abort(500)

# Flask-Login
login_manager = LoginManager()
login_manager.login_view = 'site.login'
login_manager.init_app(app)

app.config['DATABASE'] = {
  'engine': 'peewee.MySQLDatabase',
  'name': app.config['MYSQL_DATABASE'],
  'user': app.config['MYSQL_USER'],
  'passwd': app.config['MYSQL_PASSWORD'],
  'host': app.config['MYSQL_HOST'],
  'threadlocals': True,
  'autocommit': False
}

db = Database(app)

def register_blueprint(app):
  from chalicepoints.views.site import site
  app.register_blueprint(site)

  from chalicepoints.views.api import api
  app.register_blueprint(api)

register_blueprint(app)
Example #9
0
# -*- coding: utf-8 -*-
__version__ = '0.3.0'

from flask import Flask
app = Flask('streck')
app.config['VERSION'] = __version__
app.config['DATABASE'] = './streck/streck.db'
app.config['PAID_BARCODE'] = 'BETALT'
app.config['UNDO_BARCODE'] = 'undo'
app.config['LOGOUT_BARCODE'] = 'log out'
app.config['JOBBMAT_BARCODE'] = 'Jobbmat'
app.config['REMOVE_JOBBMAT_BARCODE'] = 'Ta+bort+jobbmat'
app.config['ALLOWED_JOBBMAT_CATEGORIES'] = [u'Icke├Âl']
app.config['UPLOAD_FOLDER'] = './pictures/'
app.secret_key = '\xbe\xb8_i\xbe\xe7{\xd0\xb8\xb6\x9b\xb3\x8c#\xc4\x81\x8bZ\x994cEcf'

import streck.models
import streck.controller
Example #10
0
    logging.getLogger().setLevel(settings.LOG_LEVEL)

    events.setup_logging(settings.EVENTS_LOG_PATH, settings.EVENTS_CONSOLE_OUTPUT)

setup_logging()

app = Flask(__name__,
            template_folder=settings.STATIC_ASSETS_PATH,
            static_folder=settings.STATIC_ASSETS_PATH,
            static_path='/static')

api = Api(app)

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

from redash.authentication import setup_authentication
auth = setup_authentication(app)

@api.representation('application/json')
def json_representation(data, code, headers=None):
    resp = make_response(json.dumps(data, cls=utils.JSONEncoder), code)
    resp.headers.extend(headers or {})
    return resp


redis_url = urlparse.urlparse(settings.REDIS_URL)
if redis_url.path:
    redis_db = redis_url.path[1]
Example #11
0
from gridfs import GridFS
from gridfs.errors import NoFile
from werkzeug.exceptions import NotFound
from functools import wraps
import json
import StringIO
import gzip
from pyrpm import rpmdefs
from pyrpm.rpm import RPM


DEBUG = True

app = Flask(__name__)
app.config.from_object(__name__)
app.config['DATABASE'] = 'shepherd'

def connect_db():
   c = Connection()
   return c[app.config['DATABASE']]

def get_package(name):
    try:
        return g.fs.get(name)
    except NoFile, e:
        raise NotFound('Package not found')

def compressed(f):
    @wraps(f)
    def decorated(*args, **kwargs):
        d = f(*args, **kwargs)
Example #12
0
# -*- coding: utf-8 -*-
from __future__ import print_function, division, absolute_import, unicode_literals

import os

from flask import Flask, render_template, jsonify, request

from gramophone import db, explore


app = Flask(__name__)


app.config['PROJECT_ROOT'] = os.path.dirname(os.path.abspath(__file__))
app.config['MUSIC_PATH'] = os.environ.get('MUSIC_PATH', os.path.dirname('static/music/'))
app.config['DATABASE'] = os.path.join(app.config.get('PROJECT_ROOT'), 'metadata.db')


app.register_blueprint(db.blueprint)


### VIEWS ###

@app.route('/')
def index():
    return render_template('index.html')


@app.route('/update_db/')
def update_db():
    tracks = explore.explore_collection(app.config['MUSIC_PATH'])
            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"""
Example #14
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
    f_in = gzip.open(app.config['DATABASE']+'.gz', 'rb')
    f_out = open(app.config['DATABASE'], 'wb')
Example #15
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 #16
0
import os
from flask import Flask
from flask import g
from flask import jsonify
import psycopg2
import json
from json import load
from flask import render_template
app = Flask(__name__)

app.config['DATABASE'] = os.environ.get(
	'DATABASE_URL', ''
	)

app.config['SECRET_KEY'] = os.environ.get(
	'FLASK_SECRET_KEY', '892BEF232E4A81DA955BA79D42E9D'
	)

table_labels = [
    # "Universal Stock Symbol",
    # "Current Price",
    # "Num Change",
    # "% Change",
    "Universal Stock Symbol",
    "Date Time Gathered",
    "Market Cap (intraday)",
    "Enterprise Value",
    "Trailing P/E (ttm, intraday)",
    "PEG Ratio (5 yr expected)",
    "Profit Margin (ttm)",
    "Revenue (ttm)",
Example #17
0
import sqlite3
from flask import Flask


# Initialize the Flask application
app = Flask(__name__)
app.config['DATABASE'] = '/db/payserv.db'


# Database code
def connect_db():
    return sqlite3.connect(app.config['DATABASE'])


# Routes
@app.route('/')
def index():
    return "Hello World"


# Run application
if __name__ == '__main__':
    # Run the Flask app
    app.run(
        host="0.0.0.0",
        port=int("5000"),
        debug=True
    )
import datetime
import model
from contextlib import closing
import psycopg2
import default_images
from default_images import sorry_image


app = Flask(__name__)

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

app.config['DATABASE'] = os.environ.get(
    'DATABASE_URL', 'dbname=telephone_db user=store'
)


def connect_db():
    """Return a connection to the configured database"""
    if 'DATABASE' not in app.config:
        app.config['DATABASE'] = os.environ.get(
            'DATABASE_URL', 'dbname=telephone_db user=store')
    return psycopg2.connect(app.config['DATABASE'])


def init_db():
    """Initialize the database.
    WARNING: This will drop existsing tables"""
    with closing(connect_db()) as db:
Example #19
0
from flask.ext.migrate import Migrate, MigrateCommand
from flask_restful import Api
from flask_marshmallow import Marshmallow
from mixer.backend.flask import mixer
from flask_wiki.backend.models import db
# TODO: Verify URL prefix implementation if debug is true.
# TODO: Verify Migrate Support.

PROJECT_ROOT_PATH = os.path.dirname(os.path.realpath(__file__))

app = Flask(__name__)
app.config['TESTING'] = True
app.config['BOOTSTRAP'] = True


app.config['DATABASE'] = 'wiki.db'
db_url = 'sqlite:////%s/%s' % (PROJECT_ROOT_PATH, app.config.get('DATABASE'))
app.config['SQLALCHEMY_DATABASE_URI'] = db_url


# Database Configuration
# Use test_request_context is some kind of sorcery, but works?!
if app.config['BOOTSTRAP'] is True:
    with app.test_request_context():
        db.init_app(app)
        db.create_all()
else:
    db.init_app(app)

api = Api(app)
marsh = Marshmallow(app)
Example #20
0
    my_config = NestConfig(config=CONFIG_FILE)
    config = my_config.load_config()
else:
    sys.exit("No configuration found. Run PyNestAdmin.py --configure")

if config['nest_web']['ssl_crt'] and config['nest_web']['ssl_key']:
    ssl_enabled = True
else:
    ssl_enabled = False

app = Flask(__name__)
Bootstrap(app)

app.config['USERNAME'] = config['nest_web']['admin_user']
app.config['PASSWORD'] = config['nest_web']['admin_pass']
app.config['DATABASE'] = os.path.join('nest_data.db')
app.config['SECRET_KEY'] = uuid.uuid4().hex


# Forms
class OptionsForm(Form):
    nest_username = StringField('Nest Username', validators=[DataRequired()])
    nest_password = PasswordField('Nest Password', validators=[DataRequired()])
    admin_user = StringField('PyNestAdmin Username', validators=[DataRequired()])
    admin_pass = PasswordField('PyNestAdmin Password', validators=[DataRequired()])
    port = StringField('PyNestAdmin Port', validators=[DataRequired()])
    ip = StringField('PyNestAdmin Listen IP', validators=[DataRequired()])
    api_key = StringField('PyNestAdmin API Key', validators=[DataRequired()])

# Web facing routes
@app.route("/")
Example #21
0
DB_EDIT_ENTRY = """
SELECT id, title, text, created FROM entries WHERE id = %s
"""

DB_UPDATE_ENTRY = """
UPDATE entries
SET title=%s, text=%s
WHERE id=%s;
"""

app = Flask(__name__)


# letting application know about how to connect db
app.config['DATABASE'] = os.environ.get(
    'DATABASE_URL', 'dbname=learning_journal user=muazzezmira'
)


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'
)

sh.setFormatter(frmtr)
log.addHandler(fh)
log.addHandler(sh)

#oauth props init
props_filename = os.path.join(curr_path, 'oauth_properties.json')
props = json.loads(open(props_filename, 'r').read())
GOOGLE_CLIENT_ID = props['google']['client_id']
TTR_CONSUMER_KEY = props['twitter']['consumer_key']
TTR_CONSUMER_SECRET = props['twitter']['consumer_secret']
TTR_CALLBACK_URL = props['twitter']['callback_url']

#flask init
app = Flask(__name__, static_folder='static', static_url_path='')
app.config['SECRET_KEY'] = 'FUCKING_SECRET_KEY_FUCKING_FUCKING_FUCKING!!!'
app.config['DATABASE'] = os.path.join(curr_path, 'db/database.db')

#identities source
t_identities_source_path = os.path.join(curr_path, 't_identities.csv')
g_identities_source_path = os.path.join(curr_path, 'g_identities.csv')


def load_interested_identities(source_google, source_twitter, sep=';'):
    """
    source must be file like object with some separator like
    """
    google_objects = source_google.read()
    google_objects = [el.strip() for el in google_objects.split(sep) if len(el)]

    twitter_objects = source_twitter.read()
    twitter_objects = [el.strip() for el in twitter_objects.split(sep) if len(el)]
Example #23
0
from bokeh.plotting import figure
from bokeh.resources import INLINE
from bokeh.util.string import encode_utf8

from hackrtrackr.helpers import COLORS, get_matching_comments, make_fig

# from helpers import COLORS, get_matching_comments, make_fig
from hackrtrackr import settings
import logging
import datetime

app = Flask(__name__)

# Configure the app
app.debug = settings.DEBUG
app.config['DATABASE'] = (0, settings.DATABASE_NAME)

# Make a custom logger so we don't log every GET request
logger = logging.getLogger('hn_logger')
logger.setLevel(logging.DEBUG)
fh = logging.FileHandler('queries.log')
fh.setLevel(logging.DEBUG)
formatter = logging.Formatter("%(asctime)s %(levelname)s %(module)s: %(message)s")
fh.setFormatter(formatter)
logger.addHandler(fh)
#LOGGING_FORMAT = "%(asctime)s %(levelname)s %(module)s: %(message)s"
# set to warning to avoid all the _internal logs about eac
#logging.basicConfig(format=LOGGING_FORMAT, filename='queries.log', level=logging.WARNING)

def connect_db(db_name):
    # Connect to the database
Example #24
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 #25
0
import os
from werkzeug.routing import BaseConverter
from werkzeug.contrib.cache import SimpleCache

DATABASE = {
    'name': os.environ['DB_NAME'],
    'host': os.environ['DB_HOST'],
    'engine': 'peewee.MySQLDatabase',
    'user': os.environ['DB_USER'],
    'passwd': os.environ['DB_PASS'],
}


app = Flask(__name__)
# app.config['DEBUG'] = False
app.config['DATABASE'] = DATABASE
app.config['SECRET_KEY'] = os.environ['SECRET_KEY']
if os.environ.get('DEBUG', '') == 'DEBUG':
    app.config['DEBUG'] = True
else:
    app.config['DEBUG'] = False

db = Database(app)
cache = SimpleCache()


# source http://stackoverflow.com/questions/5870188/does-flask-support-regular-expressions-in-its-url-routing
class RegexConverter(BaseConverter):
    def __init__(self, url_map, *items):
        super(RegexConverter, self).__init__(url_map)
        self.regex = items[0]
Example #26
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>')
def superecho(word):
    return render_template('superecho.html', word=word)
from flask import Flask, request, Response, render_template, session
from werkzeug import ImmutableDict

import os # environ
import flask

app = Flask(__name__)
app.jinja_env.add_extension('pyjade.ext.jinja.PyJadeExtension')

app.secret_key = 'ENTER RANDOM STUFF HERE'
app.debug=True # Works in uwsgi environment

# See http://docs.sqlalchemy.org/ru/latest/dialects/sqlite.html#connect-strings
app.config['DATABASE'] = os.environ.get("FLASK_DB", 'sqlite:///sqlite_hackathon.db') # Relative URL
# 'sqlite:////home/USERNAME/hackathon-starter-flask-plus/backend/flask/sqlite_hackathon.db' # Absolute URL

app.config['SENDMAIL'] = os.environ.get("FLASK_MAIL", False)
app.config['SENDMAIL_FILE'] = os.environ.get("FLASK_MAIL_FILE", 'mime_message.txt')

app.debug = os.environ.get("FLASK_DEBUG", False)

# Pull in routes
import www.main
import www.auth
import www.admin

import www.database as db

@app.teardown_request
def shutdown_session(exception=None):
    db.session.remove()
Example #28
0
import os, datetime, codecs, random, string, json, re, time, sqlite3, shutil
from flask import Flask, render_template, request, url_for, abort, redirect, send_from_directory, g, Response, escape
from werkzeug import secure_filename
from functools import wraps
import email.parser, smtplib
from validate_email import validate_email

####################### config
UPLOAD_FOLDER = os.path.abspath(os.path.join(os.path.split(__file__)[0], "uploads"))
ALLOWED_EXTENSIONS = set(['click'])

####################### app config
app = Flask(__name__)
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
app.config['PROPAGATE_EXCEPTIONS'] = True
app.config['DATABASE'] = os.path.join(os.path.split(__file__)[0], "requests.db")

fp = open("claim_secret") # this needs to exist. Put many long random strings in it, one per worker
app.config["CLAIM_SECRETS"] = [x.strip() for x in fp.readlines()]
fp.close()

def get_db():
    db = getattr(g, '_database', None)
    if db is None:
        db = g._database = sqlite3.connect(app.config['DATABASE'])
        crs = db.cursor()
        init_db(db, crs)
    else:
        crs = db.cursor()
    return db, crs
Example #29
0
#-*- coding: utf-8 -*-
import re
import sqlite3

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

app = Flask(__name__)

app.config['DATABASE'] = './test.db'
app.secret_key = 'reminder'

def connect_db():
	rv = sqlite3.connect(app.config['DATABASE'])
	rv.row_factory = sqlite3.Row
	return rv

def get_db():
	if not hasattr(g,'sqlite_db'):
		g.sqlite_db = connect_db()
	return g.sqlite_db

def close_db():
	if hasattr(g,'sqlite_db'):
		g.sqlite_db.close() 

def init_db():
	with app.app_context():
		db = get_db()
		with app.open_resource('schema.sql', mode='r') as f:
			db.cursor().executescript(f.read())
		db.commit()
Example #30
0
File: app.py Project: dz0ny/lxcapi
from flask import Flask
from flask.ext.restful import Api
from lxcapi.lxcapi.users import User, Users

app = Flask(__name__)
app.config['DEBUG'] = True
app.config['SECRET_KEY'] = 'super-secret'
app.config['DATABASE'] = {
    'name': 'example.db',
    'engine': 'peewee.SqliteDatabase',
}

# remote api
api = Api(app, prefix='/v1', catch_all_404s=True)
api.add_resource(Users, '/users')
api.add_resource(User, '/users/<string:user_id>')

if __name__ == '__main__':
    app.run(debug=True)