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)) admin_blueprint = admin.create_admin_blueprint( (Course, Student, Teacher), db_session, 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
def create_app(): from flask import Flask, render_template from flask.ext.httpauth import HTTPBasicAuth from flask.ext.mongoengine import MongoEngine from flask_debugtoolbar import DebugToolbarExtension from v1.models import db #start the app app = Flask(__name__) #Load up the config app.debug=True app.port="8080" app.host="0.0.0.0" #app.config.from_pyfile('config') app.config["MONGODB_SETTINGS"]={ "db":"deploy", "host":"0.0.0.0", "port":27017 } app.config["SECRET_KEY"]="secretkey" app.config["DEBUG_TB_ENABLED"]=True #bootstrap the database db.init_app(app) #bootstrap everything else #auth = HTTPBasicAuth() toolbar=DebugToolbarExtension(app) from v1.routes import blueprint as DeployApi app.register_blueprint(DeployApi) print app.url_map return app
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
def create_app(config=None, environment=None): app = Flask(__name__) # TODO: Get this from a config file app.config["MONGODB_SETTINGS"] = {'db': "eatdb"} app.config[ "SECRET_KEY"] = "\x1a\xb1\x9d\x1d\xf2\x01\xa1X\xb8g\xed\x1c\xb3\x0f+s\xbce\xf6\x92\x83'\xf2\xbc\x96\xc6\x18\x03`\xc0\x0c(" app.config["IV"] = '\xe7\x9d\xc7\xbd\x12l\x88\xc7\xe9D\x93!\xa2B\xed\x91' app.config.from_pyfile('settings.cfg', silent=True) app.session_interface = MongoSessionInterface(**(app.config["MONGODB_SETTINGS"])) with app.app_context(): from models import db db.init_app(app) login_manager = LoginManager() @login_manager.user_loader def load_user(id): if id in (None, 'None'): return None try: from models.user import User return User.objects(id=id).first() except: return None login_manager.init_app(app) from views import register_routes as register_views register_views(app) return app
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
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 generate_app( debug=False, config_file=None, secret="", session_secret="", github_client_id="", github_client_secret="", github_hook_secret="", mongodb_db="Hook", mongodb_host='127.0.0.1', mongodb_port=27017, mongodb_user=None, mongodb_password=None, hooktest_secret="", hooktest_remote="http://127.0.0.1:5002/hooktest/rest/api/queue" ): app = Flask(__name__) app.config["JSONIFY_PRETTYPRINT_REGULAR"] = False if not config_file: app.config["SECRET_KEY"] = session_secret, app.config["GITHUB_CLIENT_ID"] = github_client_id app.config["GITHUB_CLIENT_SECRET"] = github_client_secret app.config["MONGODB_DB"]= mongodb_db app.config['MONGODB_HOST'] = mongodb_host app.config['MONGODB_PORT'] = mongodb_port if mongodb_user: app.config['MONGODB_USERNAME'] = mongodb_user if mongodb_password: app.config['MONGODB_PASSWORD'] = mongodb_password app.config["HOOKUI_HOOKTEST_SECRET"] = hooktest_secret app.config["HOOKUI_GITHUB_SECRET"] = github_hook_secret app.config["HOOKUI_REMOTE"] = hooktest_remote else: app.config.update(read_yaml(config_file)[0]) app.debug = debug app.config["DEBUG"] = debug hook = HookUI(prefix="", app=app) return app
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)
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
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
def create_app(): import os app = Flask(__name__) app.config["SECRET_KEY"] = os.urandom(40) @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
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
def app(jwt): 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 == "joe" and password == "pass": return User(id=1, username="joe") None @jwt.user_handler def load_user(payload): if payload["user_id"] == 1: return User(id=1, username="joe") @app.route("/protected") @flask_jwt.jwt_required() def protected(): return "success" return app
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
def create_app(_run_mode=None): # Create Flask app. global app base_dir = os.path.dirname(os.path.abspath(__file__)) template_dir = os.path.join(base_dir, 'templates') static_dir = os.path.join(base_dir, 'static') app = Flask("procjam15", template_folder=template_dir, static_folder=static_dir) # Dev run mode. if _run_mode == "dev": app.config["DEBUG"] = True app.config["SECRET_KEY"] = "WeDontCareAboutSecretsInDev" # Heroku run mode. elif _run_mode == "heroku": # Get port number and secret key from Heroku environment variable. app.config["PORT_NR"] = int(os.environ["PORT"]) app.config["SECRET_KEY"] = os.environ["FLASK_SECRET_KEY"] app.config["DEBUG"] = False init_stdout_handler() set_up_logger(app.logger) # Dreamhost run mode. elif _run_mode == "dreamhost": # Get port number and secret key from Heroku environment variable. app.config["SECRET_KEY"] = os.environ["FLASK_SECRET_KEY"] app.config["DEBUG"] = False init_stdout_handler() set_up_logger(app.logger) # Unrecognized run mode. else: logging.error("Did not recognize run mode '%s'." % _run_mode) return None app.debug = app.config["DEBUG"] # Import the views, to apply the decorators which use the global app object. import main.views # Set up Jinja 2 filters. set_up_jinja_filters(app) return app
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
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
def setup(): connect("superadmin_test") app = Flask(__name__) app.config["SECRET_KEY"] = "1" app.config["CSRF_ENABLED"] = False admin = Admin(app) return app, admin
def test_handle_auth_error(mocker): flash = mocker.patch("flask_multipass.core.flash") app = Flask("test") app.config["SECRET_KEY"] = "testing" multipass = Multipass(app) with app.test_request_context(): multipass.handle_auth_error(AuthenticationFailed()) assert flash.called assert session["_multipass_auth_failed"]
def test_handle_auth_error_with_redirect(mocker): flash = mocker.patch("flask_multipass.core.flash") redirect = mocker.patch("flask_multipass.core.redirect") app = Flask("test") app.config["SECRET_KEY"] = "testing" multipass = Multipass(app) with app.test_request_context(): multipass.handle_auth_error(AuthenticationFailed(), redirect_to_login=True) assert flash.called redirect.assert_called_with(app.config["MULTIPASS_LOGIN_URLS"][0])
def setup(): app = Flask(__name__) app.config["SECRET_KEY"] = "1" app.config["CSRF_ENABLED"] = False app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:///" db = SQLAlchemy(app) admin = Admin(app) return app, db, admin
def create_app(self): app = Flask(__name__) app.config["SECRET_KEY"] = "not secure" engine = sa.create_engine("sqlite://", convert_unicode=True) app.db_session = sa.orm.scoped_session(sa.orm.sessionmaker(autocommit=False, autoflush=False, bind=engine)) admin_blueprint = admin.create_admin_blueprint( (simple.Course, simple.Student, simple.Teacher), app.db_session, exclude_pks=False ) app.register_blueprint(admin_blueprint, url_prefix="/admin") simple.Base.metadata.create_all(bind=engine) return app
def run_socket_server(): app = Flask(__name__) app.config["SECRET_KEY"] = "OpenPoGoBotSocket" socketio = SocketIO(app, logging=False, engineio_logger=False, json=myjson) state = {} botevents.register_bot_events(socketio, state) uievents.register_ui_events(socketio, state) socketio.run(app, host="0.0.0.0", port=8000, debug=False, use_reloader=False, log_output=False)
def test_cookie_encoding(self): app = Flask(__name__) app.config["SECRET_KEY"] = "deterministic" COOKIE = u"1|7d276051c1eec578ed86f6b8478f7f7d803a7970" with app.test_request_context(): self.assertEqual(COOKIE, encode_cookie(u"1")) self.assertEqual(u"1", decode_cookie(COOKIE)) self.assertIsNone(decode_cookie(u"Foo|BAD_BASH")) self.assertIsNone(decode_cookie(u"no bar"))
def setUp(self): app = Flask(__name__) app.session_interface = CheckerSessionInterface() app.json_encoder = CustomJSONEncoder app.config["SECRET_KEY"] = "test" app.add_url_rule("/<step>", view_func=TestWizard.as_view("wizard")) app.add_url_rule( "/session-expired", endpoint="base.session_expired", view_func=lambda request: "Session expired" ) self.client = app.test_client() with self.client.session_transaction() as sess: sess.checker["foo"] = "bar"
def create_app(): app = Flask(__name__) c = get_config() app.config["SECRET_KEY"] = c.secrets.session_key app.config["PERMANENT_SESSION_LIFETIME"] = timedelta(days=365) app.jinja_env.block_start_string = "[%" app.jinja_env.block_end_string = "%]" app.jinja_env.variable_start_string = "[[" app.jinja_env.variable_end_string = "]]" app.jinja_env.comment_start_string = "[#" app.jinja_env.comment_end_string = "#]" app.jinja_env.block_start_string = "[%" app.jinja_env.block_end_string = "%]" app.jinja_env.variable_start_string = "[[" app.jinja_env.variable_end_string = "]]" app.jinja_env.comment_start_string = "[#" app.jinja_env.comment_end_string = "#]" @app.before_request def before_request(): g.db = scoped_session(sessionmaker(autocommit=False, autoflush=False, bind=engine)) g.user = None if "auth" in session and session["auth"]: user = g.db.query(User).get(session["user_id"]) g.user = user session.permanent = True @app.teardown_appcontext def after_request(exception=None): g.db.remove() @app.route("/") def index(): user = None if g.user: user = g.user.serialize return render_template("index.html", user=user, config=c, title=c.app_title, logo=c.logo_url, ) app.register_blueprint(account_bp, url_prefix="/v1/account") app.register_blueprint(train_bp, url_prefix="/v1/train") return app
def eventum(tmpdir_factory): app = Flask("testing") app.config["EVENTUM_SETTINGS"] = { "UPLOAD_FOLDER": str(tmpdir_factory.mktemp("upload")), "DELETE_FOLDER": str(tmpdir_factory.mktemp("delete")), "GOOGLE_AUTH_ENABLED": False, } app.config["SECRET_KEY"] = "HELLO" eventum = Eventum(app) with eventum.app.app_context(): yield eventum
def setup(): app = Flask(__name__) app.config["SECRET_KEY"] = "1" app.config["CSRF_ENABLED"] = False app.config["MONGODB_SETTINGS"] = {"DB": "tests"} db = MongoEngine() db.init_app(app) admin = Admin(app) return app, db, admin
def create_app(database_connection): app = Flask("Distributed Cuckoo") app.config["SQLALCHEMY_DATABASE_URI"] = database_connection app.config["SECRET_KEY"] = os.urandom(32) app.register_blueprint(ApiBlueprint, url_prefix="/api") app.register_blueprint(ApiBlueprint, url_prefix="/api/v1") db.init_app(app) db.create_all(app=app) return app
def create_app(): app = Flask(__name__) app.config["MONGODB_SETTINGS"] = { "host": getenv("MONGOLAB_URI", None), } app.config["SECRET_KEY"] = "KeepThisS3cr3t" app.register_blueprint(blueprint) db.init_app(app) return app