def setup(env): app.config.from_pyfile("config/%s.py" % env) init_engine(app.config["DATABASE_URI"]) init_db() return app
def entrypoint(debug=False, mode='app'): assert isinstance(mode, str), 'bad mode type "{}"'.format(type(mode)) assert mode in ('app', 'celery'), 'bad mode "{}"'.format(mode) app = Flask(__name__) app.debug = debug app.json_encoder = AlchemyEncoder configure_app(app) init_engine(app.config['SQLALCHEMY_DATABASE_URI']) init_db() configure_logging(debug=debug) configure_celery(app, simulation_tasks.celery) configure_celery(app, simbad_cli_task.celery) configure_celery(app, simbad_analyzer_task.celery) configure_celery(app, simbad_reports_task.celery) # register blueprints app.register_blueprint(simulation_api, url_prefix='/api/simulation') app.register_blueprint(artifact_api, url_prefix='/api/artifact') app.register_blueprint(reports_api, url_prefix='/api/reports') if mode == 'app': mark_ongoing_as_failed() return app elif mode == 'celery': return celery
def setup(config_env=None): global handlers, pool, app app.config.from_pyfile('config/config.cfg') if config_env: app.config.from_pyfile('config/config.%s.cfg' % config_env, silent=True) handlers = {} mods = filter(os.path.isfile, glob.glob(os.path.join('handlers', '*.py'))) for mod_path in mods: mod_name = os.path.splitext(os.path.split(mod_path)[-1])[0] mod = importlib.import_module('handlers.%s' % mod_name) members = inspect.getmembers(mod, inspect.isclass) if len(members) != 1: continue handlers[mod_name] = members[0][1](app.config['ARCHIVE_PATH']) print('Found module "%s"' % members[0][0]) pool = ThreadPool(5) init_engine(app.config['DATABASE_URI']) init_db() return app
def setup(env): app.config.from_pyfile('config/%s.py' % env) app.config.from_pyfile('config/%s_secret.py' % env, silent=True) init_engine(app.config['DATABASE_URI']) init_db() return app
def setup(conf_path): global app, games app.config.from_pyfile(conf_path) init_engine(app.config['DATABASE_URI']) init_db() with open('config/games.json') as data_file: games = json.load(data_file) return app
def get_app(config=None, **kwargs): """Creates a Flask application""" app = Flask(__name__, **kwargs) configure_app(app, config) init_engine(app.config['DATABASE_URI']) cache.init_app(app) configure_logging(app) return app
def init_app(): print 'init app called' db_name = os.environ['AUTH_SVC_DB_NAME'] db_user = os.environ['AUTH_SVC_DB_USER'] db_pass = os.environ['AUTH_SVC_DB_PASS'] app = Flask(__name__) app.config[ 'SQLALCHEMY_DATABASE_URI'] = 'mysql+mysqlconnector://' + db_user + ':' + db_pass + '@authentication-mariadb/' + db_name init_engine(app.config['SQLALCHEMY_DATABASE_URI']) init_db() from authentication import authentication app.register_blueprint(authentication, url_prefix='/signonservice') return app
def setup(env): global app, paypal_api, tournaments, servers, server_games servers = [] pub_conf_path = 'config/%s_config.py' % env private_conf_path = 'config/secret.%s_config.py' % env app.config.from_pyfile(pub_conf_path) # Only ignore missing config if env is 'default' app.config.from_pyfile(private_conf_path, silent=(env == 'default')) log_path = app.config['LOG_PATH'] handler = TimedRotatingFileHandler(log_path, utc=True, when='D', backupCount=365 * 2) handler.setLevel(logging.INFO) handler.setFormatter( Formatter('%(asctime)s %(levelname)s: %(message)s ' '[in %(pathname)s:%(lineno)d]')) app.logger.addHandler(handler) app.logger.info('Starting lanmomo app') init_engine(app.config['DATABASE_URI']) init_db() paypal_api = Paypal() paypal_api.configure( client_id=app.config['PAYPAL_API_ID'], client_secret=app.config['PAYPAL_API_SECRET'], mode=app.config['PAYPAL_API_MODE'], return_url='{}/pay/execute'.format(app.config['WEB_ROOT']), # TODO check cancel url cancel_url='{}/pay/cancel'.format(app.config['WEB_ROOT'])) with open('config/tournaments.json') as data_file: tournaments = json.load(data_file) with open('config/server_games.json') as data_file: server_games = json.load(data_file) if 'STAGING' in app.config: app.config['CURRENT_COMMIT'] = '!!Staging is broken!!' set_app_commit() return app
def setup(conf_path): global app, games, tournaments, paypal_api app.config.from_pyfile(conf_path) init_engine(app.config['DATABASE_URI']) init_db() paypal_api = Paypal() paypal_api.configure(client_id=app.config['PAYPAL_API_ID'], client_secret=app.config['PAYPAL_API_SECRET'], mode=app.config['PAYPAL_API_MODE'], return_url=app.config['PAYPAL_RETURN_URL'], cancel_url=app.config['PAYPAL_CANCEL_URL']) with open('config/games.json') as data_file: games = json.load(data_file) with open('config/tournaments.json') as data_file: tournaments = json.load(data_file) return app
def setUpClass(cls): """Bootstrap test environment by creating the db engine """ cls.engine = init_engine(TEST_URI) cls.connection = cls.engine.connect() cls.db_session = db_session #cls.db_session = scoped_session(sessionmaker(autocommit=False, #autoflush=False, #bind=cls.engine)) Base.query = cls.db_session.query_property() Base.metadata.create_all(cls.engine)
def setup(conf_path): global app, games, tournaments, paypal_api app.config.from_pyfile(conf_path) init_engine(app.config['DATABASE_URI']) init_db() paypal_api = Paypal() paypal_api.configure( client_id=app.config['PAYPAL_API_ID'], client_secret=app.config['PAYPAL_API_SECRET'], mode=app.config['PAYPAL_API_MODE'], return_url=app.config['PAYPAL_RETURN_URL'], cancel_url=app.config['PAYPAL_CANCEL_URL']) with open('config/games.json') as data_file: games = json.load(data_file) with open('config/tournaments.json') as data_file: tournaments = json.load(data_file) return app
def select(): global frame global finalname global full_path global file_extension Datalist = request.form.getlist("Data") x_axistitle = request.form.get("xaxis") # Database Function statement = "" for i in Datalist: statement += "`" + i + "`," # Get the colums that the user just requested db_engine = database.init_engine() frame = pd.read_sql( "SELECT " + statement[:-1] + " FROM ict1002." + finalname, db_engine.connect()) frame.index += 1 # Plot table html = frame.to_html(escape=False, table_id="dataTable", justify="center") # Reading csv/xlxs file if file_extension[1] == ".csv": df = pd.read_csv(full_path) elif file_extension[1] == ".xlsx": df = pd.read_excel(full_path) # Plotting graph tempBranches = getattr(df, x_axistitle) mainBranches = [] statementlist = statement[:-1].replace("`", '') titlelist = statementlist titlelist = titlelist.split(',') statementlist = statementlist.split(',') for x in tempBranches: mainBranches.append(x) # Plot Bar Chart bar = plotchart.plotBarChart(statementlist, mainBranches, df, titlelist, x_axistitle) # Plot Line Chart line = plotchart.plotLineChart(statementlist, mainBranches, df, titlelist, x_axistitle) # Plot Stack Chart stack = plotchart.plotStackChart(statementlist, mainBranches, df, titlelist, x_axistitle) return render_template("uploaded.html", content=html, chart=bar, line=line, stack=stack)
def create_app(uri): """ dynamically create the app """ app = Flask(__name__, static_url_path="/static", static_folder="./static") # app.config.from_pyfile(config) app.config["SQLALCHEMY_DATABASE_URI"] = uri init_engine(app.config["SQLALCHEMY_DATABASE_URI"], pool_recycle=3600) app.secret_key = "\xda\xe0\xff\xc8`\x99\x93e\xd0\xb9\x0e\xc9\xde\x84?q" "\x9e\x19\xc0\xa1\xa7\xfb\xd0\xde" login_manager.init_app(app) oauth.init_app(app) @app.teardown_appcontext def shutdown_session(exception=None): db_session.remove() @app.before_request def before_request(): g.user = current_user g.api_url = API_URL @app.errorhandler(401) def unauthorized_error_handle(error=None): """ handle all unauthorized_errors with redirect to login """ return redirect(url_for("auth.login")) import core.views import auth.views import user.views import product.views import artist.views import video.views # app.register_blueprint(landing.app) app.register_blueprint(core.views.core) app.register_blueprint(auth.views.auth, url_prefix="/auth") app.register_blueprint(user.views.user, url_prefix="/user") app.register_blueprint(product.views.product, url_prefix="/product") app.register_blueprint(artist.views.artist, url_prefix="/artist") app.register_blueprint(video.views.video, url_prefix="/video") return app
def create_app(uri): """ dynamically create the app """ app = Flask(__name__) #app.config.from_pyfile(config) app.config['SQLALCHEMY_DATABASE_URI'] = uri #init_engine(app.config['SQLALCHEMY_DATABASE_URI'], pool_recycle=3600, #echo=True) init_engine(app.config['SQLALCHEMY_DATABASE_URI'], pool_recycle=3600) @app.teardown_appcontext def shutdown_session(exception=None): db_session.remove() @app.errorhandler(400) @app.errorhandler(404) @app.errorhandler(405) @app.errorhandler(500) def default_error_handle(error=None): """ handle all errors with json output """ return jsonify(error=error.code, message=str(error), success=False),\ error.code ## add each api Blueprint and create the base route from inspired.v1.api.artists.views import artists from inspired.v1.api.product_types.views import product_types from inspired.v1.api.users.views import users from inspired.v1.api.scenes.views import scenes from inspired.v1.api.videos.views import videos from inspired.v1.api.products.views import products from inspired.v1.api.product_styles.views import product_styles app.register_blueprint(artists, url_prefix="/api/v1/artists") app.register_blueprint(product_types, url_prefix="/api/v1/product_types") app.register_blueprint(users, url_prefix="/api/v1/users") app.register_blueprint(scenes,url_prefix="/api/v1/scene") app.register_blueprint(videos, url_prefix="/api/v1/videos") app.register_blueprint(products, url_prefix="/api/v1/products") app.register_blueprint(product_styles, url_prefix="/api/v1/product_styles") return app
def setUpClass(cls): """ Bootstrap test environment by creating the db engine we can mock the other sqlalchemy models or just create them below """ cls.engine = init_engine(TEST_URI) cls.connection = cls.engine.connect() cls.db_session = db_session #cls.db_session = scoped_session(sessionmaker(autocommit=False, #autoflush=False, #bind=cls.engine)) Base.query = cls.db_session.query_property() init_models() Base.metadata.create_all(cls.engine)
def upload_file(): global finalname global full_path global file_extension uploaded_file = request.files['dataupload'] if uploaded_file.filename != '': uploaded_file.save("saved/" + uploaded_file.filename) full_path = "saved/" + uploaded_file.filename file_extension = os.path.splitext(uploaded_file.filename) size = os.path.getsize(full_path) if size >= 1048576: # 10mb return render_template("danger.html") if file_extension[1] == ".csv": raw_data = pd.read_csv(full_path) # Read data from csv spreadsheet else: raw_data = pd.read_excel(request.files.get( "dataupload")) # Read data from excel spreadsheet filename = request.files["dataupload"].filename purename = filename.split(".") finalname = purename[0].replace("-", "_") finalname = finalname.replace(" ", "") raw_data.head() print(filename) print(finalname) # Call virustotal module and return the value from virustotal resultDict = virustotal.scan(full_path) if resultDict.get("malicious") != 0: return render_template("danger.html") # If virustotal has already check before and check whether is it malicious elif resultDict.get("times_submitted") == 0: if resultDict.get("malicious") != 0: return render_template("danger.html") else: raw_data.to_sql(finalname, database.init_engine(), index=False, if_exists="replace") # Insert database # Get the column names from the database that we just inserted and populate list with it df = database.execute_select(finalname) columnlist = df['COLUMN_NAME'].tolist() return render_template("selectData.html", items=columnlist)
def setUpClass(cls): """Bootstrap test environment by creating the db engine and app """ init_models() cls.app = create_app(TEST_URI) cls.app.config['TESTING'] = True cls.app.config['CSRF_ENABLED'] = False cls.client = cls.app.test_client() #cls.engine = create_engine('sqlite:///:memory:', #connect_args={'check_same_thread':False}, #poolclass=StaticPool) cls._ctx = cls.app.test_request_context() cls._ctx.push() cls.engine = init_engine(TEST_URI) cls.connection = cls.engine.connect() cls.db_session = db_session Base.query = cls.db_session.query_property() Base.metadata.create_all(cls.engine)
__author__ = 'Will Crawford <*****@*****.**>' from flask import Flask, g from flask.ext.login import LoginManager, current_user import config from session import ItsdangerousSessionInterface from database import init_engine, db_session app = Flask(__name__.split('.')[0]) app.config.from_object(config.PycharmDev) # Toggle production/development login_manager = LoginManager() login_manager.init_app(app) login_manager.login_view = 'mods_login' app.session_interface = ItsdangerousSessionInterface() init_engine(app.config['DATABASE_URI'], convert_unicode=True) from database import db_session import views @app.before_request def before_request(): g.user = current_user #@app.teardown_request # This decorator calls this function when a request is finished. #def shutdown_session(exception=None): # db_session.remove()
import sys from database import db_session, init_db, init_engine from Student import Student init_engine("sqlite:///schooldb.sqlite") init_db() def add_user(): first_name = input("Ecrie ton first_name:") last_name = input("Ecrie ton last_name:") age = input("Ecrie ton age:") email = input("Ecrie ton email:") new_student = Student(first_name, last_name, age, email) db_session.add(new_student) db_session.commit() # db_session.delete(eleve); def remove_user(): students = Student.query.filter().all() for student in students: student.print_self() email_remove = input( "Ecrie le email de la personne que tu veut supprimer:") student_delete = None for student in students:
token = uuid.uuid4().hex user.token = token session['auth_token'] = token db_session.query(User).filter_by(id=user.id) \ .update({"token": user.token}) db_session.commit() resp = jsonify({'message': "login successful", 'token': token}) return resp return jsonify({'message': 'Bad login'}), 401 @app.teardown_appcontext def shutdown_session(exception=None): db_session.remove() if __name__ == "__main__": app.config.from_pyfile('config/config.py') if len(sys.argv) == 2: conf = sys.argv[1] print('Loading additional config %s...', conf) app.config.from_pyfile('config/' + conf + '_config.py') init_engine(app.config['DATABASE_URI']) init_db() app.run(host='0.0.0.0') session(app)
sys.path.insert(0, os.path.dirname( os.path.realpath(__file__)) + '/api') sys.path.insert(0, os.path.dirname( os.path.realpath(__file__)) + '/conf') sys.path.insert(0, os.path.dirname( os.path.realpath(__file__)) + '/db') from flask.ext.sqlalchemy import SQLAlchemy from flask import make_response, jsonify from flask.ext.bcrypt import Bcrypt from database import init_engine, db_session app = Flask(__name__) app.config.from_object('config.DevelopmentConfig') bcrypt = Bcrypt(app) init_engine(app.config['SQLALCHEMY_DATABASE_URI'], pool_recycle=3600) @app.teardown_appcontext def shutdown_session(exception=None): db_session.remove() @app.errorhandler(400) @app.errorhandler(404) @app.errorhandler(405) @app.errorhandler(500) def default_error_handle(error=None): """ handle all errors with json output """ return jsonify(error=error.code, message=str(error), success=False),\ error.code
return jsonify({'error': 'Bad request'}), 400 username = req['username'] password = req['password'] invite_code = req['invite_code'] if not verify_invite_code(invite_code): return jsonify({'error': 'Invalid invite code'}), 400 new_user(username, password) Invite.query.filter(Invite.code == invite_code).first().redeemed = True db_session.commit() return jsonify({'success': True}) @app.teardown_appcontext def shutdown_session(exception=None): db_session.remove() if __name__ == "__main__": app.config.from_pyfile('config/default_config.py') if len(sys.argv) == 2: conf = sys.argv[1] print('Loading additional config %s...', conf) app.config.from_pyfile('config/' + conf + '_config.py') init_engine(app.config['DATABASE_URI']) init_db() app.run()