Exemple #1
0
def add_data():
    """Add sample data to the database"""
    try:
        data_json = load_json_data('landlords.json')
        for item in data_json:
            item['password'] = generate_hashed_password(item['password'])
            landlord = Landlord(**item)
            db.session.add(landlord)

        data_json = load_json_data('flats.json')
        for item in data_json:
            flat = Flat(**item)
            db.session.add(flat)

        data_json = load_json_data('tenants.json')
        for item in data_json:
            item['password'] = generate_hashed_password(item['password'])
            tenant = Tenant(**item)
            db.session.add(tenant)

        data_json = load_json_data('agreements.json')
        for item in data_json:
            item['sign_date'] = datetime.strptime(item['sign_date'],
                                                  '%d-%m-%Y').date()
            item['date_from'] = datetime.strptime(item['date_from'],
                                                  '%d-%m-%Y').date()
            item['date_to'] = datetime.strptime(item['date_to'],
                                                '%d-%m-%Y').date()
            agreement = Agreement(**item)
            db.session.add(agreement)

        data_json = load_json_data('settlements.json')
        for item in data_json:
            item['date'] = datetime.strptime(item['date'], '%d-%m-%Y').date()
            settlement = Settlement(**item)
            db.session.add(settlement)

        flat_id = 0
        for picture_name in PICTURES_LIST:
            flat_id += 1
            item = load_picture_data(flat_id, picture_name,
                                     f'Opis dla fotki {picture_name}')
            picture = Picture(**item)
            db.session.add(picture)
            copyfile(os.path.join(SAMPLES_DIR, picture_name), item['path'])

        db.session.commit()
        print('Data has been added to database')
    except Exception as exc:
        print(f'Unexpected error: {exc}')
def update_landlord_password(landlord_id: str, args: dict):
    landlord = Landlord.query.get_or_404(
        landlord_id, description=f"Landlord with id {landlord_id} not found")

    if not landlord.is_password_valid(args["current_password"]):
        abort(401, description="Invalid password")

    landlord.password = generate_hashed_password(args["new_password"])
    db.session.commit()

    return jsonify({"success": True, "data": landlord_schema.dump(landlord)})
def update_landlord_password(landlord_id: str, args: dict):
    landlord = Landlord.query.get_or_404(
        landlord_id, description=f'Landlord with id {landlord_id} not found')

    if not landlord.is_password_valid(args['current_password']):
        abort(401, description='Invalid password')

    landlord.password = generate_hashed_password(args['new_password'])
    db.session.commit()

    return jsonify({'success': True, 'data': landlord_schema.dump(landlord)})
Exemple #4
0
def update_tenant_password(id_model_tuple: tuple, args: dict, tenant_id: int):
    if id_model_tuple[1] == 'landlords':
        tenant = Tenant.query.filter(Tenant.landlord_id == id_model_tuple[0]) \
                            .filter(Tenant.id == tenant_id).first()
        if tenant is None:
            abort(404, description=f'Tenant with id {tenant_id} not found')

    if id_model_tuple[1] == 'tenants':
        if id_model_tuple[0] != tenant_id:
            abort(404, description=f'Incorrect tenant id')
        tenant = Tenant.query.get_or_404(
            tenant_id, description=f'Tenant with id {tenant_id} not found')

    if not tenant.is_password_valid(args['current_password']):
        abort(401, description='Invalid password')

    tenant.password = generate_hashed_password(args['new_password'])
    db.session.commit()

    return jsonify({'success': True, 'data': tenant_schema.dump(tenant)})
Exemple #5
0
def create_tenant(landlord_id: int, args: dict):
    if Tenant.query.filter(Tenant.identifier == args['identifier']).first():
        abort(409,
              description=
              f'Tenant with identifier {args["identifier"]} already exists')

    if Tenant.query.filter(Tenant.email == args['email']).first():
        abort(409,
              description=f'Tenant with email {args["email"]} already exists')

    args['password'] = generate_hashed_password(args['password'])

    new_tenant = Tenant(landlord_id=landlord_id, **args)
    db.session.add(new_tenant)
    db.session.commit()

    return jsonify({
        'success': True,
        'data': tenant_schema.dump(new_tenant)
    }), 201
def update_tenant_password(id_model_tuple: tuple, args: dict, tenant_id: int):
    if id_model_tuple[1] == "landlords":
        tenant = (Tenant.query.filter(
            Tenant.landlord_id == id_model_tuple[0]).filter(
                Tenant.id == tenant_id).first())
        if tenant is None:
            abort(404, description=f"Tenant with id {tenant_id} not found")

    if id_model_tuple[1] == "tenants":
        if id_model_tuple[0] != tenant_id:
            abort(404, description=f"Incorrect tenant id")
        tenant = Tenant.query.get_or_404(
            tenant_id, description=f"Tenant with id {tenant_id} not found")

    if not tenant.is_password_valid(args["current_password"]):
        abort(401, description="Invalid password")

    tenant.password = generate_hashed_password(args["new_password"])
    db.session.commit()

    return jsonify({"success": True, "data": tenant_schema.dump(tenant)})
def register_landlord(args: dict):
    if Landlord.query.filter(
            Landlord.identifier == args['identifier']).first():
        abort(409,
              description=
              f'Landlord with identifier {args["identifier"]} already exists')

    if Landlord.query.filter(Landlord.email == args['email']).first():
        abort(
            409,
            description=f'Landlord with email {args["email"]} already exists')

    args['password'] = generate_hashed_password(args['password'])

    new_landlord = Landlord(**args)
    db.session.add(new_landlord)
    db.session.commit()

    token = new_landlord.generate_jwt()

    return jsonify({'success': True, 'token': token.decode()}), 201
Exemple #8
0
def add_data():
    """Add sample data to the database and AWS S3"""
    try:
        data_json = load_json_data("landlords.json")
        for item in data_json:
            item["password"] = generate_hashed_password(item["password"])
            landlord = Landlord(**item)
            db.session.add(landlord)

        data_json = load_json_data("flats.json")
        for item in data_json:
            flat = Flat(**item)
            db.session.add(flat)

        data_json = load_json_data("tenants.json")
        for item in data_json:
            item["password"] = generate_hashed_password(item["password"])
            tenant = Tenant(**item)
            db.session.add(tenant)

        data_json = load_json_data("agreements.json")
        for item in data_json:
            item["sign_date"] = datetime.strptime(item["sign_date"],
                                                  "%d-%m-%Y").date()
            item["date_from"] = datetime.strptime(item["date_from"],
                                                  "%d-%m-%Y").date()
            item["date_to"] = datetime.strptime(item["date_to"],
                                                "%d-%m-%Y").date()
            agreement = Agreement(**item)
            db.session.add(agreement)

        data_json = load_json_data("settlements.json")
        for item in data_json:
            item["date"] = datetime.strptime(item["date"], "%d-%m-%Y").date()
            settlement = Settlement(**item)
            db.session.add(settlement)

        pictures_list = get_picture_samples()
        if pictures_list:
            bucket_name = current_app.config.get("S3_BUCKET")
            flat_id = 0

            s3 = boto3.client(
                "s3",
                aws_access_key_id=current_app.config.get("AWS_ACCESS_KEY_ID"),
                aws_secret_access_key=current_app.config.get(
                    "AWS_SECRET_ACCESS_KEY"),
            )

            for pic in pictures_list:
                flat_id += 1
                file_name = f"flat{flat_id}_{os.path.split(pic)[1]}"
                file_type = mimetypes.guess_type(pic)[0]

                s3.upload_file(
                    pic,
                    bucket_name,
                    file_name,
                    ExtraArgs={
                        "ACL": "public-read",
                        "ContentType": file_type
                    },
                )
                print(f"Uploading file {file_name} to s3 bucket {bucket_name}")

                picture = Picture(
                    name=file_name,
                    description=f"Description for {file_name}",
                    path=f"http://{bucket_name}.s3.amazonaws.com/{file_name}",
                    flat_id=flat_id,
                )
                db.session.add(picture)

        db.session.commit()
        print("Data has been added to database")
    except Exception as exc:
        print(f"Unexpected error: {exc}")