def create_app(config_name): from flask_potion import Api app = Flask(__name__, instance_relative_config=True) app.config.from_object(config_by_name[config_name]) app.logger.info('Connecting database') db.init_app(app) app.logger.info('Setting authenticator') def authenticate(email, password): user = User.query.filter_by(email=email).first() if user and safe_str_cmp(user.password.encode('utf-8'), password.encode('utf-8')): return user def identity(payload): user_id = payload['identity'] return User.query.get(user_id) jwt = JWT(app, authenticate, identity) app.logger.info('creating Flask-Potion Apis') from application import apis api = Api(app, prefix='/api/v1', title='Backend API') apis.create_api(api) app.logger.info('Finished initialization') return app
def __init__(self, *args, **kwargs): """Конструктор класса :param args: tuple :param kwargs: dict """ os.putenv('FLASK_CONFIGURATION', 'test') app = create_app() self.app = app.test_client(self) db.init_app(app) self.login = app.config.get('TEST_LOGIN') self.password = app.config.get('TEST_PASSWORD') self.is_subagent = app.config.get('TEST_IS_SUBAGENT') self.test_rollback = app.config.get('TEST_ROLLBACK') super(FlaskTestCase, self).__init__(*args, **kwargs) self.session_id = None self.www_uuid = None self.wizard_token = None if 'TESTS_DIRECTORY' in app.config: logging.basicConfig(format='%(message)s', filename='%s/test_%s.log' % (app.root_path + app.config['TESTS_DIRECTORY'], datetime.now().strftime('%y-%m-%d_%H-%M'))) else: logging.basicConfig(format='%(message)s')
def create_app(config=None): app = Flask(__name__) app.config.from_object(config) app.register_blueprint(auth_blueprint) # app.register_blueprint(main_blueprint) db.init_app(app) return app
def setUpClass(cls): app.config[ 'SQLALCHEMY_DATABASE_URI'] = 'postgresql://{user}:{password}@{host}/{database}'.format( **config) app.app_context().push() db.init_app(app) cls.app = app.test_client()
def tearDown(self): """ Ensures that the database is emptied for next unit test """ self.app = Flask(__name__) db.init_app(self.app) with self.app.app_context(): db.drop_all()
def setUp(self): """ Creates a new database for the unit test to use """ self.app = Flask(__name__) db.init_app(self.app) with self.app.app_context(): db.create_all() self.populate_db() # Your function that adds test data.
def create_app(config): application = Flask(__name__) application.config.from_object(ProductionConfig) db.init_app(application) application.register_blueprint(bp) application.app_context().push() # application.debug=True db.create_all() return application
def app(request): """ Returns a Flask app for testing Following https://github.com/pallets/flask/blob/master/examples/flaskr/tests/test_flaskr.py """ app = create_app("development") with app.app_context(): db.init_app(app) db.create_all(app=app) yield app
def main(): db.drop_all() db.init_app(app) db.create_all() db.session.add(Cafe('ABS', 'Sydney Uni: Business School')) db.session.add(Cafe('Cafe Ella', '274 Abercrombie St, Darlington')) db.session.add(Cafe('Campos', 'Newtown')) db.session.add( Cafe('Taste Baguette (CPC)', 'Sydney Uni: Charles Perkins Centre')) db.session.add(Cafe('Taste Baguette (Law)', 'Sydney Uni: Law Building')) db.session.add(Cafe('The Shortlist', '258 Abercrombie St, Darlington')) db.session.add(Cafe('Toby\'s Estate', 'City Rd')) db.session.commit()
def create_app(test_config=None): # create and configure the app app = Flask(__name__, instance_relative_config=True) app.config.from_mapping( SECRET_KEY='dev', DATABASE=os.path.join(app.instance_path, 'db.sqlite'), ) 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 # register the database from application import db db.init_app(app) # a simple page that says hello @app.route('/hello') def hello(): return 'Hello, World!' from application import trainer app.register_blueprint(trainer.bp) # set trainer blueprint to index (no url_prefix) app.add_url_rule('/', endpoint='index') # add click command from application.internal_api import upload_craw_csv @app.cli.command('upload-craw-csv') @click.argument('filename') def upload_craw_csv_command(filename): """Clear the existing data and create new tables.""" upload_craw_csv(filename) click.echo(f'Uploaded {filename} data to database.') return app
def create_app(test_config=None): """Create and configure an instance of the Flask application.""" app = Flask(__name__, instance_relative_config=True) app.config.from_mapping( # a default secret that should be overridden by instance config SECRET_KEY="dev", # store the database in the instance folder DATABASE=os.path.join(app.instance_path, "topp52.db"), ) 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.update(test_config) # ensure the instance folder exists try: os.makedirs(app.instance_path) except OSError: pass @app.route("/hello") def hello(): return "Hello, World!" # register the database commands from application import db db.init_app(app) # apply the blueprints to the app from application import auth, index, user, top app.register_blueprint(auth.bp) app.register_blueprint(index.bp) app.register_blueprint(user.bp) app.register_blueprint(top.bp) # make url_for('index') == url_for('blog.index') # in another app, you might define a separate main index here with # app.route, while giving the blog blueprint a url_prefix, but for # the tutorial the blog will be the main index app.add_url_rule("/", endpoint="index") return app
def create_app(test_config=None): app = Flask(__name__, instance_relative_config=True) #CORS(app) sk = os.environ['SECRET_KEY'] app.config.from_mapping( SECRET_KEY=sk, #DATABASE_URI='mysql://ming@localhost/3306', ) '''if test_config is None: app.config.from_pyfile('config.py', silent=False) else: app.config.from_mapping(test_config) try: os.makedirs(app.instance_path) except OSError: pass''' #app.config.from_object('config') @app.route('/') def index(): return "Server is running" @app.route('/test') def test(): tstMsg = "The test environment value is: " + os.environ['TEST_VAL'] return tstMsg import application.db as db db.init_app(app) import application.auth as auth app.register_blueprint(auth.bp) import application.operations as operations app.register_blueprint(operations.bp) return app
def initialize_plugins(app): # Initialize Plugins db.init_app(app) migrate.init_app(app, db) toolbar.init_app(app)
from flask import Flask, render_template, request, redirect, url_for, flash, jsonify from application import db from flask_socketio import SocketIO, emit, join_room, leave_room from application.models import * from application.forms import * import flask_login import query_parser import os import json import datetime import json # Elastic Beanstalk initalization application = Flask(__name__) db.init_app(application) application.debug = True # change this to your own value application.secret_key = 'cC1YCIWOj9GgWspgNEo2' application.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False application.config["CACHE_TYPE"] = "null" login_manager = flask_login.LoginManager() login_manager.init_app(application) login_manager.login_view = 'login' INSTRUCTOR = 'instructor' STUDENT = 'student'
def setUpClass(cls): app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql://{user}:{password}@{host}/{database}'.format(**config) app.app_context().push() db.init_app(app) cls.app = app.test_client()
def create_app(config_object): from application.static_site import static_site_blueprint from application.cms import cms_blueprint from application.admin import admin_blueprint from application.register import register_blueprint from application.auth import auth_blueprint from application.dashboard import dashboard_blueprint from application.review import review_blueprint from application.redirects import redirects_blueprint if isinstance(config_object, str): from application.config import DevConfig, Config, TestConfig if config_object.lower().startswith("production"): config_object = Config elif config_object.lower().startswith("dev"): config_object = DevConfig elif config_object.lower().startswith("test"): config_object = TestConfig else: raise ValueError( f"Invalid config name passed into create_app: {config_object}") app = Flask(__name__) app.config.from_object(config_object) app.file_service = FileService() app.file_service.init_app(app) page_service.init_app(app) upload_service.init_app(app) scanner_service.init_app(app) dimension_service.init_app(app) trello_service.init_app(app) trello_service.set_credentials(config_object.TRELLO_API_KEY, config_object.TRELLO_API_TOKEN) db.init_app(app) app.url_map.strict_slashes = False app.dictionary_lookup = EthnicityDictionaryLookup( lookup_file=config_object.DICTIONARY_LOOKUP_FILE, default_values=config_object.DICTIONARY_LOOKUP_DEFAULTS) app.classification_finder = ethnicity_classification_finder_from_file( config_object.ETHNICITY_CLASSIFICATION_FINDER_LOOKUP, config_object.ETHNICITY_CLASSIFICATION_FINDER_CLASSIFICATIONS, ) # Note not using Flask-Security role model user_datastore = SQLAlchemyUserDatastore(db, User, None) Security(app, user_datastore) if os.environ.get("SENTRY_DSN") is not None: sentry = Sentry(app, dsn=os.environ["SENTRY_DSN"]) app.register_blueprint(cms_blueprint) app.register_blueprint(static_site_blueprint) app.register_blueprint(admin_blueprint) app.register_blueprint(register_blueprint) app.register_blueprint(auth_blueprint) app.register_blueprint(dashboard_blueprint) app.register_blueprint(review_blueprint) app.register_blueprint(redirects_blueprint) # To stop url clash between this and the measure page url (which is made of four variables. # See: https://stackoverflow.com/questions/17135006/url-routing-conflicts-for-static-files-in-flask-dev-server @app.route("/static/<path:subdir1>/<subdir2>/<file_name>") def static_subdir(subdir1, subdir2, file_name): file_path = "%s/%s/%s" % (subdir1, subdir2, file_name) return send_from_directory("static", file_path) register_errorhandlers(app) app.after_request(harden_app) # Render jinja templates with less whitespace; applies to both CMS and static build app.jinja_env.trim_blocks = True app.jinja_env.lstrip_blocks = True app.jinja_env.add_extension(jinja_do) app.add_template_filter(format_page_guid) app.add_template_filter(format_approve_button) app.add_template_filter(format_date_time) app.add_template_filter(render_markdown) app.add_template_filter(filesize) app.add_template_filter(format_friendly_date) app.add_template_filter(format_friendly_short_date) app.add_template_filter(format_friendly_short_date_with_year) app.add_template_filter(format_versions) app.add_template_filter(format_status) app.add_template_filter(value_filter) app.add_template_filter(flatten) app.add_template_filter(flatten_chart) app.add_template_filter(version_filter) app.add_template_filter(strip_trailing_slash) app.add_template_filter(join_enum_display_names) app.add_template_filter(slugify_value) app.add_template_filter(first_bullet) app.add_template_filter(index_of_last_initial_zero) app.add_template_filter(yesno) # There is a CSS caching problem in chrome app.config["SEND_FILE_MAX_AGE_DEFAULT"] = 10 setup_app_logging(app, config_object) if os.environ.get("SQREEN_TOKEN") is not None: setup_sqreen_audit(app) from werkzeug.contrib.fixers import ProxyFix app.wsgi_app = ProxyFix(app.wsgi_app) from flask_sslify import SSLify SSLify(app) mail.init_app(app) @app.context_processor def inject_globals(): from application.auth.models import ( COPY_MEASURE, CREATE_MEASURE, CREATE_VERSION, DELETE_MEASURE, MANAGE_SYSTEM, MANAGE_USERS, ORDER_MEASURES, PUBLISH, READ, UPDATE_MEASURE, VIEW_DASHBOARDS, ) return dict( COPY_MEASURE=COPY_MEASURE, CREATE_MEASURE=CREATE_MEASURE, CREATE_VERSION=CREATE_VERSION, DELETE_MEASURE=DELETE_MEASURE, MANAGE_SYSTEM=MANAGE_SYSTEM, MANAGE_USERS=MANAGE_USERS, ORDER_MEASURES=ORDER_MEASURES, PUBLISH=PUBLISH, READ=READ, UPDATE_MEASURE=UPDATE_MEASURE, VIEW_DASHBOARDS=VIEW_DASHBOARDS, get_content_security_policy=get_content_security_policy, ) return app
import views import models from application import app, db from config import config app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql://{user}:{password}@{host}/{database}'.format(**config) db.init_app(app) if __name__ == '__main__': with app.app_context(): db.create_all() app.run(port=8888)
db.session.commit() login_user(user, force=True) message="in" """ return render_template('status.html', message=message) @app.errorhandler(404) def page_not_found(e): return render_template('404.html'), 404 @app.errorhandler(500) def server_error(e): return render_template('500.html'), 500 @app.errorhandler(502) def gateway_error(e): return render_template('500.html'), 502 db.init_app(app) if __name__ == "__main__": port = int(os.environ.get("PORT", 80)) #for production app.run(host='0.0.0.0', port=port) #for dev #app.run(host='0.0.0.0', debug=True, port=5000)
def create_app(self): """Start new instance of app & initialize db""" app.config['SQLALCHEMY_DATABASE_URI'] = "sqlite://" app.config['TESTING'] = True db.init_app(app) return app