assert zeeguu_core.model # ----------------- from .api import api app.register_blueprint(api) try: import flask_monitoringdashboard as dashboard dashboard.config.init_from(envvar='FLASK_MONITORING_DASHBOARD_CONFIG') from zeeguu_core.model import Session dashboard.config.get_group_by = lambda: Session.find(request=flask.request).user_id dashboard.bind(app=app) print("Started the Flask Monitoring Dashboard") except Exception as e: print("Could not install the flask_monitornig_dashboard") print(e) import traceback print(traceback.format_exc()) try: from zeeguu_api.machine_specific import machine_specific_config machine_specific_config(app) except ModuleNotFoundError as e: print("no machine specific code found")
from flask import Flask, request, jsonify import flask_monitoringdashboard as dashboard # เปิด dashboard ได้ app = Flask(__name__) dashboard.config.init_from(file='./dashboard.cfg') dashboard.bind(app) # bind(เชื่อมต่อ) กับตัว flask app @app.route('/area/circle') def circle(): radius = request.args.get('radius', type=float) area = 3.14 * (radius * radius) return_data = {"radius": radius, "area": area} return jsonify(return_data) @app.route('/area/rectangle') def rectangle(): width = request.args.get('width', type=float) height = request.args.get('height', type=float) area = width * height return_data = {"widht": width, "height": height, "area": area} return jsonify(return_data)
UPLOAD_FOLDER = './Charts' ##function to check whether file is is allowed extensions or not def allowed_file(filename): file_object = open('./flask_logs.txt', 'a+') flask_log.log(file_object, "checking if file is in correct extension") return '.' in filename and filename.rsplit( '.', 1)[1].lower() in ALLOWED_EXTENSIONS ##inintialization of flask app instance flask_log.log(file_object, "initializing flask app") app = Flask(__name__) dashboard.bind(app) app.secret_key = "secret key" app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER app.config['MAX_CONTENT_LENGTH'] = 16 * 1024 * 1024 ##loading best model flask_log.log(file_object, "Loading the best model for predictions") model = joblib.load("model.pkl") instance = predict() ##redirecting to root template @app.route('/') def upload_form(): file_object = open('./flask_logs.txt', 'a+') flask_log.log(file_object, "Entering to the first template ")
from wsgiref import simple_server from flask import Flask, request, render_template from flask import Response import os from flask_cors import CORS, cross_origin from prediction_Validation_Insertion import pred_validation from trainingModel import trainModel from training_Validation_Insertion import train_validation import flask_monitoringdashboard as dashboard from predictFromModel import prediction import json os.putenv('LANG', 'en_US.UTF-8') os.putenv('LC_ALL', 'en_US.UTF-8') app = Flask(__name__) dashboard.bind(app) CORS(app) @app.route("/", methods=['GET']) @cross_origin() def home(): return render_template('index.html') @app.route("/train", methods=['GET']) @cross_origin() def trainRouteClient(): try: #if request.json['folderPath'] is not None: #path = request.json['folderPath'] path = 'Training_Batch_Files' train_valObj = train_validation(path) #object initialization
def get_app(db_name=None, db_port=None, db_host=None, extra_config_settings={}): # pylint: disable=dangerous-default-value,too-many-locals """You may pass the name/port/host of the db if you want to deviate from the standard configs (staging/production). This is used for testing. extra_config_settings is forwarded to app.config during instantiation of Flask. """ curdir = os.path.dirname(os.path.abspath(__file__)) dev_mode = bool(os.environ.get('SC_DEV')) app = Flask(__name__) app.config.from_pyfile(os.path.join(curdir, 'config', 'public.py')) app.config.from_pyfile(os.path.join(curdir, 'config', 'private.py')) app.config.update(extra_config_settings) app.config['DEBUG'] = dev_mode # The flask app reads the database configs directly, rather than being passed them # through the env in docker. This means runserver and other debug/dev methods # aren't FULLY coupled to docker-compose. Runserver still won't work because it now expects # the db in another container on a certain port, but you can still use it for # light smoketesting. db_conf_dir = os.path.join(curdir, '..', 'docker', 'database') db_public_conf = get_headerless_conf( os.path.join(db_conf_dir, 'public.conf')) db_private_conf = get_headerless_conf( os.path.join(db_conf_dir, 'private.conf')) db_conf = {**db_public_conf, **db_private_conf} app.config['SQLALCHEMY_DATABASE_URI'] = \ 'postgresql://{user}:{password}@{host}:{port}/{database}'.format( user=db_conf['POSTGRES_USER'], password=db_conf['POSTGRES_PASSWORD'], host=db_host or db_conf['POSTGRES_HOST'], port=db_port or db_conf['POSTGRES_PORT'], database=db_name or db_conf['POSTGRES_DB']) db.init_app(app) migrate.init_app(app, db) mail.init_app(app) csrf_protect.init_app(app) from supercontest.views import register_blueprints # pylint: disable=wrong-import-position register_blueprints(app) from supercontest.models import User # pylint: disable=wrong-import-position user_manager = UserManager(app, db, User) app.jinja_env.globals['bootstrap_is_hidden_field'] = is_hidden_field_filter # pylint: disable=no-member # Make the function for displaying dates available to the templates from supercontest.core.utilities import convert_date app.jinja_env.globals['convert_date'] = convert_date # pylint: disable=no-member @app.context_processor def context_processor(): # pylint: disable=unused-variable return dict(user_manager=user_manager) # Add graphql view. from supercontest.graphql import schema # Intentionally allowing users in production to use graphiql to explore # the db because it still requires auth. To disable this in dev mode, # set graphiql=dev_mode instead of True. view = GraphQLView.as_view('graphql', schema=schema, graphiql=True) app.add_url_rule('/graphql', view_func=login_required(csrf_protect.exempt(view))) # Add the dashboard. this_dir = os.path.dirname(os.path.realpath(__file__)) fmd_cfg = os.path.join(this_dir, 'config', 'dashboard.cfg') dashboard.config.init_from(file=fmd_cfg) dashboard.bind(app) csrf_protect.exempt(dashboard.blueprint) # Add the debug toolbar. toolbar.init_app(app) return app
def create_app(test_config=None): # Create Flask app with a default config app = Flask(__name__, instance_relative_config=True) # Load test config if we are in testing mode if test_config is None: app.config.from_pyfile('config.py', silent=True) else: app.config.from_mapping(test_config) # ensure the instance folder exists try: os.makedirs(app.instance_path) except OSError: pass from lidarts.models import User, Role from lidarts.auth.forms import ExtendedLoginForm, ExtendedRegisterForm, \ ExtendedChangePasswordForm, ExtendedResetPasswordForm # Initialize Flask extensions db.init_app(app) # To overcome the disability of sqlite to alter colums of a table with app.app_context(): if db.engine.url.drivername == 'sqlite': migrate.init_app(app, db, render_as_batch=True) else: migrate.init_app(app, db) mail.init_app(app) user_datastore = SQLAlchemyUserDatastore(db, User, Role) security.init_app(app, user_datastore, login_form=ExtendedLoginForm, register_form=ExtendedRegisterForm, change_password_form=ExtendedChangePasswordForm, reset_password_form=ExtendedResetPasswordForm) origins = app.config[ 'CORS_ALLOWED_ORIGINS'] if 'CORS_ALLOWED_ORIGINS' in app.config else '*' if 'ENGINEIO_MAX_DECODE_PACKETS' in app.config: Payload.max_decode_packets = app.config['ENGINEIO_MAX_DECODE_PACKETS'] socketio.init_app( app, message_queue='redis://', async_mode='gevent', cors_allowed_origins=origins, # logger=True, engineio_logger=True, ) babelobject.init_app(app) moment.init_app(app) configure_uploads(app, avatars) patch_request_class(app, 2 * 1024 * 1024) app.json_encoder = JSONEncoder # Fixes bug: url_for generates http endpoints instead of https which causes mixed-content-errors app.wsgi_app = ReverseProxied(app.wsgi_app) # filter for jinja app.jinja_env.filters['datetime'] = format_datetime app.redis = Redis.from_url('redis://') app.task_queue = rq.Queue('lidarts-tasks', connection=app.redis) if 'DASHBOARD_ENABLED' in app.config and app.config['DASHBOARD_ENABLED']: dashboard.config.init_from( file=os.path.join(app.instance_path, 'dashboard.cfg')) dashboard.bind(app) # Load all blueprints from lidarts.generic import bp as generic_bp app.register_blueprint(generic_bp) from lidarts.game import bp as game_bp app.register_blueprint(game_bp) from lidarts.profile import bp as profile_bp app.register_blueprint(profile_bp) from lidarts.legal import bp as legal_bp app.register_blueprint(legal_bp) from lidarts.auth import bp as auth_bp app.register_blueprint(auth_bp) from lidarts.tools import bp as tools_bp app.register_blueprint(tools_bp) from lidarts.statistics import bp as statistics_bp app.register_blueprint(statistics_bp) from lidarts.generic.errors import not_found_error, internal_error app.register_error_handler(404, not_found_error) app.register_error_handler(500, internal_error) import lidarts.models import lidarts.socket.base_handler import lidarts.socket.chat_handler import lidarts.socket.X01_game_handler import lidarts.socket.public_challenge_handler return app
import shutil from flask_cors import cross_origin, CORS from TrainingModel import TrainModel from predict_from_model import Prediction from predict_from_model import Prediction_Row from training_validation_insertion import Train_Validation from prediction_validation_insertion import Predict_Validation import flask_monitoringdashboard as dashboard import json import pandas as pd os.putenv('LANG', 'en_US.UTF-8') os.putenv('LC_ALL', 'en_US.UTF-8') application = Flask(__name__) dashboard.bind(application) CORS(application) @application.route("/", methods=['GET']) @cross_origin() def home(): country_list = pd.read_csv('assets/countrylist.csv') country_list = pd.Series(country_list['0']) country_list = country_list.tolist() return render_template('index.html', country_list=country_list) @application.route("/train", methods=['POST']) @cross_origin() def trainRouteClient():
def create_app(test_config=None): # Create Flask app with a default config app = Flask(__name__, instance_relative_config=True) # Load test config if we are in testing mode if test_config is None: app.config.from_pyfile('config.py', silent=True) else: app.config.from_mapping(test_config) # ensure the instance folder exists try: os.makedirs(app.instance_path) except OSError: pass from lidarts.models import User, Role from lidarts.auth.forms import ExtendedLoginForm, ExtendedRegisterForm, \ ExtendedChangePasswordForm, ExtendedResetPasswordForm # Initialize Flask extensions db.init_app(app) migrate.init_app(app, db) mail.init_app(app) user_datastore = SQLAlchemyUserDatastore(db, User, Role) security.init_app(app, user_datastore, login_form=ExtendedLoginForm, register_form=ExtendedRegisterForm, change_password_form=ExtendedChangePasswordForm, reset_password_form=ExtendedResetPasswordForm) origins = app.config[ 'CORS_ALLOWED_ORIGINS'] if 'CORS_ALLOWED_ORIGINS' in app.config else '*' if 'ENGINEIO_MAX_DECODE_PACKETS' in app.config: Payload.max_decode_packets = app.config['ENGINEIO_MAX_DECODE_PACKETS'] socketio.init_app( app, message_queue='redis://', async_mode='gevent', cors_allowed_origins=origins, # logger=True, engineio_logger=True, ) babelobject.init_app(app) moment.init_app(app) configure_uploads(app, avatars) patch_request_class(app, 2 * 1024 * 1024) app.json_encoder = JSONEncoder # Fixes bug: url_for generates http endpoints instead of https which causes mixed-content-errors app.wsgi_app = ReverseProxied(app.wsgi_app) # filter for jinja app.jinja_env.filters['datetime'] = format_datetime app.jinja_env.globals['get_locale'] = get_locale if 'REDIS_URL' in app.config: # app.redis = Redis.from_url('redis://') # app.redis_client = StrictRedis() app.redis = StrictRedis( host=app.config['REDIS_URL'], password=app.config['REDIS_PASSWORD'], ) else: app.redis = StrictRedis.from_url('redis://') app.task_queue = rq.Queue('lidarts-tasks', connection=app.redis) # Flask-Security mails need to be sent in background @security.send_mail_task def delay_flask_security_mail(msg): app.task_queue.enqueue('lidarts.tasks.send_mail', msg) if 'DASHBOARD_ENABLED' in app.config and app.config['DASHBOARD_ENABLED']: dashboard.config.init_from( file=os.path.join(app.instance_path, 'dashboard.cfg')) def get_user_id(): return current_user.id dashboard.config.group_by = get_user_id dashboard.bind(app) # Load all blueprints from lidarts.admin import bp as admin_bp app.register_blueprint(admin_bp) from lidarts.api import bp as api_bp app.register_blueprint(api_bp) from lidarts.generic import bp as generic_bp app.register_blueprint(generic_bp) from lidarts.game import bp as game_bp app.register_blueprint(game_bp) from lidarts.profile import bp as profile_bp app.register_blueprint(profile_bp) from lidarts.legal import bp as legal_bp app.register_blueprint(legal_bp) from lidarts.auth import bp as auth_bp app.register_blueprint(auth_bp) from lidarts.tools import bp as tools_bp app.register_blueprint(tools_bp) from lidarts.statistics import bp as statistics_bp app.register_blueprint(statistics_bp) from lidarts.tournament import bp as tournament_bp app.register_blueprint(tournament_bp) from lidarts.generic.errors import not_found_error, internal_error app.register_error_handler(404, not_found_error) app.register_error_handler(500, internal_error) import lidarts.models import lidarts.socket.base_handler import lidarts.socket.chat_handler import lidarts.socket.X01_game_handler import lidarts.socket.game.cricket.cricket_game_handler import lidarts.socket.public_challenge_handler import lidarts.socket.tournament_handler import lidarts.socket.webcam_follow_handler return app