Example #1
0
    def setup_class(cls):
        cls.krakens_pool = {}
        logging.info("Initing the tests {}, let's pop the krakens".format(
            cls.__name__))
        cls.launch_all_krakens()
        instances_config_files = cls.create_dummy_json()
        i_manager.configuration_files = instances_config_files
        i_manager.initialisation()
        cls.mocks = []
        for name in cls.krakens_pool:
            priority = cls.data_sets[name].get('priority', 0)
            logging.info('instance %s has priority %s', name, priority)
            is_free = cls.data_sets[name].get('is_free', False)
            cls.mocks.append(
                mock.patch.object(i_manager.instances[name],
                                  'get_models',
                                  return_value=FakeModel(priority, is_free)))

        for m in cls.mocks:
            m.start()

        # we check that all instances are up
        for name in cls.krakens_pool:
            instance = i_manager.instances[name]
            try:
                retrying.Retrying(
                    stop_max_delay=5000,
                    wait_fixed=10,
                    retry_on_result=lambda x: not instance.is_up).call(
                        instance.init)
            except RetryError:
                logging.exception('impossible to start kraken {}'.format(name))
                assert False, 'impossible to start a kraken'

        #we block the stat manager not to send anything to rabbit mq
        def mock_publish(self, stat):
            pass

        #we don't want to initialize rabbit for test.
        def mock_init():
            pass

        StatManager.publish_request = mock_publish
        StatManager._init_rabbitmq = mock_init

        #we don't want to have anything to do with the jormun database either
        class bob:
            @classmethod
            def mock_get_token(cls, token, valid_until):
                #note, since get_from_token is a class method, we need to wrap it.
                #change that with a real mock framework
                pass

        User.get_from_token = bob.mock_get_token

        @property
        def mock_journey_order(self):
            return 'arrival_time'

        Instance.journey_order = mock_journey_order
Example #2
0
def getImageAndRunScript():
    try:
        serverImageUrl = ''
        if request.method == 'POST':
            uploadedImage = request.files['pic']
            uploadedImageName = secure_filename(uploadedImage.filename)
            uploadedImage.save(
                os.path.join(app.config['UPLOAD_FOLDER'], uploadedImageName))
            serverImageUrl = os.path.join(app.config['UPLOAD_FOLDER'],
                                          uploadedImageName)
        else:
            return jsonify({
                "error":
                "This is not a Post Method Please make a Post with image with name (pic)",
                "class": "None",
                "accuracy": "None"
            })

        modelUrl = os.getcwd() + "\\other\\trainedModel.model"
        labelUrl = os.getcwd() + "\\other\\labels.pickle"
        from other import Prediction as importedScript
        classResult, accuracyResult = importedScript.predict(
            serverImageUrl, modelUrl, labelUrl)
        return jsonify({
            "error": "Nothing",
            "class": str(classResult),
            "accuracy": str(accuracyResult)
        })
    except Exception as e:
        logging.exception(str(e))
        return jsonify({"error": str(e), "class": "None", "accuracy": "None"})
Example #3
0
def getImageAndRunScript():
    try:
        serverImageUrl = ''
        if request.method == 'POST':
            file = request.files['pic']
            filename = secure_filename(file.filename)
            file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
            serverImageUrl = os.path.join(app.config['UPLOAD_FOLDER'],
                                          filename)
        else:
            # print('false', file=sys.stderr)
            return abort(404)
        #return jsonify({"error": "Nothing"})

        modelUrl = os.getcwd() + "\\other\\trainedModel.model"
        labelUrl = os.getcwd() + "\\other\\labels.pickle"
        from other import Prediction as importedScript
        classResult, accuracyResult = importedScript.predict(
            serverImageUrl, modelUrl, labelUrl)
        return jsonify({
            "error": "Nothing",
            "class": str(classResult),
            "accuracy": str(accuracyResult)
        })
    except Exception as e:
        logging.exception(str(e))
        return jsonify({"error": str(e), "class": "None", "accuracy": "None"})
Example #4
0
def createAccount():
    try:
        # check if we got a json file
        content = request.get_json()
    except Exception as e:
        return jsonify({
            'successful': '0',
            'error': '1',
            'error_message': 'didnt receive a json file '
        })
    try:
        username = content.get('username')
        if username is None:
            return errorForCreateAccountJsonFormat(
                2, "json file doesn't have username")
        password = content.get('password')
        if password is None:
            return errorForCreateAccountJsonFormat(
                3, "json file doesn't have password")
        firstName = content.get('first_name')
        if firstName is None:
            return errorForCreateAccountJsonFormat(
                4, "json file doesn't have firstName")
        lastName = content.get('last_name')
        if lastName is None:
            return errorForCreateAccountJsonFormat(
                5, "json file doesn't have lastName")
        age = content.get('age')
        if age is None:
            return errorForCreateAccountJsonFormat(
                6, "json file doesn't have age")
        email = content.get('email')
        if email is None:
            return errorForCreateAccountJsonFormat(
                7, "json file doesn't have email")
        phone = content.get('phone')
        if phone is None:
            return errorForCreateAccountJsonFormat(
                8, "json file doesn't have phone")

        checkUserFoundinDataBase = PatientController.getPatientByUserName(
            username)
        if checkUserFoundinDataBase:
            return errorForCreateAccountJsonFormat(9, "Username already exist")
        p = Patient(username, password, firstName, lastName, age, email, phone)
        PatientController.addPatientt(p)
        return jsonify({
            'successful': '1',
            'error': '0',
            'error_message': "None"
        })
    except Exception as e:
        logging.exception(str(e))
        return jsonify({
            'successful': '0',
            'error': '99',
            'error_message': "Exception : " + str(e)
        })
Example #5
0
def get_db() -> sqlite3.Connection:
    """Connect to the application's configured database. The connection
    is unique for each request and will be reused if this is called
    again.
    """
    if 'db' not in g:
        g.db = sqlite3.connect(current_app.config['DATABASE'],
                               detect_types=sqlite3.PARSE_DECLTYPES)
        g.db.row_factory = sqlite3.Row
        try:
            init_db(g.db)
        except Exception as e:
            logging.exception(e)

    return g.db
Example #6
0
def upload(user_name):

    Brand_Name = request.form['brand']
    Cloth_Type = request.form['type']
    Size = request.form['size']
    Gender = request.form['gender']
    Original_Price = request.form['original_price']
    Rental_Price = request.form['rental_price']
    Location = request.form['location']
    Deposit = request.form['deposit']
    Available_From = date.today()

    if request.method == 'POST':
        file = request.files['file']

    file_name = str(file.filename)
    bucket_name = 'clothonfly_bucket'
    client = storage.Client()
    bucket = client.get_bucket(bucket_name)
    blob = bucket.blob(secure_filename(file.filename))
    try:
        blob.upload_from_file(file.stream)
        conn = db_connect()

        with conn.cursor() as cursor:
            cursor.execute('SELECT * from Users where User_Name = %s',
                           (user_name))
            users = cursor.fetchall()
            for user in users:
                Owner_ID = user['User_ID']

        with conn.cursor() as cursor:
            cursor.execute(
                'Insert into Inventory_Items(Brand_Name, Cloth_Type, Size, Gender, Original_Price, Rental_Price, Owner_ID, Location, Cloth_Image, Deposit, Available_From) VALUES(%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)',
                (Brand_Name, Cloth_Type, Size, Gender, Original_Price,
                 Rental_Price, Owner_ID, Location, file_name, Deposit,
                 Available_From))
        conn.commit()
        conn.close()
        return seller_home(
            user_name,
            message=
            "The item is added in inventory and will be available for renting from today."
        )

    except Exception as e:
        logging.exception(e)
        return jsonify({"success": False})
Example #7
0
def Login():

    try:
        content = request.get_json()
    except Exception as e:
        logging.exception(str(e))
        return errorForLoginJsonFormat("didnt receive a json file ")

    if content is None:
        return errorForLoginJsonFormat("didnt receive a json file ")
    username = content.get('username')
    if username is None:
        return errorForLoginJsonFormat("username is not found in json file ")
    password = content.get('password')
    if password is None:
        return errorForLoginJsonFormat("username is not found in json file ")
    CheckIfUserExist = PatientController.getPatientByUserNamepassword(
        username, password)
    if CheckIfUserExist:
        return jsonify({'user_found': '1', 'error': 'nothing'})
    else:
        return jsonify({'user_found': '0', 'error': 'nothing'})
Example #8
0
def server_error(e):
    logging.exception('An error occurred during a request.')
    return """
    An internal error occurred: <pre>{}</pre>
    See logs for full stacktrace.
    """.format(e), 500
Example #9
0
def server_error(e):
    # Log the error and stacktrace.
    logging.exception('An error occurred during a request.')
    return 'An internal error occurred.', 500
Example #10
0
def testy():
    try:
        exep = 5 / 0
    except Exception as e:
        logging.exception(str(e))
    return "zzz"