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__) # We use Flask-Appconfig here, but this is not a requirement AppConfig(app) # Install our Bootstrap extension Bootstrap(app) Debug(app) # Our application uses blueprints as well; these go well with the # application factory. We already imported the blueprint, now we just need # to register it: app.register_blueprint(frontend) # Because we're security-conscious developers, we also hard-code disabling # the CDN support (this might become a default in later versions): app.config['BOOTSTRAP_SERVE_LOCAL'] = True # We initialize the navigation as well nav.init_app(app) return app
def create_app(config_name): app = Flask(__name__, instance_relative_config=True) app.config.from_object(app_config[config_name]) app.config.from_pyfile('config.py') db.init_app(app) Bootstrap(app) Debug(app) login_manager.init_app(app) login_manager.login_message="YOU MUST BE LOGGED IN" login_manager.login_view="auth.login" #migration migrate=Migrate(app,db) from app import models #registering the blueprints from .admin import admin as admin_blueprint app.register_blueprint(admin_blueprint, url_prefix='/admin') from .auth import auth as auth_blueprint app.register_blueprint(auth_blueprint) from .home import home as home_blueprint app.register_blueprint(home_blueprint) return app
def create_app(configfile=None): app = Flask(__name__, template_folder='templates') AppConfig(app) # Install our Bootstrap extension Bootstrap(app) # For debugging (there will be errors without it) Debug(app) # Our application uses blueprints as well; these go well with the # application factory. We already imported the blueprint, now we just need # to register it: app.register_blueprint(frontend) app.config['BOOTSTRAP_SERVE_LOCAL'] = True app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER app.config['MAX_FILE_SIZE'] = MAX_FILE_SIZE app.config['ALLOWED_EXTENSIONS'] = ALLOWED_EXTENSIONS app.config['BOOTSTRAP_SERVE_LOCAL'] = True app.secret_key = 'try_to_guess' # We initialize the navigation as well nav.init_app(app) return app
def create_app(test_config=None) -> Flask: app = Flask(__name__, instance_relative_config=True) if test_config is None: user_config = pathlib.Path('config.py') if user_config.exists(): app.config.from_pyfile(user_config, silent=True) else: app.config.from_object(Config) else: app.config.from_object(test_config) Debug(app) Bootstrap(app) app.register_blueprint(frontend) app.config['BOOTSTRAP_SERVE_LOCAL'] = True nav.init_app(app) crsf = CSRFProtect() crsf.init_app(app) return app
def create_app(): app = Flask(__name__) Bootstrap(app) Debug(app) app.register_blueprint(frontend) app.config['BOOTSTRAP_SERVE_LOCAL'] = True nav.init_app(app) return app
def create_app(configfile=None): app = Flask(__name__) AppConfig(app) Bootstrap(app) Debug(app) app.register_blueprint(frontend) app.config["BOOTSTRAP_SERVE_LOCAL"] = True app.secret_key = 'myverylongsecretkey' return app
def app(): app = Flask(__name__) Debug(app) app.config['DEBUG'] = True app.config['TESTING'] = True app.config['FLASK_DEBUG_DISABLE_STRICT'] = True assert app.debug assert app.testing return app
def CreateApp(configfile=None): from flask import Flask from flask.ext.appconfig import AppConfig from rq_dashboard import RQDashboard from flask_debug import Debug from flask.ext.rq import RQ result = Flask(__name__) AppConfig(result, default_settings="gir.config", configfile=configfile) result.config['RQ_DEFAULT_URL'] = result.config['REDIS_URL'] RQDashboard(result) Debug(result) RQ(result) return result
def app(): import sys sys.path.append('.') from sample_app import create_app app = create_app() app.debug = True app.testing = True # manually add flask-debug from flask_debug import Debug Debug(app) return app
def create_app(test_config=None): app = Flask(__name__, instance_relative_config=True) Debug(app) # Front-end blueprint architecture of the app. Material(app) app.register_blueprint(blueprint) APP_SECRET_KEY = os.urandom(32) app.config.from_mapping( SECRET_KEY=APP_SECRET_KEY, DATABASE=os.path.join(app.instance_path, 'app.sqlite'), FLASK_DEBUG_DISABLE_STRICT='True', ) app.debug = True if test_config is None: # load the instance config, if it exists, when not testing app.config.from_pyfile('config.py', silent=True) else: # load the test config if passed in app.config.from_mapping(test_config) # ensure the instance folder exists try: os.makedirs(app.instance_path) except OSError: pass #Database managment with app.app_context(): db.init_app(app) login_manager.init_app(app) login_manager.login_view = 'blueprint.login' return app
def _construct_sms(matching_movies): """ Create a pretty text to be sent over SMS :param matching_movies: list of Movie objects :return: str """ pretty_print_movies = '- ' + '\n- '.join( sorted(_remove_unicode(*matching_movies))) return 'Thank you for using Trang\'s Movie App!\n' \ 'Here is a reminder to see these movies:\n' + str(pretty_print_movies) def _remove_unicode(*args): """ Turn all of the unicode titles to plain text :param args: list of Movie objects :return: list of modified Movie objects """ return [m.title.encode('UTF8') for m in args] if __name__ == '__main__': print("hello") Debug(app) print("y") app.config.from_object(Config) print("aasdf") app.run(debug=True, host='0.0.0.0', port=5000) print("after")
def init_app(app): Configuration.init_app(app) from flask_debug import Debug Debug(app)
def dev(obj, debug, hostname, port, ssl, flask_debug, extended_reload): app = obj['app'] msgs = [] if flask_debug is None: flask_debug = debug Debug = None DebugToolbarExtension = None if flask_debug: try: from flask_debug import Debug except ImportError: pass try: from flask_debugtoolbar import DebugToolbarExtension except ImportError: pass if Debug: Debug(app) app.config['SERVER_NAME'] = '{}:{}'.format(hostname, port) # taking off the safety wheels app.config['FLASK_DEBUG_DISABLE_STRICT'] = True if DebugToolbarExtension: # Flask-Debugtoolbar does not check for debugging settings at runtime. # this hack enabled debugging if desired before initializing the # extension if debug: app.debug = True # set the SECRET_KEY, but only if we're in debug-mode if not app.config.get('SECRET_KEY', None): msgs.append('SECRET_KEY not set, using insecure "devkey"') app.config['SECRET_KEY'] = 'devkey' DebugToolbarExtension(app) def on_off(ext): return 'on' if ext is not None else 'off' msgs.insert(0, 'Flask-Debug: {}'.format(on_off(Debug))) msgs.insert(0, 'Flask-DebugToolbar: {}'.format(on_off(DebugToolbarExtension))) if msgs: click.echo(' * {}'.format(', '.join(msgs))) if extended_reload > 0: # we need to moneypatch the werkzeug reloader for this feature from werkzeug._reloader import ReloaderLoop orig_restart = ReloaderLoop.restart_with_reloader def _mp_restart(*args, **kwargs): while True: status = orig_restart(*args, **kwargs) if status == 0: break # an error occured, possibly a syntax or other click.secho( 'App exited with exit code {}. Will attempted restart in ' '{} seconds.'.format(status, extended_reload), fg='red') time.sleep(extended_reload) return status ReloaderLoop.restart_with_reloader = _mp_restart app.run(hostname, port, ssl_context=ssl, debug=debug, extra_files=obj['extra_files'])
from flask_debug import Debug debug = Debug()
database.addPost(data, lat, lng) print("created new entry in database") resp = jsonify(success=True) resp.status_code = 200 return resp @application.route('/favorited/<postID>') def favorite_post(postID): if request.method == 'GET': '''favorite the post with id''' database.incrementFavorites(postID) return redirect('/') @application.route('/feed/<latitude>/<longitude>') def show_feed(latitude, longitude): posts = database.getPosts(float(longitude), float(latitude)) posts = json.loads(posts) for post in posts["posts"]: post["location"]["coordinates"][ 0] = "%.2f" % post["location"]["coordinates"][0] post["location"]["coordinates"][ 1] = "%.2f" % post["location"]["coordinates"][1] return render_template('feed.html', posts=posts["posts"]) if __name__ == "__main__": application.debug = True Debug(application) application.run(ssl_context='adhoc')
def main(): # Our database dbpath = 'dbflask-config.json' # Usando TinyJ dbj = Database(dbpath) class ConfigModel(TinyJsonModel): __tablename__ = "config" ENV = fields.StringField(required=True, validators=[validators.Length(3, 25)]) SECRET_KEY = fields.StringField(required=True, validators=[validators.Length(50, 64)]) APP_DIR = fields.StringField(required=True, validators=[validators.Length(1, 253)]) PROJECT_ROOT = fields.StringField( required=True, validators=[validators.Length(1, 256)]) BCRYPT_LOG_ROUNDS = fields.IntField( required=True, validators=[ validators.Min(4), validators.Max(10000) ]) # needs at least 4 to avoid "ValueError: Invalid rounds" DEBUG = fields.BoolField(required=True) ASSETS_DEBUG = fields.BoolField(required=True) DEBUG_TB_ENABLED = fields.BoolField(required=True) DEBUG_TB_INTERCEPT_REDIRECTS = fields.BoolField(required=True) CACHE_TYPE = fields.EmbeddedField(CacheType) SQLALCHEMY_TRACK_MODIFICATIONS = fields.BoolField(required=True) APP_NAME = fields.StringField(required=True, validators=[validators.Length(1, 32)]) APP_TMPL = fields.StringField(required=True, validators=[validators.Length(1, 32)]) DB_NAME = fields.StringField(required=True, validators=[validators.Length(1, 32)]) DB_PATH = fields.StringField(required=True, validators=[validators.Length(1, 256)]) SQLALCHEMY_DATABASE_URI = fields.StringField( required=True, validators=[validators.Length(1, 256)]) WTF_CSRF_ENABLED = fields.BoolField(required=True) TESTING = fields.BoolField(required=True) AUTH_ENGINES = fields.ListField([AuthType]) FLASK_DEBUG_DISABLE_STRICT = fields.BoolField(required=True) _last_update = fields.DateTimeField(required=True) _created_at = fields.DateTimeField(required=True) def __init__(self, *args, **kwargs): self._last_update = datetime.utcnow() self._created_at = self._last_update super(ConfigModel, self).__init__(*args, **kwargs) # Example model custom method def created_at_datetime(self): return self._created_at @property def getauthbackends(self): return self.AUTH_ENGINES class Meta: database = dbj # Create new record for dev config devcfg = ConfigModel( ENV='dev', SECRET_KEY=os.urandom(25).encode('hex'), APP_DIR=os.path.abspath(os.path.dirname(__file__)), # This directory #PROJECT_ROOT = os.path.abspath(os.path.join(config.APP_DIR, os.pardir)), PROJECT_ROOT=os.path.abspath( os.path.join(os.path.abspath(os.path.dirname(__file__)), os.pardir)), # For faster tests use 4, see http://security.stackexchange.com/questions/3959/recommended-of-iterations-when-using-pkbdf2-sha256/3993#3993 BCRYPT_LOG_ROUNDS=100, DEBUG=True, ASSETS_DEBUG=True, DEBUG_TB_ENABLED=True, DEBUG_TB_INTERCEPT_REDIRECTS=False, CACHE_TYPE=CacheType(engine='Memcached', host='localhost', port=11211), SQLALCHEMY_TRACK_MODIFICATIONS=False, APP_NAME='Daspanel - Panel GUI', APP_TMPL='sb-admin', DB_NAME='dev.db', #DB_PATH = os.path.join('/opt/daspanel/data/db', config.DB_NAME), DB_PATH='/opt/daspanel/data/db/dev.db', #SQLALCHEMY_DATABASE_URI = 'sqlite:///{0}'.format(config.DB_PATH), SQLALCHEMY_DATABASE_URI='sqlite:////opt/daspanel/data/db/dev.db', WTF_CSRF_ENABLED=False, TESTING=False, AUTH_ENGINES=[ AuthType(provider='Local'), AuthType(provider='Daspanel') ], FLASK_DEBUG_DISABLE_STRICT=True, ) # ListField can have valued appended devcfg.AUTH_ENGINES.append(AuthType(provider='Getuuid')) # Validate before save devcfg.validate() # Insert/save the new record devcfgid = devcfg.insert() devcfgcuid = devcfg._cuid print("\nDevcfg: ", devcfgid, devcfg.id, devcfgcuid, devcfg._cuid, devcfg.ENV, devcfg.AUTH_ENGINES) # Create new record for staging config stgcfg = ConfigModel() stgcfg.ENV = 'staging' stgcfg.SECRET_KEY = os.urandom(25).encode('hex') stgcfg.APP_DIR = os.path.abspath(os.path.dirname(__file__)) stgcfg.PROJECT_ROOT = os.path.abspath( os.path.join(stgcfg.APP_DIR, os.pardir)) stgcfg.BCRYPT_LOG_ROUNDS = 100 stgcfg.DEBUG = True stgcfg.ASSETS_DEBUG = True stgcfg.DEBUG_TB_ENABLED = True stgcfg.DEBUG_TB_INTERCEPT_REDIRECTS = False stgcfg.CACHE_TYPE = CacheType(engine='Memcached', host='localhost', port=11211) stgcfg.SQLALCHEMY_TRACK_MODIFICATIONS = False stgcfg.APP_NAME = 'Daspanel - Panel GUI' stgcfg.APP_TMPL = 'sb-admin' stgcfg.DB_NAME = 'dev.db' stgcfg.DB_PATH = os.path.join('/opt/daspanel/data/db', stgcfg.DB_NAME) stgcfg.SQLALCHEMY_DATABASE_URI = 'sqlite:///{0}'.format(stgcfg.DB_PATH) stgcfg.WTF_CSRF_ENABLED = False stgcfg.TESTING = False stgcfg.AUTH_ENGINES = [ AuthType(provider='Getuuid'), AuthType(provider='Local') ] stgcfg.FLASK_DEBUG_DISABLE_STRICT = True stgcfg.validate() stgcfgid = stgcfg.insert() print("Stgcfg: ", stgcfgid, stgcfg.id, stgcfg._cuid, stgcfg.ENV, stgcfg.AUTH_ENGINES) # Create new record for production config prodcfg = ConfigModel() prodcfg.ENV = 'prod' prodcfg.SECRET_KEY = os.urandom(25).encode('hex') prodcfg.APP_DIR = os.path.abspath(os.path.dirname(__file__)) prodcfg.PROJECT_ROOT = os.path.abspath( os.path.join(prodcfg.APP_DIR, os.pardir)) prodcfg.BCRYPT_LOG_ROUNDS = 100 prodcfg.DEBUG = True prodcfg.ASSETS_DEBUG = True prodcfg.DEBUG_TB_ENABLED = True prodcfg.DEBUG_TB_INTERCEPT_REDIRECTS = False prodcfg.CACHE_TYPE = CacheType(engine='Memcached', host='localhost', port=11211) prodcfg.SQLALCHEMY_TRACK_MODIFICATIONS = False prodcfg.APP_NAME = 'Daspanel - Panel GUI' prodcfg.APP_TMPL = 'sb-admin' prodcfg.DB_NAME = 'dev.db' prodcfg.DB_PATH = os.path.join('/opt/daspanel/data/db', prodcfg.DB_NAME) prodcfg.SQLALCHEMY_DATABASE_URI = 'sqlite:///{0}'.format(prodcfg.DB_PATH) prodcfg.WTF_CSRF_ENABLED = False prodcfg.TESTING = False prodcfg.AUTH_ENGINES = [ AuthType(provider='Getuuid'), AuthType(provider='Daspanel') ] prodcfg.FLASK_DEBUG_DISABLE_STRICT = True prodcfg.validate() prodcfgid = prodcfg.insert() prodcfgcuid = prodcfg._cuid print("Prodcfg: ", prodcfgid, prodcfg.id, prodcfgcuid, prodcfg._cuid, prodcfg.ENV, prodcfg.AUTH_ENGINES, "\n") # Get Config record myconfig = ConfigModel.get(dbj.where("ENV") == "prod").to_struct() app = Flask(__name__) app.config.update(myconfig) Debug(app) app.run(debug=True, port=8000, host='0.0.0.0')