def create_app(): # Define the application object # Change to production configuration if in production if(os.environ['ENVIRONMENT'] == 'PRODUCTION'): #flask_app = Flask(__name__, static_url_path = '/makeuoft/static') flask_app = Flask(__name__) config_class=ProductionConfig() # Line for mounting the app to the /makeuoft domain """ Note: ensure that ProxyPass and ReverseProxyPass are as follows on apache config: ProxyPass /makeuoft/static ! ProxyPass /makeuoft http://127.0.0.1:8181/ ProxyPassReverse /makeuoft http://ieee.utoronto.ca/makeuoft Alias /makeuoft/static /var/www/makeuoft/public_html/static """ flask_app.wsgi_app = ReverseProxied(flask_app.wsgi_app, script_name='/mfthardware') else: flask_app = Flask(__name__) config_class=DevelopmentConfig() cors.init_app(flask_app) # Configurations taken from function argument flask_app.config.from_object(config_class) # Initialize the various models with the flask_app db.init_app(flask_app) migrate.init_app(flask_app, db) # Create a LoginManager instance login_manager.init_app(flask_app) login_manager.login_view = 'auth.login' login_manager.login_message= '' # Sample HTTP error handling @flask_app.errorhandler(404) def not_found(error): return render_template("404.html"), 404 # Import a module / component using its blueprint handler variable (mod_auth) #from application.mod_auth.controllers import mod_auth as auth_module from application.hardware_signout import hardware_signout as hs_module from application.auth import auth as auth_module from application.api import api as api_module # Register blueprint(s) - connects each module to the main flask application # app.register_blueprint(xyz_module) flask_app.register_blueprint(hs_module) flask_app.register_blueprint(auth_module) flask_app.register_blueprint(api_module) return flask_app
def create_app(config=None): app = Flask(__name__) app.config.from_object(config if config else ProductionConfig()) db.init_app(app) migrate.init_app(app, db) @app.route("/", methods=("GET", "POST")) def index(): form = sign_ins.Form() if form.validate_on_submit(): db.session.execute( sign_ins.table.insert().values(**form.data, signed_in_at=datetime.now()) ) db.session.commit() return redirect("/thank-you") return render_template("index.html.jinja2", form=form) @app.route("/data-protection") def data_protection(): return render_template("data-protection.html.jinja2") @app.route("/thank-you") def thank_you(): return render_template("success-page.html.jinja2") @app.errorhandler(500) def internal_server_error(e): return render_template("error-page.html.jinja2"), 500 app.register_error_handler(500, internal_server_error) return app
def test_production(): ''' Test production config ''' production_config = ProductionConfig() assert 'beta' in production_config.ETENGINE.keys() assert production_config.DEBUG is False assert production_config.TESTING is False
def set_app_config(app, environment: str): config_object = None if environment == "development": config_object = DevelopmentConfig() if environment == "testing": config_object = TestingConfig() if environment == "production": config_object = ProductionConfig() if config_object: app.config.from_object(config_object)
def main(args=[]): app_port = PORT if len(args)<=1 else args[1] environment = os.getenv('TUTUBO_ENV') config = ProductionConfig() if environment == "PROD" else DevelopmentConfig() app = create_app(config) print("Raising AuthServer in port", app_port) app.run(host="0.0.0.0", port=app_port)
def main(env: str = None): if env == 'prod': config = ProductionConfig() elif env == 'test': config = TestConfig() else: print("Usage: python3 deploy.py --env=prod|test") return ecs = ECS(config_obj=config) ecs.run()
def create_app(): app = Flask(__name__, instance_path=os.path.join(os.path.abspath(os.curdir), 'instance'), instance_relative_config=True) # configuration if os.path.isdir(app.instance_path) and \ os.path.isfile(os.path.join(app.instance_path, 'config.py')): # append instance folder to import search scope sys.path.append(app.instance_path) from config import ProductionConfig, DevelopmentConfig, TestingConfig if app.config['ENV'] == 'production': app.config.from_object(ProductionConfig(app)) elif app.config['ENV'] == 'development': app.config.from_object(DevelopmentConfig(app)) elif app.config['ENV'] == 'testing': app.config.from_object(TestingConfig(app)) else: raise Exception( 'FLASK_ENV only in (production, development, testing). Your FLASK_ENV is: %s' % (app.config['ENV'])) else: raise Exception( 'Copy config.py.example to %s AND rename to config.py' % (app.instance_path)) # logging import logging formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') from logging.handlers import TimedRotatingFileHandler handler = TimedRotatingFileHandler(**app.config['LOG_PARAMETERS']) handler.setLevel(app.logger.level) handler.setFormatter(formatter) app.logger.addHandler(handler) @app.route('/') def dashboard(): app.logger.info("Dashboard") return render_template('dashboard.html') @app.route('/test') def test(): return render_template('test.html') from .blueprints import maintain app.register_blueprint(maintain.bp, url_prefix='/maintain') app.logger.info("Load maintain blueprint") return app
def create_app(test_config=None): """Create and configure an instance of the Flask application.""" app = Flask(__name__) if app.config['ENV'] == "production": app.config.from_object(ProductionConfig()) elif app.config['ENV'] == "development": app.config.from_object(DevelopmentConfig()) app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False setup_app(app) return app
def create_app(): flask_app = Flask(__name__) # Change to production configuration if in production if (os.environ['ENVIRONMENT'] == 'PRODUCTION'): config_class = ProductionConfig() else: config_class = DevelopmentConfig() # Define the application object flask_app = Flask(__name__) # Configurations taken from function argument flask_app.config.from_object(config_class) # Initialize the various models with the flask_app #db.init_app(flask_app) #migrate.init_app(flask_app, db) # Create a LoginManager instance #login_manager.init_app(flask_app) #login_manager.login_view = 'auth.login' #login_manager.login_message= '' # Sample HTTP error handling @flask_app.errorhandler(404) def not_found(error): return render_template("404.html"), 404 # Setup the DASH apps from application.visualizer.layout import layout as layout from application.visualizer.callbacks import register_callbacks as register_callbacks register_dashapp(flask_app, 'Visualizer 1', 'visualizer', layout, register_callbacks) # Import a module / component using its blueprint handler variable (mod_auth) #from application.mod_auth.controllers import mod_auth as auth_module from application.home import home as home_module #from application.visualizer import dash as dash_visualizer # Register blueprint(s) - connects each module to the main flask application # app.register_blueprint(xyz_module) flask_app.register_blueprint(home_module) #flask_app.register_blueprint(auth_module) #flask_app.register_blueprint(dash_module) return flask_app
def create_app(config='production'): """ :config: can be one of ['production', 'development'], or a config object """ if isinstance(config, string_types): if config.lower().startswith('dev'): config = DevelopmentConfig() elif config.lower().startswith('prod'): config = ProductionConfig() else: raise RuntimeError("invalid `config`") app = Flask(__name__) app.config.from_object(config) if app.config.get('STATIC_FOLDER') is None: app.config['STATIC_FOLDER'] = app.static_url_path from . import main app.register_blueprint(main.bp) return app
def store_last_update(end_date): last_update = dt.strftime(end_date, DATE_FORMAT) filename.write(last_update) filename.flush() filename.close() def update_database(): """ Method called to update the database. """ update = Update() last_update = load_last_update() from_date = last_update + td(days=1) end_date = dt.now() update.update_daily_data(from_date, end_date) store_last_update(end_date) logger.info('Database EOD has been updated.') if __name__ == '__main__': config = ProductionConfig() logger.info('Start update database...') logger.info('Config type: {type}'.format(type=config.CONFIG_TYPE)) logger.info('Database URL : {url}'.format(url=config.DATABASE_URL)) settings = config.get_database_from_url(config.DATABASE_URL) initialize_database(settings) update_database()
business = data['business'] return total, business if __name__ == '__main__': from sqlalchemy import create_engine from sqlalchemy.engine.url import URL import pandas as pd df = pd.read_csv('neighbourhoods.csv') dct = dict(zip(df['neighbourhood'], df['neighbourhood_group'])) clt = YelpClient(DevelopmentConfig.yelp_api_key) url = "/businesses/yelp-san-francisco" for neighbourhood, neighbourhood_group in dct.items(): print(neighbourhood, neighbourhood_group) res = clt.get_spots( 'restaurant', neighbourhood + ' ' + neighbourhood_group + 'New York') engine = create_engine(URL(**ProductionConfig().DATABASE)) res.to_sql('yelp_restaurants', con=engine, schema='dbo', if_exists='append', index=False)
import sys import os import time import json from websocket import create_connection from weather import WeatherAPI if __name__ == "__main__": sys.path.append(os.getcwd()) from config import ProductionConfig as Config weather = WeatherAPI().get_data() if weather is not None: ws = create_connection(Config.websocket_endpoint()+"/websocket") data = weather.to_dict() data["time"] = time.strftime("%m月%M日%H時%M分") ws.send(json.dumps(data)) ws.recv() ws.close()
from math import cos, sqrt import time from tasks import * from config import ProductionConfig # from vincenty import vincenty from random import random # todo: add beast to client # beast.on click: (beast.stop) + beast.showTrack + currentBeast=this # map.on click: currentBeast.addWayPoint # waypoint.on click: currentBeast.removeWayPoint # currentBeast.on click: (beast.startMoving) + beast.hideTrack cfg = ProductionConfig() celery = Celery('kingler', broker=cfg.CELERY_BROKER_URL) celery.conf.update({ 'CELERY_RESULT_BACKEND': cfg.CELERY_RESULT_BACKEND, 'REDIS_URL': cfg.REDIS_URL }) def distance(hier, daar): lon1, lat1 = hier lon2, lat2 = daar R = 6371 # radius of the earth in km x = (lon2 - lon1) * cos(0.5 * (lat2 + lat1)) y = lat2 - lat1 d = R * sqrt(x * x + y * y) if __name__ == '__main__':
def get(self): self.render("templates/index.html", endpoint=Config.websocket_endpoint())
from flask_sqlalchemy import SQLAlchemy import json from datetime import datetime import logging from lib.ldap import cLDAP from base64 import urlsafe_b64decode from service.ldap_service import LdapUser, LdapGroup from service.ovirt_service import OvirtEngineService from config import ProductionConfig from base64 import urlsafe_b64encode from flask_httpauth import HTTPBasicAuth basic_auth = HTTPBasicAuth() application = Flask(__name__) application.config.from_object(ProductionConfig()) # enable LDAP service cLDAP(application) # enable database plugin db = SQLAlchemy(application) from domain.models import ApiUser, User @basic_auth.verify_password def verify_password(username_or_token, password): # first try to authenticate by token user = ApiUser.verify_auth_token(username_or_token) if not user:
if __name__ == '__main__': # Parse command line arguments parser = argparse.ArgumentParser( description='Import building data into database') parser.add_argument('data_directory', help='Directory containing data CSV files') parser.add_argument('sql_file', help='SQLite target file') parser.add_argument('--verbose', action='store_true', help='Turn on SQL command echo') args = parser.parse_args() # Use a testing config for echoing database commands, but change the # database URI to the target file config = ProductionConfig() config.SQLALCHEMY_DATABASE_URI = f'sqlite:///{os.path.abspath(args.sql_file)}' config.SQLALCHEMY_ECHO = True if args.verbose else False # Create app to register database app = create_app(config) # adds default user to db print('Adding admin user', flush=True) with app.app_context(): if len(Admin.query.all()) == 0: with open('data/user.json') as f: data = json.load(f) db.session.add( Admin( data['name'], data['username'],
import os from config import DevelopmentConfig, ProductionConfig from flask import Flask from flask_sqlalchemy import SQLAlchemy from flask_migrate import Migrate from flask_socketio import SocketIO, send, emit app = Flask(__name__) config = ProductionConfig() if os.environ.get( 'FLASK_ENV') == 'production' else DevelopmentConfig() app.config.from_object(config) db = SQLAlchemy(app) migrate = Migrate(app, db) socketio = SocketIO(app) from app import route, models # route.initiateManifest() # route.initiateEkspor() if __name__ == '__main__': socketio.run(app)
app = Flask(__name__, template_folder='./templates', static_folder='./static') # Config app.config.production = False app.config.development = False environment = os.getenv("ENVIRONMENT", "development") if environment == "development": from config import DevelopmentConfig app.config.from_object(DevelopmentConfig()) app.config.development = True print(f"Theater started with environment = {environment}") elif environment == "production": from config import ProductionConfig app.config.from_object(ProductionConfig()) app.config.production = True print(f"Theater started with environment = {environment}") else: raise ValueError(f'"{environment}" not valid environment.') # Extensions CORS(app) api = Api(app) db = SQLAlchemy(app) ma = Marshmallow(app) jwt = JWTManager(app) migrate = Migrate(app, db) # database models from app.models.auditorium import Auditorium
import sys import joblib sys.path.append('..') #external scripts imports for prediction purposes from src.utils import load_books, predict_sentiment, predict_toxicity, get_embedding, get_information, check_user_input_information, check_user_input_prediction #here the configurations of the Flask API are set app = Flask(__name__) #bind the API to a dashboard dashboard.bind(app) #set configurations productionconfigurations = ProductionConfig() app.config['DEBUG'] = productionconfigurations.DEBUG #load the prediction models clf_toxicity = joblib.load('../src/models/toxicity.joblib') clf_sentiment = joblib.load('../src/models/sentiment.joblib') #load the embedding and sentences of the books books_dict = load_books() # endpoint to obtain the sentiment of sentence @app.route('/get_sentiment', methods=["POST"]) def sentiment_prediction(): #get the input from the user
def create_app(): app = Flask(__name__) config = None if os.environ["FLASK_ENV"] == "production": config = ProductionConfig() elif os.environ["FLASK_ENV"] == "development": config = DevelopmentConfig() print("THIS APP IS IN DEV CONFIGURATION. DO NOT USE IN PRODUCTION.") elif os.environ["FLASK_ENV"] == "test": config = TestConfig() print("THIS APP IS IN TEST CONFIGURATION. DO NOT USE IN PRODUCTION.") elif config == None: print("NO CONFIGURATION SET.") app.config.from_object(config) db.init_app(app) migrate.init_app(app, db) login.init_app(app) mail.init_app(app) from app.scheduler_tasks.check_studies import check_studies if os.environ["FLASK_ENV"] != "test": scheduler.api_enabled = True scheduler.init_app(app) scheduler.add_job( id="check_studies_job", trigger="cron", func=check_studies, hour="*", minute=5, args=[app], ) scheduler.start() atexit.register(lambda: scheduler.shutdown(wait=False)) csrf.init_app(app) jwt.init_app(app) from app.errors import bp as errors_bp app.register_blueprint(errors_bp) app.register_blueprint(bp, url_prefix="/") from app.auth import bp as auth_bp app.register_blueprint(auth_bp, url_prefix="/auth") from app.admin import bp as admin_bp app.register_blueprint(admin_bp, url_prefix="/admin") from app.study import bp as study_bp app.register_blueprint(study_bp, url_prefix="/study") from app.responses import bp as responses_bp app.register_blueprint(responses_bp, url_prefix="/responses") from app.api import bp as api_bp app.register_blueprint(api_bp, url_prefix="/api") # from https://blog.miguelgrinberg.com/post/the-flask-mega-tutorial-part-vii-error-handling if not app.debug and not app.testing: if app.config["MAIL_SERVER"]: auth = None if app.config["MAIL_USERNAME"] or app.config["MAIL_PASSWORD"]: auth = ( app.config["MAIL_USERNAME"], app.config["MAIL_PASSWORD"], ) mail_handler = SMTPHandler( mailhost=(app.config["MAIL_SERVER"], app.config["MAIL_PORT"]), fromaddr=app.config["MAIL_USERNAME"], toaddrs=app.config["ADMIN_EMAILS"], subject="User Study Error", credentials=auth, secure=() if app.config["MAIL_USE_TLS"] else None, ) mail_handler.setLevel(logging.ERROR) app.logger.addHandler(mail_handler) if not os.path.exists("logs"): os.mkdir("logs") file_handler = RotatingFileHandler( "logs/userstudy.log", maxBytes=10240, backupCount=10 ) file_handler.setFormatter( logging.Formatter( "%(asctime)s %(levelname)s: %(message)s [in %(pathname)s:%(lineno)d]" ) ) file_handler.setLevel(logging.INFO) app.logger.addHandler(file_handler) app.logger.setLevel(logging.INFO) app.logger.info("User Study startup") return app