Example #1
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 #2
0
def create_app(name=None, config=None):
    """Create the Flask application."""
    name = 'invenio_kwalitee' if name is None else name
    app = Flask(name, template_folder="templates", static_folder="static",
                instance_relative_config=True)

    # Load default configuration
    app.config.from_object("invenio_kwalitee.config")

    # Load invenio_kwalitee.cfg from instance folder
    app.config.from_pyfile("invenio_kwalitee.cfg", silent=True)
    app.config.from_envvar("INVENIO_KWALITEE_CONFIG", silent=True)
    app.config.update(config or {})

    # Create instance path
    if not os.path.exists(app.instance_path):
        os.makedirs(app.instance_path)

    # Setting up the database
    database = os.path.join(app.instance_path,
                            app.config.get("DATABASE_NAME", "database"))
    database = "{0}.db".format(database)
    app.config["DATABASE"] = database
    app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:///{0}".format(database)
    from .models import db, init_app
    init_app(app)
    if not os.path.exists(database):
        db.create_all()

    # Setting up RQ
    from .worker import init_app
    init_app(app)

    # Setting up the views
    app.url_map.converters['sha'] = ShaConverter
    from . import views
    app.add_url_rule("/", "index", views.index, methods=["GET"])
    app.add_url_rule("/<account>/", "account", views.account, methods=["GET"])
    app.add_url_rule("/<account>/<repository>/", "repository", views.repository,
                     methods=["GET"])
    app.add_url_rule("/<account>/<repository>/commits/<sha:sha>/", "commit",
                     views.commit, methods=["GET"])
    app.add_url_rule("/<account>/<repository>/branches/<sha:sha>/<path:branch>",
                     "branch_status", views.branch_status, methods=["GET"])
    app.add_url_rule("/<account>/<repository>/branches/<path:branch>", "branch",
                     views.branch, methods=["GET"])
    app.add_url_rule("/payload", "payload", views.payload, methods=["POST"])
    # legacy
    app.add_url_rule("/status/<sha>", "status", views.status, methods=["GET"])

    if app.debug:
        from werkzeug.debug import DebuggedApplication
        app.wsgi_app = DebuggedApplication(app.wsgi_app, evalex=True)

    return app
Example #3
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 #4
0
from UploadHandler import UploadHandler
from PlayHandler import PlayHandler
import json
import eyed3
import sqlite3
from werkzeug import secure_filename
import threading
from visualizer import AudioParser
import os

app = Flask(__name__)
app.secret_key = 'this is the secret key'
PROJECT_ROOT = os.path.dirname(os.path.realpath(__file__))
DATABASE = os.path.join(PROJECT_ROOT, 'equairizer.db')
UPLOAD_FOLDER = os.path.join(PROJECT_ROOT, 'songs')
app.config["DATABASE"] = DATABASE
app.config["UPLOAD_FOLDER"] = UPLOAD_FOLDER
uh = UploadHandler()

ph = PlayHandler()

player = None
stop_event = threading.Event()


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


@app.before_request
def before_request():
Example #5
0
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 #6
0
from flask import Flask, render_template, request, session
from flask import flash, redirect, url_for, g
import sqlite3
from functools import wraps

# configuration

app = Flask(__name__)
app.config.from_object(__name__)
app.config["DATABASE"] = "blog.db"
app.config["USERNAME"] = "admin"
app.config["PASSWORD"] = "admin"
app.config["SECRET_KEY"]="hard_to_guess"

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

def login_required(test):
	@wraps(test)
	def wrap(*args, **kwargs):
		if 'logged_in' in session:
			return test(*args, **kwargs)
		else:
			flash('You need to login first.')
			return redirect(url_for('login'))
	return wrap

@app.route('/',methods=["GET","POST"])
def login():
	error=None
	print app.config["USERNAME"]
Example #7
0
    )
    return parser


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
Example #8
0
import os
import sys
import threading
from flask import (Flask, render_template, jsonify, request,
                   send_from_directory, redirect, url_for, flash)
from flask_socketio import SocketIO
from datetime import datetime
import numpy as np

from .database import database, Post, get_rnd_db_entries, get_max_id
from .image import fix_orientation


app = Flask(__name__)
app.secret_key = "DONTTELLANYONETHESECRETKEY"
app.config["DATABASE"] = os.getenv("SLIDESHOW_DB", "slideshow.sqlite")
app.config["IMG_DIR"] = os.getenv("SLIDESHOW_IMG_DIR",
                                  os.path.join(os.getenv("HOME"),
                                               "Pictures", "wedding"))


# Init app before launch
@app.before_first_request
def init_app():
    # Images are saved as posted and cropped with fixed ratios later
    os.makedirs(os.path.join(app.config["IMG_DIR"], 'original'), exist_ok=True)
    os.makedirs(os.path.join(app.config["IMG_DIR"], 'small'), exist_ok=True)
    os.makedirs(os.path.join(app.config["IMG_DIR"], 'large'), exist_ok=True)
    # Setup database
    database.init(app.config["DATABASE"])
    database.create_tables([Post], safe=True)
Example #9
0
__version__ = "0.4.0"

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


api = Api(app)
init_admin(app)

# configure our database
settings.DATABASE_CONFIG.update({"threadlocals": True})
app.config["DATABASE"] = settings.DATABASE_CONFIG
db.init_app(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


from redash import controllers
Example #10
0
            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():
    """logs out a logged in user."""
    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
from flask import Flask
from flask.ext.cache import Cache

app = Flask(__name__)
app.config['CACHE_TYPE'] = 'simple'
app.cache = Cache(app)

app.config["DATABASE"] = 'names.db'
app.config['DEBUG'] = True
app.config["SECRET_KEY"] = "restful web services kpmg"
app.config["USERNAME"] = "Carlo"
app.config["PASSWORD"] = "Butelli"

from app import views, modules
Example #12
0
    return jsonify(g.counter)

@app.errorhandler(jsonpointer.JsonPointerException)
def handle_json_pointer_exception(error):
    return jsonify(error=str(error)), 400


def errors_to_json(error: werkzeug.exceptions.HTTPException):
    return jsonify(error=str(error.description)), error.code

def register_error_handlers():
    for class_name in dir(werkzeug.exceptions):
        klass = getattr(werkzeug.exceptions, class_name)
        try:
            if issubclass(klass, werkzeug.exceptions.HTTPException):
                app.register_error_handler(klass, errors_to_json)
        except TypeError:
            pass

@app.after_request
def add_headers(response: Response):
    if "etag" in g:
        response.set_etag(g.etag)
    return response

register_error_handlers()

if __name__ == "__main__":
    app.config["DATABASE"] = Database(CONFIG)
    app.run()
Example #13
0
from flask import Flask, request, Response, abort, g
from flask.ext.api import status
from jsonschema.exceptions import ValidationError
from tables import *
from user import User
import json
import jsonschema
import os
import sqlite3

app = Flask(__name__)
app.config["DATABASE"] = os.getenv('DATABASE', "planet.db")

def success(code = status.HTTP_200_OK, response = ""):
    """
    note, if response is an object it should be serialized
    to a string before calling this
    """
    return (response, code)

def error(code, error_text = ""):
    return (json.dumps({'error': error_text}), code)

@app.before_request
def before_request():
    """
    before each request, create a thread local connection to the
    on-disk sqlite database
    """
    if not hasattr(g, 'connection'):
        g.connection = sqlite3.connect(app.config["DATABASE"])
Example #14
0
from flask import Flask
from flask_googlemaps import GoogleMaps, Map

app = Flask(__name__)
GoogleMaps(app)
app.config["DATABASE"] = 'mydb.db'


from app import views,models
Example #15
0
#coding:utf8
from flask import Flask,request,sessions,g,redirect,url_for,abort,render_template,flash
import os
import sqlite3
from contextlib import closing
DATABASE='/schema.sqlite'
DEBUG=True
SECRET_KEY='123456'
USERNAME='admin'
PASSWORD='p@ssw0rd'
app = Flask(__name__)
app.config["DATABASE"]=os.path.join(app.root_path,'schema.sqlite')
@app.route('/')
def show_entries():
    cur = g.db.execute('select title,text from entries order by id desc')
    entries = [dict(title=row[0],text=row[1]) for row in cur.fetchall()]
    return render_template('show_entries.html',entries = entries)
    # return 'Hello World!'
@app.route('/add',methods=['POST'])
def add_entry():
    if not sessions.get('logged_in'):
        abort(401)
    g.db.execute('insert into entries (title,text) values (?,?)',[request.form['title'],request.form['text']])
    g.db.commit()
    flash('New entry was successfull posted')
    return redirect(url_for('show_entries'))
@app.route('/login',methods=['GET','POST'])
def login():
    error=None
    # return redirect(url_for('show_entries'))
    if request.method == 'POST':
from functools import wraps
import os
import werkzeug
import sqlite3

from flask import Flask, render_template, request, session, redirect, flash, url_for, _app_ctx_stack
from werkzeug.security import check_password_hash, generate_password_hash

app = Flask(__name__)
app.secret_key = "Development Key"

app.config["DATABASE"] = "data.db"
app.config["UPLOAD_FOLDER"] = "static/uploads"

ALLOWED_EXTENSIONS = set(['mp3'])


def sanitize_song_title(song):
    new_song = song.strip("'")
    return new_song.replace(" ", "_")


def retrieve_user_info(username):
    return query_db("SELECT * FROM user_data WHERE username=?", [username], one=True)


def get_db():
    """Opens a new database connection if there is none yet for the current application context."""
    top = _app_ctx_stack.top
    if not hasattr(top, 'sqlite_db'):
        top.sqlite_db = sqlite3.connect(app.config["DATABASE"])
Example #17
0
from rui.series.model import User
from rui.series.model import Serie
from rui.series.model import Fansub
from rui.series.model import ScrapParam
from rui.series.model import ScrapParamTemplate
from rui.series.model import Notification
from rui.series.model import db

from rui.config import data as dataConfig

from rui.series.resources import NotificationResource

# Define the WSGI application object
app = Flask(__name__)
app.config["DATABASE"] = {"name": dataConfig["path"], "engine": "peewee.SqliteDatabase"}
app.config["SECRET_KEY"] = '?\xbf,\xb4\x8d\xa3"<\x9c\xb0@\x0f5\xab,w\xee\x8d$0\x13\x8b83'
# instantiate our api wrapper
api = RestAPI(app)

# Admin area


db = Database(app)

# needed for authentication
auth = Auth(app, db)
# auth.User.create_table(fail_silently=True)

demo = auth.User(username="demo", email="", admin=True, active=True)
demo.set_password("sonata")
Example #18
0
from flask import Flask
from flask.ext.sqlalchemy import SQLAlchemy

app = Flask(__name__)

app.config["DATABASE"] = 'database.db'
db = SQLAlchemy(app)

class User(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(80), unique=True)

    def __init__(self,name):
        self.name = name

    def __repr__(self):
        return '<User %r>' % self.name

from flask import Flask, abort, render_template, make_response, request, redirect, url_for
from flask.ext.login import LoginManager, UserMixin, login_required, login_user, logout_user, current_user
from playhouse.flask_utils import FlaskDB
from peewee import CharField, DateField
from authomatic import Authomatic
from authomatic.adapters import WerkzeugAdapter
import config

# Configure the Flask application instance.
app = Flask(__name__)
app.config["DATABASE"]   = config.database
app.config["SECRET_KEY"] = config.flask_secret

# http://peewee.readthedocs.org/en/latest/peewee/playhouse.html#flask-utils
database = FlaskDB(app)

# http://flask-login.readthedocs.org/en/latest/#flask.ext.login.LoginManager
login_manager = LoginManager()
login_manager.init_app(app)

# http://peterhudec.github.io/authomatic/reference/classes.html#authomatic.Authomatic
authomatic = Authomatic(config.authomatic_config, config.authomatic_secret)

# Super quick user model with peewee
class User(UserMixin, database.Model):
    auth_provider = CharField()
    auth_id = CharField()
    name = CharField(null=True)

@login_manager.user_loader
def load_user(uid):