def app(request): """Session-wide test `Flask` application.""" settings_override = { 'TESTING': True, 'SQLALCHEMY_DATABASE_URI': TEST_DATABASE_URI, #'SQLALCHEMY_TRACK_MODIFICATIONS' : False, } app = create_app(__name__, settings_override) # Establish an application context before running the tests. ctx = app.app_context() ctx.push() print("DB Fixture!") """Session-wide test database.""" _db.init_app(app) _db.create_all() #db.create_all() def teardown(): _db.drop_all() ctx.pop() os.unlink(TESTDB_PATH) request.addfinalizer(teardown) return app
def test_client(): d_init = {'config_class': TestingConfig} app = app_factory.create_app(d_init) # Expose the Werkzeug test Client testing_client = app.test_client() # Establish an application context before running the tests. ctx = app.app_context() ctx.push() yield testing_client ctx.pop()
def setup_test_app(): app = create_app(config=TestConfig) app.app_context().push() # Note that we do this for tests, when each DB is created from scratch, but we don't do it for prod, when the # DB is incrementally updated via alembic db.create_all() with app.test_client() as client: yield client, db, app print('Removing Test DB') try: os.remove(TestConfig.db_filepath) # this is teardown except FileNotFoundError: Warning( 'Did not manage to tear down test DB, hope this was a temporary env' )
import os import sys root = os.path.dirname(os.path.realpath(__file__)) sys.path.insert(0, root) sys.path.insert(0, os.path.join(root, '..')) from app_factory import create_app application = create_app('DEV')
from app_factory import create_app from settings import DevelopmentConfig application = create_app(DevelopmentConfig) if __name__ == "__main__": host = application.config["APP_HOST"] port = application.config["APP_PORT"] application.run(host=host, port=port)
def test_config(): """Test create_app""" assert not create_app().testing assert create_app('TestConfig').testing
def main(): #DB io should be OKAY with create_app().app_context(): with Connection(conn): worker = Worker(list(map(Queue, listen))) worker.work()
def app(): app = create_app(settings) return app
from rq.job import Job from worker import conn from app_factory import create_app from database import db from models import School, HebSchool, Student, NonDate from emailer import Emailer q = Queue(connection=conn) emailer = Emailer(q) # app = Flask(__name__,static_folder='mitzvah/static') # app.config.from_object(os.environ['APP_SETTINGS']) # app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False # db.init_app(app) app = create_app(__name__) def pre_dict(queries): return list(map(lambda x: x.to_dict(), queries)) # @app.route("/") # def index(): # # return "hello" # return app.send_static_file('index.html') # Program catch-all for routes to send the static index.html file to the current app # @app.route('/', defaults={'path': ''}) # @app.route('/<path:path>') # def index(path=''):
def app(): app_obj = create_app() app_obj.testing = True return app_obj
def app(database): settings.SQLALCHEMY_DATABASE_URI = database app_obj = create_app(settings) app_obj.testing = True with app_obj.test_request_context() as _: yield app_obj
"""WSGI Application""" from app_factory import create_app app = create_app(config_env='ProdConfig')
from app_factory import create_app from models import db import utils import pytest app, mail_server = create_app("test_app.cfg") def setup_function(function): print("Creating db test") with app.app_context(): db.create_all() def teardown_function(function): print("Dropping db test") with app.app_context(): db.drop_all() @pytest.fixture def client(): return app.test_client() @pytest.fixture def remove_time_delay(monkeypatch): monkeypatch.setattr( utils, "send_deferred_email", lambda mail, user_name, user_email: utils._send_deferred_email(
""" WSGI entry point https://flask.palletsprojects.com/en/2.0.x/deploying/wsgi-standalone/#uwsgi """ import app_factory app = app_factory.create_app()
def _create_app(self): self.app = create_app() self.app.testing = True self.app_client = self.app.test_client() self.app_client.environ_base['HTTP_AUTHORIZATION'] = 'Bearer 1234'
from app_factory import create_app from models import db # Create the project using a factory to be able to run tests # with a custom config app (as a test db) app, _ = create_app("app.cfg") with app.app_context(): db.create_all()
def initialize_db(): app = create_app() db.create_all(app=app)
#!/usr/bin/env python from __future__ import print_function, division import logging from flask import render_template from app_factory import create_app from db_model import User, CheckpointTime logger = logging.getLogger(__name__) app = create_app() @app.route('/times') @app.route('/times/<int:page>') def list_times(page=1): times = CheckpointTime.query.paginate(page, 400) return render_template('checkpoint_times.html', times=times) @app.route('/user/<username>') def show_user(username): user = User.query.filter_by(username=username).first_or_404() return render_template('show_user.html', user=user) def main(): logging.basicConfig(level=logging.DEBUG) logger.info('starting web application')
def app(): a = create_app() a.testing = True return a
from app_factory import create_app create_app()
import sys from app_factory import create_app sys.path.append("/Users/ravi/workspace/Python/flask_form") if __name__ == '__main__': app = create_app("") app.debug = True app.run("127.0.0.1", 5001)
from app_factory import create_app app, db = create_app() if __name__ == "__main__": app.run(host="0.0.0.0")
default_env = 'test' FLASK_ENV = os.environ.get('FLASK_ENV', default_env) ## set in *.wsgi ## Custom modules import app_factory import CustomLogging from api_authorization import ApiAuthorizationError from config import * DEBUG = 1 ##--------------------------------------------------------------------------------------- ## Create the Flask app instance from the app_factory d_init = {'DEBUG': DEBUG, 'environment': FLASK_ENV} app = app_factory.create_app(d_init) ##--------------------------------------------------------------------------------------- def error_response(e): """ Output a generic response for app errors """ o_dt = datetime.datetime.now() gmtime_now = o_dt.strftime("%Y-%m-%d %H:%M:%S") etype = e.__class__.__name__ code = getattr(e, 'code', 500) d_response = { 'timestamp': gmtime_now, 'exception': etype, 'message': str(e) } return d_response
import sqlite3 from flask import request, session, g, redirect, url_for, \ render_template, flash from contextlib import closing from app_factory import create_app from app_urls import LOGOUT_URL, WORD_TEST_URL, WELCOME_URL, LOGIN_URL, TEST_RESULT_URL from problems_creator import ProblemsCreator NUMBER_OF_QUESTIONS = 5 app = create_app("app_config.py") def connect_db(): return sqlite3.connect(app.config['DATABASE']) def init_db(): with closing(connect_db()) as db: with app.open_resource('schema.sql') as f: db.cursor().executescript(f.read().decode('utf-8')) # データを挿入 with open("db/Words.txt", mode="r") as f: word_list = [s.strip() for s in f.readlines()] with open("db/Meanings.txt", mode="r") as g: meaning_list = [s.strip() for s in g.readlines()] for i in range(len(word_list) - 1): db.execute(
def app(): app_obj = create_app() app_obj.testing = True with app_obj.test_request_context() as _: yield app_obj
from app_factory import create_app import unittest """ To be implemented... probably """ app, db = create_app("DEBUG") app.testing = True class HousenetBaseTestCase: def setUp(self): self.app = app.test_client() def tearDown(self): pass def test_add_amount(self): self.app.post("/profile/Person%201/", data={"t": 1}) class CliTestsCase(HousenetBaseTestCase, unittest.TestCase): def test_save_db(self): pass class TestHousenetInit(unittest.TestCase):
finder = weather.WeatherWindowFinder(preferences=preferences) window = finder.get_weather_window_for_forecast(forecasts_df) if dry_run: eligible_users.append( f"Would send forecast for {window.weather_timestamp} to {user}" ) else: event = get_calendar_event(location, window, attendees=[user.email], timezone=timezone) calendar.create_event(event) actions.update_most_recent_invite([user]) eligible_users.append( f"Sent forecast for {window.weather_timestamp} to {user}") time.sleep(DELAY_IN_S) print('\n'.join(eligible_users)) if dry_run: print(f'{len(eligible_users)} need invites') else: print(f'{len(eligible_users)} received invites') if __name__ == '__main__': get_credentials_from_s3.main() app = create_app() app.app_context().push() main(dry_run=False)
def app(): """Create and configure a new app instance for each test""" # create the app with test config app = create_app(config_env='TestConfig') yield app