def runAppThread(run_event): print("Running flask app") while run_event.is_set(): app = create_app() app.run(debug=False) #app.run(debug=True) #Only debug = True while work in progress´ time.sleep(1)
def test_set_config(self): class TestConfig(_TestingConfig): CLASS_CONFIG_KEY = 'class' def __init__(self): super().__init__() self.INSTANCE_CONFIG_KEY = 'instance' # A config class should be instantiated. app = website.create_app(TestConfig) assert app.config['CLASS_CONFIG_KEY'] == 'class' assert app.config['INSTANCE_CONFIG_KEY'] == 'instance' # And a config instance used as is. app = website.create_app(TestConfig()) assert app.config['CLASS_CONFIG_KEY'] == 'class' assert app.config['INSTANCE_CONFIG_KEY'] == 'instance'
def client(): my_app = create_app({ 'TESTING': True, # Set to True during testing. 'TEST_DATA_PATH': TEST_DATA_PATH, # Path for loading test data into the repository. 'WTF_CSRF_ENABLED': False # test_client will not send a CSRF token, so disable validation. }) return my_app.test_client()
def freeze(ctx, dst=FROZEN_WEBSITE, preview=False): config = DevelopmentConfig(FREEZER_DESTINATION=dst) app = create_app(config) freezer = Freezer(app) if preview: freezer.run(debug=True) else: freezer.freeze() print(f"Website frozen in {freezer.root}")
def demo(ctx): """Launch a demo server, with some data to play with. The server can be accessed on http://localhost:5000/ """ app = create_app(DevelopmentConfig) if not app.config['DATABASE_PATH']: # To not overwrite a database set via environment variables. setup_demo(app) app.run(debug=True, use_reloader=False)
def main(): app = create_app(config.Config) alpine_version = app.config["ALPINE_VERSION"] alpine_file_path = app.config["ALPINE_FILE_PATH"] alpine_url = f"https://unpkg.com/alpinejs@{alpine_version}/dist/cdn.min.js" alpine = requests.get(alpine_url) if alpine.ok: os.makedirs(os.path.dirname(alpine_file_path), exist_ok=True) with open(alpine_file_path, 'w') as f: f.write(alpine.text)
def create_db(ctx, path): """Create and initialize database.""" path = Path(path) if path.exists(): exit("💥 Database already exists!") path.touch() config = DevelopmentConfig(DATABASE_PATH=path) app = create_app(config) with app.app_context(): _db.create_all()
def main(serve, deployment): ''' Freeze website into static files ''' if deployment: app = create_app(config.DeployConfig) else: app = create_app(config.ProdConfig) # Instructs the freezer to also check for dynamically generated urls # from serve_page functinon. @freezer.register_generator def register_fonts(): ''' Register font files with frozen flask ''' fonts = app.config["FONTS"] for path, font in fonts.items(): file = Path('fonts', path, font) yield flask.url_for('static', filename=str(file)) click.echo("Building website:") # TODO: check font files exist and compile with pyftsubset # Freeze static files into default directory 'build' assert app.cfg == freezer.app.cfg freezer.freeze() click.echo("Website frozen") compile_css(app, compressed=True) click.echo("Css recompiled") # Frozen flask issue: # have to manually build the 404 error page for use by server with app.test_request_context(): error_page = flask.render_template('generic/404.html.j2') with open('website/build/404.html', 'w', encoding="utf-8") as f: f.write(error_page) if serve: freezer.serve()
def test_on_disk_database_is_not_overwritten(self, invoke, monkeypatch, tmpdir): db = tmpdir.ensure('test.db') config = DevelopmentConfig(DATABASE_PATH=db) app = create_app(config) with app.app_context(): _db.create_all() last_update = db.mtime() monkeypatch.setenv(DevelopmentConfig.ENV_DATABASE_PATH, str(db)) check_server_is_running(invoke, 'demo') assert db.mtime() == last_update
def run(ctx): """Run the website. The web server can be accessed on http://localhost:5000/ Let Flask runs the server, otherwise automatic reloading does not work properly. See http://flask.pocoo.org/docs/latest/api/#flask.Flask.run for more info. """ # Cannot type commands in the interpreter. # env = {'FLASK_APP': FLASK_APP, 'FLASK_DEBUG': '1'} # ctx.run('flask run', env=env) app = create_app(DevelopmentConfig) app.run(debug=True)
def main(): """ Run a hot reloading development server on port 5001 """ app = create_app(config.DevConfig) def sass(): return compile_css(app) sass() # Run dev server server = lr.Server(app.wsgi_app) server.watch('website/static/scss/**/*.scss', func=sass) server.watch('website') server.serve(port=5001)
def client(): app = create_app() app.config['TESTING'] = True def setup(): """ Code run after client has been used """ teardown() def teardown(): """ Code run after client has been used """ pass with app.test_client() as client: with app.app_context(): setup() yield client teardown()
def app(): """Create and configure a new app instance for each test.""" # create a temporary file to isolate the database for each test db_fd, db_path = tempfile.mkstemp() # create the app with common test config app = create_app({ "DEBUG": False, "TESTING": True, "SECRET_KEY": "dev", "TIMEZONE": "Europe/Paris", "WORKER_TOKEN": "dev", "RABBITMQ_HOST": "localhost", "RABBITMQ_PORT": 5672, "RABBITMQ_QUEUE": "tasks", "RABBITMQ_LOGIN": "******", "RABBITMQ_PASSWORD": "******", "API_ENABLE": True, "API_KEY": "dev", "API_CORS_ALLOW_ORIGINS": "*", "DATABASE": db_path, "WTF_CSRF_ENABLED": False }) # create the database and load test data with app.app_context(): init_db() get_db().executescript(_data_sql) update_token(1, config['USER']['GITEA_TEST_TOKEN']) update_gitea(config['GITEA']['TEST_URL'], config['GITEA']['TEST_OWNER'], config['GITEA']['TEST_REPOSITORY']) babel = Babel(app) @babel.localeselector def get_locale(): return request.accept_languages.best_match(['fr', 'en'], 'en') CSRFProtect(app) yield app # close and remove the temporary database os.close(db_fd) os.unlink(db_path)
def create_database(dataframe): app = create_app() with app.app_context(): # TODO Check if database already exists (sqlalchemy-utils) and warn user before deleting db.drop_all() db.create_all() for c_id in dataframe['cluster_id'].unique(): c = Cluster(id=int(c_id), name=f'Cluster {c_id}') db.session.add(c) for i, row in dataframe.iterrows(): r = Region(id=i, shapefile_id=row['chosen_id'], name=row['name'], cluster_id=row['cluster_id']) db.session.add(r) db.session.commit()
def setUp(self): app = create_app() basedir = os.path.abspath(os.path.dirname(__file__)) app.config['TESTING'] = True app.config['WTF_CSRF_ENABLED'] = False app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' + os.path.join( basedir, 'test.db') self.app = app.test_client() app_ctx = app.app_context() app_ctx.push() db.create_all() s1 = User(name="Abdi", email="*****@*****.**", password=1234) s2 = User(name="Farshad", email="*****@*****.**", password=123) score1 = Score(name="Abdi", score=180) score2 = Score(name="Farshad", score=180) db.session.add(s1) db.session.add(s2) db.session.add(score1) db.session.add(score2) db.session.commit()
def test_jinja2_does_not_silently_pass_undefined_variables(self): app = website.create_app(_TestingConfig) with pytest.raises(jinja2.exceptions.UndefinedError): with app.test_request_context(): flask.render_template_string('{{ undefined_variable }}')
def test_extensions_are_initialized(self): app = website.create_app(_TestingConfig) assert 'sqlalchemy' in app.extensions
def test_all_blueprints_are_registered(self): app = website.create_app(_TestingConfig) assert 'blog' in app.blueprints
from website import create_app app = create_app('../dev.cfg')
from website import create_app import config if __name__ == "__main__": app = create_app('config') app.run(host=config.SITE_URL, port=config.SITE_PORT, debug=config.DEBUG)
from website import create_app import random app = create_app() if __name__ == '__main__': app.debug = True app.run(host='0.0.0.0', port=random.randint(2000, 9000)) #app.run(debug=True)
def app(): """ Fixture for creating an instance of a Flask application. The scope is set to 'session'. """ return website.create_app(config_name="Test")
from website import create_app app, _ = create_app() client = app.test_client() if __name__ == '__main__': app.run()
import os from website import create_app, register_blueprints from flask.ext.mongoengine import MongoEngine if os.getenv('PRODUCTION', False): app = create_app('website.config.Config') else: app = create_app('website.config.DevelopmentConfig') db = MongoEngine(app) register_blueprints(app) if __name__ == '__main__': """ Change to website.config.Config for deployment """ app.run()
"""Used by Flask, to provide a command-line interface. I don't use directly. I prefer Invoke, because Invoke is more cool :ok_hand: """ from website import create_app from website.config import DevelopmentConfig app = create_app(DevelopmentConfig)
import os from website import create_app app = create_app(os.getenv('FLASK_CONFIG') or 'default') if __name__ == '__main__': app.run(host='0.0.0.0')
#!/Users/sumo/.virtualenvs/ds-site/bin/python import os from website import create_app, db from website.models import User, Role, Cup, League, Team, Article, Category, Tag, Player, Manager, Association, Country, Topic, Comment from flask.ext.script import Manager, Shell from flask.ext.migrate import Migrate, MigrateCommand app = create_app(os.getenv('FLASK_CONFIG') or 'default') manager = Manager(app) migrate = Migrate(app, db) def make_shell_context(): return dict(app=app, db=db, User=User, Role=Role, Cup=Cup, League=League, Team=Team, Article=Article, Category=Category, Tag=Tag, Player=Player, Manager=Manager, Association=Association, Country=Country, Topic=Topic, Comment=Comment ) manager.add_command('shell', Shell(make_context=make_shell_context))
def setUp(self): self.app = create_app('testing') self.app_context = self.app.app_context() self.app_context.push() db.create_all()
from website import create_app from os import environ """ created by Olga Reznyk """ app = create_app(environ.get('DevConfig')) if __name__ == '__main__': # TODO: WARNING!!!! Turn off debug option before production !!!!!!! app.run()
from website import create_app from website.models import db import ssl from handlers import CMRESHandler AGGREGATOR_HOSTNAME = 'aggregator.galahad.com' app = None is_dev = bool(os.getenv('FLASK_DEBUG')) if is_dev: os.environ['AUTHLIB_INSECURE_TRANSPORT'] = 'true' conf_file = os.path.abspath('conf/dev.config.py') app = create_app(conf_file) @app.after_request def add_header(resp): resp.headers['Cache-Control'] = 'no-store' resp.headers['Pragma'] = 'no-cache' return resp else: app = create_app() @app.before_first_request def initialize_logger(): setup_logging(AGGREGATOR_HOSTNAME, '/var/private/ssl/elasticsearch_keys/kirk.crtfull.pem', '/var/private/ssl/elasticsearch_keys/kirk.key.pem', 'admin', 'admin', '/var/private/ssl/elasticsearch_keys/ca.pem')
from website import create_app from os import environ app = create_app() # default config if __name__ == "__main__": debug = environ.get( "DEBUG").lower() == "true" if "DEBUG" in environ else False app.run(debug=debug)
from website import create_app import os app = create_app(os.environ.get('FLASK_ENV'))
import website app = website.create_app() if __name__ == '__main__': app.run(debug=True)