def read_company(company_id):
    """Read one company's details"""
    # Read company from DB
    db = database()
    company = db[company_id]
    # Return company as JSON
    return jsonify(company)
def read_companies():
    """Read all companies"""
    # Read all companies from DB
    db = database()
    companies_list = []
    for key, value in db.items():
        companies_list.append({key: value})
    # Return company as JSON
    return jsonify(companies=companies_list)
def create_company():
    """Create a new company"""
    # Get the posted data
    company = request.get_json()
    # Insert new company into the DB
    db = database()
    db.update(company)
    # Return the newly company as JSON
    return jsonify(company), 201
def update_company(company_id):
    """Update a company"""
    # Get the company details
    company = request.get_json()
    # Update the company with id = company_id
    db = database()
    db[company_id] = company
    # Return the updated company as JSON
    return jsonify({company_id: db[company_id]})
Пример #5
0
def test_delete_object():
    db = database(DB_FILENAME)

    class Person:
        id = fields.IntegerField('id', is_pk=True)
        name = fields.TextField('name')

    db.table(Person)
    Person.objects.create(name='mike')
    assert len(Person.objects.all()) == 1
    Person.objects.delete('name="mike"')
    assert len(Person.objects.all()) == 0
Пример #6
0
def test_create_object():
    db = database(DB_FILENAME)

    class Person:
        id = fields.IntegerField('id', is_pk=True)
        name = fields.TextField('name', required=True)
        age = fields.IntegerField('age', required=False, default=20)

    db.table(Person)
    assert len(Person.objects.all()) == 0
    Person.objects.create(name='mike', age=10)
    assert len(Person.objects.all()) == 1
Пример #7
0
def test_update_object():
    db = database(DB_FILENAME)

    class Person:
        id = fields.IntegerField('id', is_pk=True)
        name = fields.TextField('name', required=False)

    db.table(Person)
    Person.objects.create(name='john')
    assert len(Person.objects.all()) == 1
    Person.objects.update('name="john"', name='mike')
    assert len(Person.objects.all()) == 1
    assert Person.objects.all()[0].name == 'mike'
Пример #8
0
def test_add_column_without_default():
    db = database(DB_FILENAME)

    class Person:
        id = fields.IntegerField('id', is_pk=True)

    db.table(Person)
    Person.name = fields.TextField('name', required=True, default=None)
    try:
        db.table(Person, update_table=True)
    except exceptions.NewColumnWithoutDefault:
        assert True
    else:
        assert False
Пример #9
0
def test_create_object_without_required_column():
    db = database(DB_FILENAME)

    class Person:
        id = fields.IntegerField('id', is_pk=True)
        name = fields.TextField('name', required=False)
        age = fields.IntegerField('age', required=True)

    db.table(Person)
    try:
        Person.objects.create(name='mike')
    except sqlite3.IntegrityError:
        assert True
    else:
        assert False
Пример #10
0
def test_add_column():
    db = database(DB_FILENAME)

    class Person:
        id = fields.IntegerField('id', is_pk=True)

    db.table(Person)
    db.cursor.execute('PRAGMA table_info(Person)')
    info = db.cursor.fetchall()
    assert len(info) == 1
    Person.name = fields.TextField('name', required=False)
    db.table(Person, update_table=True)
    db.cursor.execute('PRAGMA table_info(Person)')
    info = db.cursor.fetchall()
    assert len(info) == 2
Пример #11
0
def read_companies():
    """
    Read all companies' details
    """
    # Get the companies collection
    company_collection = database()

    # Get all companies' documents and assemble a list of company dictionaries
    companies_cursor = company_collection.find({})

    companies_list = [{key: value
                       for key, value in company.items()}
                      for company in companies_cursor]

    # Read from DB and return
    return jsonify(companies=companies_list)
Пример #12
0
def test_create_table():
    db = database(DB_FILENAME)

    class Person:
        id = fields.IntegerField('id', is_pk=True)
        name = fields.TextField('name', required=True)
        age = fields.IntegerField('age', required=True)
        money = fields.RealField('money', required=False, default=0.0)
        item_amount = fields.IntegerField('i_amount',
                                          required=True,
                                          default=100)

    db.table(Person)
    assert hasattr(Person, 'objects') == True
    db.cursor.execute('PRAGMA table_info(Person)')
    info = db.cursor.fetchall()
    assert len(info) == 5
    names = [item[1] for item in info]
    assert 'id' in names
    assert 'name' in names
    assert 'age' in names
    assert 'money' in names
    assert 'i_amount' in names
    types = [item[2] for item in info]
    assert 'integer' == types[0].lower()
    assert 'text' == types[1].lower()
    assert 'integer' == types[2].lower()
    assert 'real' == types[3].lower()
    assert 'integer' == types[4].lower()
    notnulls = [item[3] for item in info]
    assert notnulls[0] == 0
    assert notnulls[1] == 1
    assert notnulls[2] == 1
    assert notnulls[3] == 0
    assert notnulls[4] == 1
    defaults = [item[4] for item in info]
    assert defaults[0] == None
    assert defaults[1] == None
    assert defaults[2] == None
    assert defaults[3] == str(0.0)
    assert defaults[4] == str(100)
    is_pks = [item[5] for item in info]
    assert is_pks[0] == 1
    assert is_pks[1] == 0
    assert is_pks[2] == 0
    assert is_pks[3] == 0
    assert is_pks[4] == 0
Пример #13
0
def check_and_insert(company):
    """
    Inserts the supplied company record if it doesnt already exists
    """
    # Get the companies collection from the database
    company_collection = database()

    # Check if a company document already exists with the id provided and throw HTTP error if so
    company_in_db = company_collection.find_one({'_id': company['_id']},
                                                {'_id': 0})
    if company_in_db:
        conflict_msg = f"Company with id '{company['_id']}' already exists in the database."
        abort(make_response(jsonify(message=conflict_msg),
                            HTTPStatus.CONFLICT))

    # Insert the posted company json body as a document in the database
    company_collection.insert_one(company)
Пример #14
0
def read_company(company_id):
    """
    Read one company's details
    """
    # Get the companies collection from the database
    company_collection = database()

    # Get the document for the company with the specified id
    company = company_collection.find_one({'_id': company_id}, {'_id': 0})

    # Throw the appropriate error if the company id was not found
    if not company:
        not_found_msg = f"Company with id '{company_id}' does not exist in the database."
        abort(
            make_response(jsonify(message=not_found_msg),
                          HTTPStatus.NOT_FOUND))

    # Return company as JSON
    return jsonify(company)
Пример #15
0
def test_update_delete_unexisting_row():
    db = database(DB_FILENAME)

    class Person:
        id = fields.IntegerField('id', is_pk=True)
        name = fields.TextField('name')

    db.table(Person)
    try:
        Person.objects.update('id=1', name='mike')
    except exceptions.DoesNotExists:
        assert True
    else:
        assert False
    try:
        Person.objects.delete('id=1')
    except exceptions.DoesNotExists:
        assert True
    else:
        assert False
Пример #16
0
def delete_company(company_id):
    """
    Deletes the company document associated with the specified company id
    """
    # Get the companies collection from the database
    company_collection = database()

    # Delete the company document
    deleted_company_document = company_collection.find_one_and_delete(
        {'_id': company_id})

    # Throw the appropriate error if the company id isn't found
    if not deleted_company_document:
        not_found_msg = f"Company with id '{company_id}' does not exist in the database."
        abort(
            make_response(jsonify(message=not_found_msg),
                          HTTPStatus.NOT_FOUND))

    # Return the deleted company document as JSON
    return jsonify(deleted_company_document), HTTPStatus.OK
Пример #17
0
def update_company(company_id):
    """
    Updates the document of an existing company; only updates fields specified in json body
    """
    # Get the posted data
    company_json = request.get_json()

    # Get the companies collection from the database
    company_collection = database()

    # Update the company document in the database
    updated_company_document = company_collection.find_one_and_update(
        {'_id': company_id}, {'$set': company_json},
        return_document=ReturnDocument.AFTER)

    # Throw the appropriate error if the company id isn't found
    if not updated_company_document:
        not_found_msg = f"Company with id '{company_id}' does not exist in the database."
        abort(
            make_response(jsonify(message=not_found_msg),
                          HTTPStatus.NOT_FOUND))

    # Return the updated company as JSON
    return jsonify(updated_company_document), HTTPStatus.OK