Exemplo n.º 1
0
def start():
    ROOT_PATH = os.path.dirname(os.path.realpath(__file__))
    os.environ.update({'ROOT_PATH': ROOT_PATH})
    sys.path.append(os.path.join(ROOT_PATH, 'modules'))

    # Create a logger object to log the info and debug
    LOG = logger.get_root_logger(os.environ.get('ROOT_LOGGER', 'root'),
                                 filename=os.path.join(ROOT_PATH,
                                                       'output.log'))

    # Port variable to run the server on.
    PORT = os.environ.get('PORT') or 4000

    @app.errorhandler(404)
    def not_found(error):
        """ error handler """
        LOG.error(error)
        return make_response(jsonify({'error': 'Not found'}), 404)

    @app.route('/')
    def index():
        """ static files serve """
        return send_from_directory('dist', 'index.html')

    @app.route('/<path:path>')
    def static_proxy(path):
        """ static folder serve """
        file_name = path.split('/')[-1]
        dir_name = os.path.join('dist', '/'.join(path.split('/')[:-1]))
        return send_from_directory(dir_name, file_name)

    if __name__ == '__main__':
        LOG.info('running environment: %s', os.environ.get('ENV'))
        app.run(host='0.0.0.0', port=int(PORT))  # Run the app
Exemplo n.º 2
0
 def get_logger(self):
     """ inits the logs. should only be if for whatever reason no logger has been defined """
     logger = get_root_logger(BASE_LOGGER_NAME, filename=f'log.log')
     logger.info(f"Initated logger in {self.__class__.__name__} ")
     logger.debug(f'logger debug level msg ')
     logger.info(f'logger info level msg ')
     logger.warning(f'logger warn level msg ')
     logger.error(f'logger error level msg ')
     logger.critical(f'logger critical level msg ')
     return logger
Exemplo n.º 3
0
import datetime
import json
from bson.json_util import dumps, loads
import boto3
from app.annotations import check_cognito_header, check_cognito_user
#from app.helpers import checkSimpleForeign

user_pool_id = os.environ.get('COGNITO_POOL_ID')

client_id = os.environ.get('COGNITO_CLIENT_ID') 

cognito_client = boto3.client('cognito-idp')


ROOT_PATH = os.environ.get('ROOT_PATH')
LOG = logger.get_root_logger(
    __name__, filename=os.path.join(ROOT_PATH, 'output.log'))

@jwt.unauthorized_loader
def unauthorized_response(callback):
    return jsonify({
        'message': 'Missing Authorization Header'
    }), 401



@app.route('/AlternativeAuth', methods=['POST'])
def al_auth_user():
    ''' auth endpoint '''
    data = validate_login(request.get_json())
    if data['ok']:
        data = data['data']
Exemplo n.º 4
0
import os
import sys
import requests
from flask import jsonify, request, make_response, send_from_directory

ROOT_PATH = os.path.dirname(os.path.realpath(__file__))
os.environ.update({'ROOT_PATH': ROOT_PATH})
sys.path.append(os.path.join(ROOT_PATH, 'modules'))

PUBLIC_PATH = os.path.join(ROOT_PATH, 'public')

import logger  # noqa
from app import app  # noqa

# Create a logger object to log the info and debug
LOG = logger.get_root_logger(os.environ.get('ROOT_LOGGER', 'root'),
                             filename=os.path.join(ROOT_PATH, 'output.log'))

# Port variable to run the server on.
PORT = os.environ.get('PORT')


@app.errorhandler(404)
def not_found(error):
    """ error handler """
    LOG.error(error)
    return make_response(jsonify({'error': 'Not found'}), 404)


@app.route('/')
def index():
    """ static files serve """
Exemplo n.º 5
0
    def test_tuner_model_MNIST(self):
        """ Loads a model/a few described in the tests configs & runs them to check they're valid
            Using our DigitMNIST class for now
         """
        for k, v in self.archs.items():
            LOG.info(f"Testing architecture {k}")
            model = TunerEngine(architecture_configs=v)
            model.execute()

    @property
    def archs(self):
        return self.confs["tests"]["architectures"]

    @property
    def tuner_archs(self):
        return self.confs["tests"]["tuner_archs"]


if __name__ == '__main__':
    import sys
    LOG = get_root_logger(BASE_LOGGER_NAME, filename=f'tests.log')
    LOG.debug(f'logger debug level msg ')
    LOG.info(f'logger info level msg ')
    LOG.warning(f'logger warn level msg ')
    LOG.error(f'logger error level msg ')
    LOG.critical(f'logger critical level msg ')

    argparser = ArgParser(logger=LOG)
    # we've parsed the args, so remove them so it doesn't trip up unitttest when it doesn't recognize them itself
    sys.argv[1:] = []
    unittest.main()
""" serving keras on flask webserver """

from keras.applications import imagenet_utils
from PIL import Image  # consider replacing pillow by scikit
from flask import Flask, request, jsonify
import io
from main import MainProgram
from utils import *
from logger import get_root_logger

LOG = get_root_logger(BASE_LOGGER_NAME)

app = Flask(__name__)
model = None
mp = None


############## api endpoints ##############
@app.route("/")
def home():
    LOG.info(f"/home ping... ")
    return "Welcome to the ML api (Keras)"


@app.route("/runmodel")
def run_model():
    LOG.info(f"")
    try:
        value = request.args.get("model")
    except Exception as ex:
        LOG.error(
Exemplo n.º 7
0
 def __init__(self, logger=None):
     self.LOG = logger if logger else get_root_logger(BASE_LOGGER_NAME)
     self.LOG.info(f"Parsing args in {self.__class__.__name__}")
     self.configs_file       = None
Exemplo n.º 8
0
from flask import Flask
from flask import request
import time
from logger import get_root_logger
import requests
import os

app = Flask(__name__)
NAME = os.environ["FLASK_NAME"]
# PORT = os.environ["PORT"]
PROJNAME = os.environ['COMPOSE_PROJECT_NAME']
LOG = get_root_logger("mylogger", filename=f'{NAME}.logs')
LOG.info(f'ENV VARS: {NAME} ')
# LOG.info(f'ENV VARS: {PORT} ')
LOG.info(f'Docker compose network name: {PROJNAME}')

envars = os.environ
for k, v in envars.items():
    LOG.info(f"{k} : {v}")


@app.route("/")
def home():
    try:
        value = request.args.get("foo")
    except Exception as ex:
        value = None

    LOG.info(f"{NAME} ping received with arg {value}")

    LOG.info("pinging other server.... ")
Exemplo n.º 9
0
""" index file for REST APIs using Flask """
import os
import sys
import requests
from flask import jsonify, request, make_response, send_from_directory

ROOT_PATH = os.path.dirname(os.path.realpath(__file__))
os.environ.update({'ROOT_PATH': ROOT_PATH})
sys.path.append(os.path.join(ROOT_PATH, 'app'))
PUBLIC_PATH = os.path.join(os.getcwd(), 'public')
import logger  # noqa
from app import app  # noqa

# Create a logger object to log the info and debug
LOG = logger.get_root_logger(os.environ.get('ROOT_LOGGER', 'root'),
                             filename=os.path.join(os.path.expanduser("~"),
                                                   'output.log'))

# Port variable to run the server on.
PORT = os.environ.get('PORT', '8881')


# Request on conetexts/routes which are not defined
@app.errorhandler(404)
def not_found(error):
    """ error handler """
    LOG.error(error)
    return make_response(jsonify({'error': 'Not found'}), 404)


@app.route('/')
Exemplo n.º 10
0
from app import app
from app import (
    authenticate,
    get_runs,
    get_waveform_from_cache,
    cache_waveform_request,
    wait_for_waveform,
    cache_events_request,
    update_db_new_waveform,
    update_db_new_tag,
)

CORS(app, supports_credentials=True)

LOG = logger.get_root_logger(
    os.environ.get("ROOT_LOGGER", "root"),
    filename=os.path.join(ROOT_PATH, "output.log"),
)

PORT = os.environ.get("PORT")
if not PORT:
    PORT = 4000

BOKEH_SERVER_URL = os.environ.get("BOKEH_SERVER_URL", None)
if BOKEH_SERVER_URL == None:
    BOKEH_SERVER_URL = "http://localhost:5006/bokeh-server"

# Connect to MongoDB
APP_DB_URI = os.environ.get("APP_DB_URI", None)
if APP_DB_URI == None:
    print("MongoDB Connection String Not Set")
my_db = pymongo.MongoClient(APP_DB_URI)["waveform"]
Exemplo n.º 11
0
import sys
from flask import send_from_directory
import configparser

ROOT_PATH = os.path.dirname(os.path.realpath(__file__))
os.environ.update({'ROOT_PATH': ROOT_PATH})
sys.path.append(os.path.join(ROOT_PATH, 'modules'))

config = configparser.ConfigParser()
config.read('config.ini')

# noinspection PyPep8
import logger
# noinspection PyPep8
from app import app

LOG = logger.get_root_logger(os.environ.get('ROOT_LOGGER', 'root'),
                             filename=os.path.join(
                                 ROOT_PATH, config['LOGGING']['FILENAME']))


@app.errorhandler(404)
def not_found(error):
    """ error handler """
    LOG.error(error)
    return send_from_directory('dist', '404.html')


# if __name__ == '__main__':
#     app.run()
Exemplo n.º 12
0
import sys
import os
from logger import get_root_logger

LOG = get_root_logger("default", filename="logs")

LOG.info("Hello world!")
LOG.info(
    f"LOG.infoing current os.environ values - including any set in DOckefile/compose file etc."
)
envars = os.environ
for var, value in envars.items():
    LOG.info(f"{var}: {value}")
LOG.info(f"Current working directory: {os.getcwd()}")

LOG.info(f"Listing all files & folder in working directory:")
for file_folder in os.listdir():
    LOG.info(f"{file_folder}")
Exemplo n.º 13
0
import os
from flask import request, jsonify
from app import app, mongo, flask_bcrypt, jwt
import logger
import configparser
from app.schemas.user import validate_user
from flask_jwt_extended import (create_access_token, create_refresh_token,
                                jwt_required, jwt_refresh_token_required,
                                get_jwt_identity)

config = configparser.ConfigParser()
config.read('config.ini')

ROOT_PATH = os.environ.get('ROOT_PATH')
LOG = logger.get_root_logger(__name__,
                             filename=os.path.join(
                                 ROOT_PATH, config['LOGGING']['FILENAME']))


@app.route('/user', methods=['GET', 'DELETE'])
@jwt_required
def user():
    if request.method == 'GET':
        # TODO: return all users if there was no argument specified
        # TODO: check if email address was provided in the query args
        query = request.args
        data = mongo.db.users.find_one(query)
        del data['password']
        return jsonify({'ok': True, 'data': data}), 200
    data = request.get_json()
    if request.method == 'DELETE':