Beispiel #1
1
def create_app(config, debug=True):
    app = Flask(__name__)
    app.debug = debug
    app.config["SECRET_KEY"] = "secret"
    app.config["SECURITY_POST_LOGIN_VIEW"] = "/profile"
    app.config.from_object(Config)

    if config:
        for key, value in config.items():
            app.config[key] = value

    app.wsgi_app = HTTPMethodOverrideMiddleware(app.wsgi_app)

    @app.route("/")
    def index():
        return render_template("index.html", content="Home Page")

    @app.route("/profile")
    @login_required
    def profile():
        twitter = current_app.social.twitter
        twitter.get_api()

        return render_template(
            "profile.html",
            content="Profile Page",
            twitter_conn=twitter.get_connection(),
            google_conn=current_app.social.google.get_connection(),
            facebook_conn=current_app.social.facebook.get_connection(),
            foursquare_conn=current_app.social.foursquare.get_connection(),
        )

    return app
Beispiel #2
1
def create_app():
    options = {"port": 0, "unitTesting": False}
    WebConfig.config(options)

    b = Borg()
    app = Flask(__name__)
    app.config["DEBUG"] = True
    app.config["SECRET_KEY"] = b.secretKey
    app.config["SECURITY_PASSWORD_HASH"] = b.passwordHash
    app.config["SECURITY_PASSWORD_SALT"] = b.passwordSalt
    app.config["SQLALCHEMY_DATABASE_URI"] = (
        "mysql://" + b.auth_dbUser + ":" + b.auth_dbPasswd + "@" + b.auth_dbHost + "/" + b.auth_dbName
    )
    b.logger.setLevel(b.logLevel)
    b.logger.debug("Error handlers: {0}".format(app.error_handler_spec))
    app.secret_key = os.urandom(24)
    logger = logging.getLogger("werkzeug")
    logger.setLevel(b.logLevel)
    enable_debug = b.logLevel = logging.DEBUG

    cors = CORS(app)
    db.init_app(app)
    user_datastore = SQLAlchemyUserDatastore(db, User, Role)
    security = Security(app, user_datastore)

    from main import main as main_blueprint

    app.register_blueprint(main_blueprint)

    with app.app_context():
        db.create_all()

    return app
Beispiel #3
1
def run_flask():
    root_dir = os.path.join(os.getcwd(), "web")
    app = Flask(__name__, static_folder=root_dir)
    app.use_reloader = False
    app.debug = False
    app.config["SECRET_KEY"] = "OpenPoGoBot"
    socketio = SocketIO(app, logging=False, engineio_logger=False)

    logging_buffer = []

    @app.route("/")
    def index():
        return app.send_static_file("index.html")

    @app.route("/<path:path>")
    def static_proxy(path):
        return app.send_static_file(path)

    @manager.on("logging")
    def logging_event(event_name, output, color):
        line = {"output": output, "color": color}
        logging_buffer.append(line)
        socketio.emit("logging", [line], namespace="/event")

    @socketio.on("connect", namespace="/event")
    def connect():
        emit("logging", logging_buffer, namespace="/event")
        logger.log("Client connected", "yellow", fire_event=False)

    @socketio.on("disconnect", namespace="/event")
    def disconnect():
        logger.log("Client disconnected", "yellow", fire_event=False)

    socketio.run(app, host="0.0.0.0", port=8000, debug=False, use_reloader=False, log_output=False)
Beispiel #4
0
def get_app():
    app = Flask(__name__)
    app.config.from_object("midgardsormr.conf.common")

    app.config["SECRET_KEY"] = SESSION_KEY

    db.init_app(app)

    # blueprints
    app.register_blueprint(index.blueprint, url_prefix="/")
    app.register_blueprint(auth.blueprint, url_prefix="/auth")

    @app.context_processor
    def inject_statics():
        root = request.script_root
        return {"static_prefix": root + app.static_url_path}

    @app.before_request
    def _before_request():
        if session.get("logged_in") or request.path in NO_AUTH_PATH:
            print session.get("logged_in")
            print request.path
            return
        return redirect(url_for("auth.login"))

    return app
Beispiel #5
0
    def setUp(self):
        """Creates the Flask application and the APIManager."""
        # create the Flask application
        app = Flask(__name__)
        app.config["DEBUG"] = True
        app.config["TESTING"] = True
        app.config["SECRET_KEY"] = "testing..."
        del app.logger.handlers[0]
        # sqlalchemy flask
        self.base = declarative_base()
        self.engine = create_engine("sqlite://")
        self.session = scoped_session(sessionmaker(autocommit=False, autoflush=False, bind=self.engine))
        self.app = app
        self._ctx = self.app.test_request_context()
        self._ctx.push()
        self.client = self.app.test_client()

        # Add an error handler that returns straight LeverException
        # recommendations
        @self.app.errorhandler(LeverException)
        def handler(exc):
            tb = exc.extra.pop("tb", None)
            self.app.logger.debug(
                "Lever Exception Thrown!\n" "Extra: {0}\nEnd User: {1}".format(exc.extra, exc.end_user), exc_info=True
            )
            if tb:
                self.app.logger.debug("Traceback from lever exception:" "\n{0}".format(tb.replace("\\n", "\n")))
            return jsonify(**exc.end_user), exc.code

        return app
Beispiel #6
0
def create():
    """Create application.
    """

    # Create application
    app = Flask("service", static_folder=None)
    app.config["DEBUG"] = True

    # CORS support
    CORS(app)

    # Session
    sess = Session()
    app.config["SESSION_TYPE"] = "filesystem"
    app.config["SECRET_KEY"] = "openspending rocks"
    sess.init_app(app)

    # Register blueprints
    print("Creating Datastore Blueprint")
    app.register_blueprint(datastore.create(), url_prefix="/datastore")
    print("Creating API Loader Blueprint")
    app.register_blueprint(apiload.create(), url_prefix="/hooks/load/")
    print("Creating Authentication Blueprint")
    app.register_blueprint(authentication.create(), url_prefix="/oauth/")
    print("Creating Authorization Blueprint")
    app.register_blueprint(authorization.create(), url_prefix="/permit/")
    print("Creating Search Blueprint")
    app.register_blueprint(search.create(), url_prefix="/search/")

    # Return application
    return app
Beispiel #7
0
def create_app(config_filename=""):
    logging.info("Spike app.init()")

    app = Flask(__name__)

    if config_filename:
        app.config.from_pyfile(config_filename)

    if not app.config["SECRET_KEY"]:
        app.config["SECRET_KEY"] = base64.b64encode(os.urandom(128))

    app.config["SQLALCHEMY_BINDS"] = {"rules": "sqlite:///rules.db"}

    db.init_app(app)
    db.app = app

    Bootstrap(app)  # add bootstrap templates and css

    # add blueprints
    app.register_blueprint(default.default)
    app.register_blueprint(rules.rules, url_prefix="/rules")
    app.register_blueprint(rulesets.rulesets, url_prefix="/rulesets")
    app.register_blueprint(sandbox.sandbox, url_prefix="/sandbox")
    app.register_blueprint(whitelists.whitelists, url_prefix="/whitelists")
    app.register_blueprint(whitelistsets.whitelistsets, url_prefix="/whitelistsets")

    # register filters
    app.jinja_env.globals["version"] = version

    return app
def create_app():
    app = Flask(__name__, static_folder=os.path.join(PROJECT_ROOT, "public"), static_url_path="/public")

    app.config.update(os.environ)

    # TODO: read in right hand side from HT config vars
    app.config["SECRET_KEY"] = "secret"
    app.config["SECURITY_PASSWORD_HASH"] = "bcrypt"
    app.config["MONGODB_DB"] = "flask_security_test"
    app.config["MONGODB_HOST"] = "localhost"
    app.config["MONGODB_PORT"] = 27017

    app.debug = app.config["X_HT_DEBUG"] == "True"

    app.wsgi_app = SharedDataMiddleware(app.wsgi_app, {"/": os.path.join(os.path.dirname(__file__), "public")})

    @app.errorhandler(404)
    def page_not_found(e):
        return render_template("404.html"), 404

    SecuritySetup(app)

    # import & register blueprints here:
    # ===================================
    from hero_tmpl.views.security import security

    app.register_blueprint(security)

    from hero_tmpl.views.misc import misc

    app.register_blueprint(misc)

    return app
Beispiel #9
0
def create_app(configfile=None):
    app = Flask(__name__)
    # AppConfig(app, configfile)  # Flask-Appconfig is not necessary, but
    # highly recommend =)
    # https://github.com/mbr/flask-appconfig
    Bootstrap(app)

    # in a real app, these should be configured through Flask-Appconfig
    app.config["SECRET_KEY"] = "devkeyqwerasdf"
    # app.config['RECAPTCHA_PUBLIC_KEY'] = '6Lfol9cSAAAAADAkodaYl9wvQCwBMr3qGR_PPHcw'

    @app.route("/", methods=("GET", "POST"))
    def index():
        if request.method == "POST":
            question = request.form["question"]
            print(question)
            answer = inquire.answer_question(question)
            return render_template("answer.html", answer=answer, question=question)

        form = ExampleForm()
        return render_template("index.html", form=form)

    # @app.route('/answer')
    # def answer():
    #     form

    return app
Beispiel #10
0
def app(jwt, user):
    app = Flask(__name__)
    app.debug = True
    app.config["SECRET_KEY"] = "super-secret"
    app.config["JWT_EXPIRATION_DELTA"] = timedelta(milliseconds=200)

    jwt.init_app(app)

    @jwt.authentication_handler
    def authenticate(username, password):
        if username == user.username and password == user.password:
            return user
        return None

    @jwt.user_handler
    def load_user(payload):
        if payload["user_id"] == user.id:
            return user

    @app.route("/protected")
    @flask_jwt.jwt_required()
    def protected():
        return "success"

    return app
Beispiel #11
0
def create_app(environ):
    app = Flask(__name__, static_url_path="/brigade/static")
    app.config["SECRET_KEY"] = "sekrit!"

    app.register_blueprint(brigade)
    app.register_blueprint(filters)
    return app
Beispiel #12
0
def create_app(database_connection):
    app = Flask("Distributed Cuckoo")
    app.config["SQLALCHEMY_DATABASE_URI"] = database_connection
    app.config["SECRET_KEY"] = os.urandom(32)

    for blueprint, routes in blueprints:
        for route in routes:
            app.register_blueprint(blueprint, url_prefix=route)

    db.init_app(app)
    db.create_all(app=app)

    # Check whether an alembic version is present and whether
    # we're up-to-date.
    with app.app_context():
        row = AlembicVersion.query.first()
        if not row:
            db.session.add(AlembicVersion(AlembicVersion.VERSION))
            db.session.commit()
        elif row.version_num != AlembicVersion.VERSION:
            sys.exit(
                "Your database is not up-to-date. Please upgrade it " "using alembic (run `alembic upgrade head`)."
            )

    return app
Beispiel #13
0
    def create_app():

        global db, bootstrap, mail, login_manager, moment, pagedown
        app = Flask(__name__)

        from main import main as main_blueprint
        from auth import auth as auth_blueprint
        from admin import admin as admin_blueprint

        app.config["SQLALCHEMY_DATABASE_URI"] = "mysql://flask:gf37888676@172.17.0.25/flask"
        app.config["SQLAlCHEMY_COMMIT_ON_TEARDOWN"] = True
        app.config["FLASK_ADMIN"] = "iamawar3player@163.com"
        app.config["FLASK_MAIL_SUBJECT_PREFIX"] = "[Flasky]"
        app.config["FLASK_MAIL_SENDER"] = "Flasky Admin <iamawar3player@163.com>"
        app.config["MAIL_SERVER"] = "smtp.163.com"
        app.config["MAIL_PORT"] = 25
        app.config["MAIL_USE_TLS"] = False
        app.config["MAIL_USERNAME"] = "iamawar3player@163.com"
        app.config["MAIL_PASSWORD"] = "fan86797121"
        app.config["DEBUG"] = True
        app.config["FLASKY_POSTS_PER_PAGE"] = 10
        app.config["SECRET_KEY"] = "gf37888676"
        app.register_blueprint(main_blueprint)
        app.register_blueprint(auth_blueprint, url_prefix="/auth")
        app.register_blueprint(admin_blueprint, url_prefix="/admin")

        db = db.init_app(app)
        mail = mail.init_app(app)
        bootstrap = bootstrap.init_app(app)
        login_manager = login_manager.init_app(app)
        moment = moment.init_app(app)
        pagedown = pagedown.init_app(app)

        return app
def create_app(configfile=None):
    app = Flask(__name__)
    AppConfig(app, configfile)  # Flask-Appconfig is not necessary, but
    # highly recommend =)
    # https://github.com/mbr/flask-appconfig
    Bootstrap(app)

    # in a real app, these should be configured through Flask-Appconfig
    app.config["SECRET_KEY"] = "devkey"
    app.config["RECAPTCHA_PUBLIC_KEY"] = "6Lfol9cSAAAAADAkodaYl9wvQCwBMr3qGR_PPHcw"

    @app.route("/", methods=("GET", "POST"))
    def index():
        form = ExampleForm()
        form.validate_on_submit()  # to get error messages to the browser
        flash("critical message", "critical")
        flash("error message", "error")
        flash("warning message", "warning")
        flash("info message", "info")
        flash("debug message", "debug")
        flash("different message", "different")
        flash("uncategorized message")
        return render_template("index.html", form=form)

    return app
Beispiel #15
0
def create():
    """Create application.
    """

    # Create application
    app = Flask("service", static_folder=None)
    app.config["DEBUG"] = True

    # CORS support
    CORS(app)

    # Session
    sess = Session()
    app.config["SESSION_TYPE"] = "filesystem"
    app.config["SECRET_KEY"] = "openspending rocks"
    sess.init_app(app)

    # Register blueprints
    logger.info("Creating Datastore Blueprint")
    app.register_blueprint(datastore.create(), url_prefix="/datastore/")
    logger.info("Creating Package Blueprint")
    app.register_blueprint(package.create(), url_prefix="/package/")
    logger.info("Creating Authentication Blueprint")
    app.register_blueprint(user.oauth_create(), url_prefix="/oauth/")
    logger.info("Creating Users Blueprint")
    app.register_blueprint(user.create(), url_prefix="/user/")
    logger.info("Creating Search Blueprint")
    app.register_blueprint(search.create(), url_prefix="/search/")

    # Return application
    return app
Beispiel #16
0
def setup():
    app = Flask(__name__)
    app.config["SECRET_KEY"] = "1"
    app.config["CSRF_ENABLED"] = False
    admin = Admin(app)

    return app, admin
Beispiel #17
0
def create_app():

    app = Flask(__name__)

    """
        Adicionado apenas por causa do redirect que o login_manager
        faz, e caso não tenha uma SECRET_KEY, poderá não funcionar.
    """
    app.config["SECRET_KEY"] = "dificil de advinhar que era isso"

    """
        Inicializando as extensões da aplicação.
        Descobri que o "factory" da aplicação é nada mais, nada 
        menos que esse método (create_app). :D
    """
    login_manager.init_app(app)
    db.init_app(app)

    """
        Importando o blueprint para registrá-lo na aplicação.
        O url_prefix é opcional, mas se definido fará com que 
        os urls do blueprint, tenham um prefixo.
    """
    from .auth import auth as auth_blueprint

    app.register_blueprint(auth_blueprint, url_prefix="/auth")

    # LINHAS DESCARTÁVEIS
    from .main import main as main_blueprint

    app.register_blueprint(main_blueprint)
    # app.debug = True

    return app
Beispiel #18
0
def create_app(app_state):
    app = Flask(__name__)
    app.debug = True

    if getattr(sys, "frozen", None):
        # set root_path to data dir from PyInstaller
        basedir = sys._MEIPASS
        app.root_path = os.path.join(basedir, os.path.join(*__name__.split(".")))

    app.config.geobox_state = app_state

    app.config["SECRET_KEY"] = app_state.config.get("web", "secret_key")

    from . import views

    app.register_blueprint(views.main)
    app.register_blueprint(views.editor)
    app.register_blueprint(views.tasks)
    app.register_blueprint(views.project)
    app.register_blueprint(views.admin)
    app.register_blueprint(views.vector)
    app.register_blueprint(views.downloads)
    app.register_blueprint(views.proxy)
    app.register_blueprint(views.boxes)
    app.register_blueprint(views.raster)

    @app.before_request
    def before_request():
        g.db = app_state.user_db_session()
        if request_for_static():
            return

        gbi_server = g.db.query(GBIServer).all()

        if len(gbi_server) == 0 and request.endpoint not in (
            "admin.initial_set_server",
            "admin.set_server",
            "admin.add_server",
        ):
            return redirect(url_for("admin.initial_set_server"))

    @app.teardown_request
    def teardown_request(exception):
        """Closes the database again at the end of the request."""
        if hasattr(g, "db"):
            g.db.close()

    from .helper import css_alert_category, add_auth_to_url
    import geobox.app

    app.jinja_env.globals.update(
        css_alert_category=css_alert_category,
        add_auth_to_url=add_auth_to_url,
        app_state=app_state,
        geobox_client_version=geobox.app.version,
    )

    configure_i18n(app, app_state.locale())
    configure_errorhandlers(app)
    return app
Beispiel #19
0
def start_server(args):
    app = Flask(__name__)
    app.config["SECRET_KEY"] = "secret"
    app.jinja_env.globals["static"] = static

    blueprint.url_prefix = args.url_prefix
    app.register_blueprint(blueprint)

    # app.run(port=args.port, debug=args.debug)

    wsgi_app = tornado.wsgi.WSGIContainer(app)
    condajs_ws = sockjs.tornado.SockJSRouter(views.CondaJsWebSocketRouter, "/condajs_ws")
    routes = condajs_ws.urls
    routes.append((r".*", tornado.web.FallbackHandler, dict(fallback=wsgi_app)))
    application = tornado.web.Application(routes, debug=args.debug)

    try:
        application.listen(args.port)
    except OSError as e:
        print("There was an error starting the server:")
        print(e)
        return

    ioloop = tornado.ioloop.IOLoop.instance()
    if not args.debug:
        callback = lambda: webbrowser.open_new_tab("http://localhost:%s" % args.port)
        ioloop.add_callback(callback)
    ioloop.start()
Beispiel #20
0
def create_app():
    app = Flask(__name__)
    app.config.from_object("config")

    # Create modules
    app.register_blueprint(newsModule)
    app.register_blueprint(commentsModule)
    app.register_blueprint(weibosModule)
    app.register_blueprint(clusterModule)
    app.register_blueprint(packageModule)
    app.register_blueprint(packageWeiboModule)

    # Enable the toolbar?
    app.config["DEBUG_TB_ENABLED"] = app.debug
    # Should intercept redirects?
    app.config["DEBUG_TB_INTERCEPT_REDIRECTS"] = True
    # Enable the profiler on all requests, default to false
    app.config["DEBUG_TB_PROFILER_ENABLED"] = True
    # Enable the template editor, default to false
    app.config["DEBUG_TB_TEMPLATE_EDITOR_ENABLED"] = True
    # debug toolbar
    # toolbar = DebugToolbarExtension(app)

    # the debug toolbar is only enabled in debug mode
    app.config["DEBUG"] = True

    app.config["ADMINS"] = frozenset(["youremail@yourdomain.com"])
    app.config["SECRET_KEY"] = "SecretKeyForSessionSigning"
    app.config["THREADS_PER_PAGE"] = 8

    app.config["CSRF_ENABLED"] = True
    app.config["CSRF_SESSION_KEY"] = "somethingimpossibletoguess"

    return app
Beispiel #21
0
def create_app(database_uri="sqlite://"):
    app = Flask(__name__)
    app.config["SECRET_KEY"] = "not secure"

    app.engine = create_engine(database_uri, convert_unicode=True)
    db_session = scoped_session(sessionmaker(autocommit=False, autoflush=False, bind=app.engine))
    datastore = SQLAlchemyDatastore((Course, Student, Teacher), db_session)
    admin_blueprint = admin.create_admin_blueprint(datastore, view_decorator=login_required)

    @admin_blueprint.route("/login/", methods=("GET", "POST"))
    def login():
        if request.form.get("username", None):
            session["user"] = request.form["username"]
            return redirect(request.args.get("next", url_for("admin.index")))
        else:
            if request.method == "POST":
                return render_template("login.html", bad_login=True)
            else:
                return render_template("login.html")

    @admin_blueprint.route("/logout/")
    def logout():
        del session["user"]
        return redirect("/")

    @app.route("/")
    def go_to_admin():
        return redirect("/admin/")

    app.register_blueprint(admin_blueprint, url_prefix="/admin")

    return app
Beispiel #22
0
def create_app(**config):
    """Application Factory

    You can create a new He-Man application with::

        from heman.config import create_app

        app = create_app() # app can be uses as WSGI application
        app.run() # Or you can run as a simple web server
    """
    app = Flask(__name__, static_folder=None)

    if "MONGO_URI" in os.environ:
        app.config["MONGO_URI"] = os.environ["MONGO_URI"]

    app.config["LOG_LEVEL"] = "DEBUG"
    app.config["SECRET_KEY"] = "2205552d13b5431bb537732bbb051f1214414f5ab34d47"

    configure_logging(app)
    configure_sentry(app)
    configure_api(app)
    configure_mongodb(app)
    configure_login(app)

    return app
Beispiel #23
0
def create_app():
    app = Flask(__name__, static_url_path="/static", static_folder="static", template_folder="template")
    app.config["SECRET_KEY"] = "lazers are kewl"

    def interrupt():
        global poll_thread
        if poll_thread:
            poll_thread.cancel()

    def poll_data():
        global poll_thread
        global current_data

        lock.acquire()
        current_data = read_data()
        lock.release()

        poll_thread = threading.Timer(POLL_TIME, poll_data, ())
        poll_thread.start()

    def poll_start():
        global poll_thread

        poll_thread = threading.Timer(POLL_TIME, poll_data, ())
        poll_thread.start()

    poll_start()
    atexit.register(interrupt)
    return app
Beispiel #24
0
def create_app(ignore_exceptions=None):
    import os

    app = Flask(__name__)
    app.config["SECRET_KEY"] = os.urandom(40)

    if ignore_exceptions:
        app.config["RAVEN_IGNORE_EXCEPTIONS"] = ignore_exceptions

    @app.route("/an-error/", methods=["GET", "POST"])
    def an_error():
        raise ValueError("hello world")

    @app.route("/capture/", methods=["GET", "POST"])
    def capture_exception():
        try:
            raise ValueError("Boom")
        except:
            current_app.extensions["sentry"].captureException()
        return "Hello"

    @app.route("/message/", methods=["GET", "POST"])
    def capture_message():
        current_app.extensions["sentry"].captureMessage("Interesting")
        return "World"

    @app.route("/an-error-logged-in/", methods=["GET", "POST"])
    def login():
        login_user(User())
        raise ValueError("hello world")

    return app
Beispiel #25
0
def create_cartographer(args):
    app = Flask(__name__)
    app.config["SECRET_KEY"] = "map the soul"

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

    @app.route("/getPoints", methods=["POST"])
    def getPoints():
        print(request.json)
        zoom = int(request.json.get("zoom", 1))
        seen = request.json.get("seen", [])
        ensure(seen).is_a_list_of(str)
        points = POI.objects(
            at__geo_within_box=(request.json["SW"], request.json["NE"]), min_zoom=zoom, name__nin=request.json["seen"]
        )

        return jsonify(
            {
                "points": [
                    {
                        "name": p.name,
                        "lat": p.at["coordinates"][1],
                        "lng": p.at["coordinates"][0],
                        "abstract": lz4.decompress(p.abstract).decode() if p.abstract else "",
                        "img": p.img,
                    }
                    for p in points
                ]
            }
        )

    return app
Beispiel #26
0
def create_app(configfile=None):
    app = Flask(__name__)
    AppConfig(app, configfile)  # Flask-Appconfig is not necessary, but
    # highly recommend =)
    # https://github.com/mbr/flask-appconfig
    Bootstrap(app)

    # in a real app, these should be configured through Flask-Appconfig
    app.config["SECRET_KEY"] = "devkey"
    app.config["RECAPTCHA_PUBLIC_KEY"] = "6Lfol9cSAAAAADAkodaYl9wvQCwBMr3qGR_PPHcw"

    @app.route("/garage")
    def add_numbers():
        ajax_request = request.args.get("ajax_request", 0, type=str)
        print("wassup!\nwassup!\nwassup!\nwassup!\nwassup!\nwassup!\nwassup!\n")
        # open_garage()
        return jsonify(result=ajax_request)

    @app.route("/", methods=("GET", "POST"))
    def index():
        # form = ExampleForm()
        # form.validate_on_submit()  # to get error messages to the browser
        # flash('critical message', 'critical')
        # flash('error message', 'error')

        # flash('info message', 'info')
        # flash('debug message', 'debug')
        # flash('different message', 'different')
        # flash('uncategorized message')
        flash("This application is undergoing tests", "warning")
        # return render_template('index.html', form=form)
        return render_template("index.html")

    return app
Beispiel #27
0
def create_app(config=None):
    app = Flask(__name__)

    app.config["SECRET_KEY"] = "129iv3n91283nv9812n3v89q2nnv9iaszv978n98qwe7z897d"
    app.config["SQLALCHEMY_DATABASE_URI"] = "postgresql://postgres@localhost/mooddiaryDb"
    # app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:////tmp/mooddiary.db'

    app.config["DEBUG"] = True
    app.config["LESS_BIN"] = os.path.realpath(os.path.join(os.path.dirname(__file__), "../node_modules/less/bin/lessc"))

    app.config["JWT_EXPIRATION_DELTA"] = timedelta(days=28)
    app.config["JWT_ALGORITHM"] = "HS512"

    app.config["RECAPTCHA_SECRET_KEY"] = "6LdSswwTAAAAADs20eK6NqYaeppxIWm-gJrpto0l"
    app.config["RECAPTCHA_PUBLIC_KEY"] = "6LdSswwTAAAAABTZq5Za_0blmaSpcg-dFcqaGda9"

    if config:
        app.config.from_object(config)

    app.config["ASSETS_DEBUG"] = app.config["DEBUG"]

    db.init_app(app)
    migrate.init_app(app, db)
    assets.init_app(app)
    jwt.init_app(app)

    assets.register("js", js)
    assets.register("css", css)

    app.register_blueprint(main)
    app.register_blueprint(api, url_prefix="/api")
    app.register_blueprint(auth, url_prefix="/auth")

    return app
Beispiel #28
0
def create_app(config=Config()):
    """Flask application factory."""

    app = Flask(__name__)

    if config is not None:
        app.config.from_object(config)

    # override settings by environment variables

    if "DEBUG" in os.environ:
        app.config["DEBUG"] = os.environ["DEBUG"].lower() == "true"

    if "SECRET_KEY" in os.environ:
        app.config["SECRET_KEY"] = os.environ["SECRET_KEY"]

    if "SSL_ENABLE_REDIRECTS" in os.environ:
        app.config["SSL_ENABLE_REDIRECTS"] = os.environ["SSL_ENABLE_REDIRECTS"].lower() == "true"

    if "DATABASE_URL" in os.environ:
        app.config["SQLALCHEMY_DATABASE_URI"] = os.environ["DATABASE_URL"]

    db.init_app(app)
    babel = Babel(app)
    login_manager.setup_app(app)
    oid.init_app(app)
    DebugToolbarExtension(app)

    app.register_blueprint(times)

    admin = Admin(app, url_prefix="/admin", title="Admin")
    admin.add_path_security("/", secure_admin_path)
    admin.add_path_security("/auth", secure_admin_auth_path)

    auth_node = admin.register_node("/auth", "auth", "Authentication")
    time_node = admin.register_node("/time_node", "time_node", "Times")

    admin.register_module(UserAdmin, "/users", "users", "Users", parent=auth_node)
    admin.register_module(CompanyAdmin, "/companies", "companies", "Companies", parent=time_node)
    admin.register_module(ProjectAdmin, "/projects", "projects", "Projects", parent=time_node)
    admin.register_module(TaskAdmin, "/tasks", "tasks", "Tasks", parent=time_node)
    admin.register_module(WorkingUnitAdmin, "/times", "times", "Working Times", parent=time_node)

    @login_manager.user_loader
    def load_user(userid):
        return User.query.get(int(userid))

    @app.context_processor
    def inject_context():
        version = os.environ.get("VERSION", "devel")
        return dict(user=current_user, now=datetime.now(), version=version)

    @babel.localeselector
    def get_locale():
        if hasattr(current_user, "locale"):
            return current_user.locale
        return request.accept_languages.best_match(["en", "ja", "de"])

    return app
Beispiel #29
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
Beispiel #30
0
def test_adds_auth_endpoint():
    app = Flask(__name__)
    app.config["SECRET_KEY"] = "super-secret"
    app.config["JWT_AUTH_URL_RULE"] = "/auth"
    app.config["JWT_AUTH_ENDPOINT"] = "jwt_auth"
    flask_jwt.JWT(app)
    rules = [str(r) for r in app.url_map._rules]
    assert "/auth" in rules