Exemple #1
0
 def test_city_state(self):
     new_state = State(name="California")
     new_state.save()
     new_city = City(name="San Francisco", state=1)
     new_city.save()
     get_cities = self.app.get('/states/1/cities/1')
     assert get_cities.status_code == 200
Exemple #2
0
    def test_review_place3(self):
        # Creating a setUp
        new_state = State(name='California')
        new_state.save()
        new_city = City(name='San Francisco', state=1)
        new_city.save()
        new_place = Place(owner=1,
                          city=1,
                          name="Steven",
                          description="house",
                          number_rooms=3,
                          number_bathrooms=2,
                          max_guest=3,
                          price_by_night=100,
                          latitude=37.774929,
                          longitude=-122.419416)
        new_place.save()

        # Creating a review for a place that exist
        new_review = self.app.post('/places/1/reviews',
                                   data=dict(message="I like it",
                                             stars=5))
        assert new_review.status_code == 200

        # Checking for a review that does not exist
        new_review_get = self.app.get('/places/1/reviews/5')
        assert new_review_get.status_code == 404

        # Checking for a place that does not exist
        new_review_get = self.app.get('/places/2/reviews/2')
        assert new_review_get.status_code == 404

        # Checking for a review that does exist
        new_review_get = self.app.get('/places/1/reviews/1')
        assert new_review_get.status_code == 200
Exemple #3
0
def handle_city_id(state_id, city_id):
    '''Select the city with the id from the database and store as the variable
    `city` with a GET request method. Remove the city with this id from the
    database with a DELETE request method.

    Keyword arguments:
    state_id: The state of the city from the database.
    city_id: The id of the city from the database.
    '''
    try:
        city = City.select().where((City.id == city_id)
                                   & (City.state == state_id)).get()
    except City.DoesNotExist:
        raise jsonify(msg="There is no city with this id in this state."), 400

    if request.method == 'GET':
        return jsonify(city.to_dict())

    elif request.method == 'DELETE':
        try:
            city = City.delete().where((City.id == city_id)
                                       & (City.state == state_id))
        except City.DoesNotExist:
            raise Exception("There is no city with this id, in this state.")
        city.execute()
        return jsonify(msg="City deleted successfully."), 200
Exemple #4
0
    def test_create(self):
        """
        Test proper creation (or non-creation) of city records upon POST
        requests to API.
        """
        # test creation of city with all parameters provided in POST request

        POST_request1 = self.app.post('/states/1/cities',
                                      data=dict(name='namestring'))

        now = datetime.now().strftime('%d/%m/%Y %H:%M')

        self.assertEqual(City.get(City.id == 1).name, 'namestring')
        self.assertEqual(City.get(City.id == 1).state.id, 1)
        self.assertEqual(
            City.get(City.id == 1).created_at.strftime('%d/%m/%Y %H:%M'), now)
        self.assertEqual(
            City.get(City.id == 1).updated_at.strftime('%d/%m/%Y %H:%M'), now)

        # test creation of city in all cases of a parameter missing in POST request
        POST_request2 = self.app.post('/states/1/cities', data=dict())
        self.assertEqual(POST_request2.status[:3], '400')

        # test that city ID for sole record in database is correct
        self.assertEqual(City.select().get().id, 1)

        # test that a post request with a duplicate name value is rejected
        POST_request3 = self.app.post('/states/1/cities',
                                      data=dict(name='namestring'))

        self.assertEqual(POST_request3.status[:3], '409')
        self.assertEqual(json.loads(POST_request3.data), {
            'code': 10002,
            'msg': 'City already exists in this state'
        })
 def setUp(self):
     #connect to db and delete everyone in the users table
     PlaceBook.delete().execute()
     Place.delete().execute()
     User.delete().execute()
     City.delete().execute()
     State.delete().execute()
 def tearDown(self):
     #delete all from users
     PlaceBook.delete().execute()
     Place.delete().execute()
     User.delete().execute()
     City.delete().execute()
     State.delete().execute()
Exemple #7
0
    def test_get(self):
        """
        Test proper representation of a city record upon GET requests via city
        ID to API
        """
        # set-up for tests
        # ----------------------------------------------------------------------
        # create city record in city table; should have ID 1
        city_record = self.createCityViaPeewee()

        # test for handling of GET request for user record by user id which
        # exists
        # ----------------------------------------------------------------------
        # make GET request for record in table
        GET_request1 = self.app.get('/states/1/cities/1')
        GET_data = json.loads(GET_request1.data)

        # test that status of response is 200
        self.assertEqual(GET_request1.status[:3], '200')

        # test that values of response correctly reflect record in database
        self.assertEqual(city_record.id, GET_data['id'])
        self.assertEqual(city_record.created_at.strftime('%d/%m/%Y %H:%M'), GET_data['created_at'][:-3])
        self.assertEqual(city_record.updated_at.strftime('%d/%m/%Y %H:%M'), GET_data['updated_at'][:-3])
        self.assertEqual(City.get(City.id == 1).name, GET_data['name'])
        self.assertEqual(City.get(City.id == 1).state.id, GET_data['state_id'])

        # test for handling of GET request for city record by city id which
        # does not exist
        # ----------------------------------------------------------------------
        GET_request2 = self.app.get('/states/1/cities/1000')
        self.assertEqual(GET_request2.status[:3], '404')
Exemple #8
0
    def test_review_place2(self):
        # Creating a setUp
        new_state = State(name='California')
        new_state.save()
        new_city = City(name='San Francisco', state=1)
        new_city.save()
        new_place = Place(owner=1,
                          city=1,
                          name="Steven",
                          description="house",
                          number_rooms=3,
                          number_bathrooms=2,
                          max_guest=3,
                          price_by_night=100,
                          latitude=37.774929,
                          longitude=-122.419416)
        new_place.save()

        # Creating a review for a place that exist
        new_review = self.app.post('/places/1/reviews',
                                   data=dict(message="I like it",
                                             stars=5))
        assert new_review.status_code == 200
        # checking the review id, should be 1
        assert json.loads(new_review.data)["id"] == 1
        # Creating a review for a place that does not exist
        new_review = self.app.post('/places/3/reviews',
                                   data=dict(message="I like it",
                                             user_id=1,
                                             stars=5))
        assert new_review.status_code == 404
Exemple #9
0
def handle_city_id(state_id, city_id):
    '''Select the city with the id from the database and store as the variable
    `city` with a GET request method. Remove the city with this id from the
    database with a DELETE request method.

    Keyword arguments:
    state_id: The state of the city from the database.
    city_id: The id of the city from the database.
    '''
    try:
        city = City.select().where((City.id == city_id) &
                                   (City.state == state_id)
                                   ).get()
    except City.DoesNotExist:
        raise jsonify(msg="There is no city with this id in this state."), 400

    if request.method == 'GET':
        return jsonify(city.to_dict())

    elif request.method == 'DELETE':
        try:
            city = City.delete().where((City.id == city_id) &
                                       (City.state == state_id))
        except City.DoesNotExist:
            raise Exception("There is no city with this id, in this state.")
        city.execute()
        return jsonify(msg="City deleted successfully."), 200
Exemple #10
0
    def test_get(self):
        """
        Test proper representation of a city record upon GET requests via city
        ID to API
        """
        # set-up for tests
        # ----------------------------------------------------------------------
        # create city record in city table; should have ID 1
        city_record = self.createCityViaPeewee()

        # test for handling of GET request for user record by user id which
        # exists
        # ----------------------------------------------------------------------
        # make GET request for record in table
        GET_request1 = self.app.get('/states/1/cities/1')
        GET_data = json.loads(GET_request1.data)

        # test that status of response is 200
        self.assertEqual(GET_request1.status[:3], '200')

        # test that values of response correctly reflect record in database
        self.assertEqual(city_record.id, GET_data['id'])
        self.assertEqual(city_record.created_at.strftime('%d/%m/%Y %H:%M'),
                         GET_data['created_at'][:-3])
        self.assertEqual(city_record.updated_at.strftime('%d/%m/%Y %H:%M'),
                         GET_data['updated_at'][:-3])
        self.assertEqual(City.get(City.id == 1).name, GET_data['name'])
        self.assertEqual(City.get(City.id == 1).state.id, GET_data['state_id'])

        # test for handling of GET request for city record by city id which
        # does not exist
        # ----------------------------------------------------------------------
        GET_request2 = self.app.get('/states/1/cities/1000')
        self.assertEqual(GET_request2.status[:3], '404')
Exemple #11
0
    def setUp(self):
        # disabling logs
        logging.disable(logging.CRITICAL)
        self.app = app.test_client()
        # connecting to the database
        db.connect()
        # creating tables
        db.create_tables([User], safe=True)
        db.create_tables([State], safe=True)
        db.create_tables([City], safe=True)
        db.create_tables([Place], safe=True)
        db.create_tables([PlaceBook], safe=True)

        # Creating a setUp
        new_state = State(name='California')
        new_state.save()
        new_city = City(name='San Francisco', state=1)
        new_city.save()
        # Creating a new users
        user1 = User(first_name='Jon',
                     last_name='Snow',
                     email='jon@snow',
                     password='******')
        user1.save()
        new_place = Place(owner=1,
                          city=1,
                          name="Steven",
                          description="house",
                          number_rooms=3,
                          number_bathrooms=2,
                          max_guest=3,
                          price_by_night=100,
                          latitude=37.774929,
                          longitude=-122.419416)
        new_place.save()
Exemple #12
0
def handle_city(state_id):
    '''Returns all the cities in the state with the id passed as `state_id`
    from the database as JSON objects with a GET request, or adds a new state
    to the database with a POST request. Refer to exception rules of peewee
    `get()` method for additional explanation of how the POST request is
    handled:
    http://docs.peewee-orm.com/en/latest/peewee/api.html#SelectQuery.get
    '''
    if request.method == 'GET':
        list = ListStyle().list((City
                                 .select()
                                 .where(City.state == state_id)),
                                request)
        return jsonify(list), 200

    elif request.method == 'POST':
        try:
            City.select().where((City.name == request.form['name']) &
                                (City.state == state_id)
                                ).get()
            return jsonify(code=10002, msg="City already exists in this " +
                           "state"), 409
        except City.DoesNotExist:
            '''Check that all the required parameters are made in request.'''
            required = set(["name"]) <= set(request.values.keys())
            if required is False:
                return jsonify(msg="Missing parameter."), 400
            city = City.create(name=request.form['name'], state=state_id)
            return jsonify(city.to_dict()), 200
Exemple #13
0
def create_database():
    try:
         User.create_table()
    except peewee.OperationalError:
        pass

    try:
         State.create_table()
    except peewee.OperationalError:
        pass

    try:
         City.create_table()
    except peewee.OperationalError:
        pass

    try:
         Place.create_table()
    except peewee.OperationalError:
        pass

    try:
         PlaceBook.create_table()
    except peewee.OperationalError:
        pass

    try:
         Amenity.create_table()
    except peewee.OperationalError:
        pass

    try:
         PlaceAmenities.create_table()
    except peewee.OperationalError:
        pass
Exemple #14
0
def create_city(state_id):
    """
    Create a city with state as state_id
    """
    data = request.form
    try:
        if 'name' not in data:
            raise KeyError('name')
        city_check = City.select().join(State).where(State.id == state_id,
                                                     City.name == data['name'])
        if city_check:
            return {
                'code': 10000,
                'msg': 'City already exists in this state'
            }, 409
        new = City.create(name=data['name'], state_id=state_id)
        res = {}
        res['code'] = 201
        res['msg'] = "City was created successfully"
        return res, 201
    except KeyError as e:
        res = {}
        res['code'] = 40000
        res['msg'] = 'Missing parameters'
        return res, 400
    except Exception as error:
        response = {}
        response['code'] = 403
        response['msg'] = str(error)
        return response, 403
Exemple #15
0
def city(state_id):
    """Handle GET and POST requests to /states/<state_id>/cities route.

    Return a list of all cities in state (according to database) in the case of
    a GET request.
    Create a new city record in the given state in the database in the case of
    a POST request.
    """
    # handle GET requests:
    # --------------------------------------------------------------------------
    if request.method == 'GET':
        list = ListStyle.list(City.select().where(City.state == state_id), request)
        return jsonify(list)

    # handle POST requests:
    # --------------------------------------------------------------------------
    elif request.method == 'POST':
        try:
            record = City(name=request.form["name"], state=state_id)
            record.save()
            return jsonify(record.to_hash())

        # return 409 if city with given name already exists
        except IntegrityError:
                return json_response(
                    add_status_=False,
                    status_=409,
                    code=10002,
                    msg="City already exists in this state"
                )
Exemple #16
0
    def test_create(self):
        """
        Test proper creation (or non-creation) of city records upon POST
        requests to API.
        """
        # test creation of city with all parameters provided in POST request

        POST_request1 = self.app.post('/states/1/cities', data=dict(
            name='namestring'
        ))

        now = datetime.now().strftime('%d/%m/%Y %H:%M')

        self.assertEqual(City.get(City.id == 1).name, 'namestring')
        self.assertEqual(City.get(City.id == 1).state.id, 1)
        self.assertEqual(City.get(City.id == 1).created_at.strftime('%d/%m/%Y %H:%M'), now)
        self.assertEqual(City.get(City.id == 1).updated_at.strftime('%d/%m/%Y %H:%M'), now)

        # test creation of city in all cases of a parameter missing in POST request
        POST_request2 = self.app.post('/states/1/cities', data=dict())
        self.assertEqual(POST_request2.status[:3], '400')

        # test that city ID for sole record in database is correct
        self.assertEqual(City.select().get().id, 1)

        # test that a post request with a duplicate name value is rejected
        POST_request3 = self.app.post('/states/1/cities', data=dict(
            name='namestring'
        ))

        self.assertEqual(POST_request3.status[:3], '409')
        self.assertEqual(json.loads(POST_request3.data), {'code': 10002, 'msg': 'City already exists in this state'})
    def setUp(self):
        # disabling logs
        logging.disable(logging.CRITICAL)
        self.app = app.test_client()
        # connecting to the database
        db.connect()
        # creating tables
        db.create_tables([User], safe=True)
        db.create_tables([State], safe=True)
        db.create_tables([City], safe=True)
        db.create_tables([Place], safe=True)
        db.create_tables([PlaceBook], safe=True)

        # Creating a setUp
        new_state = State(name='California')
        new_state.save()
        new_city = City(name='San Francisco', state=1)
        new_city.save()
        # Creating a new users
        user1 = User(first_name='Jon',
                     last_name='Snow',
                     email='jon@snow',
                     password='******')
        user1.save()
        new_place = Place(owner=1,
                          city=1,
                          name="Steven",
                          description="house",
                          number_rooms=3,
                          number_bathrooms=2,
                          max_guest=3,
                          price_by_night=100,
                          latitude=37.774929,
                          longitude=-122.419416)
        new_place.save()
Exemple #18
0
def handle_city(state_id):
    '''Returns all the cities in the state with the id passed as `state_id`
    from the database as JSON objects with a GET request, or adds a new state
    to the database with a POST request. Refer to exception rules of peewee
    `get()` method for additional explanation of how the POST request is
    handled:
    http://docs.peewee-orm.com/en/latest/peewee/api.html#SelectQuery.get
    '''
    if request.method == 'GET':
        list = ListStyle().list((City.select().where(City.state == state_id)),
                                request)
        return jsonify(list), 200

    elif request.method == 'POST':
        try:
            City.select().where((City.name == request.form['name'])
                                & (City.state == state_id)).get()
            return jsonify(code=10002,
                           msg="City already exists in this " + "state"), 409
        except City.DoesNotExist:
            '''Check that all the required parameters are made in request.'''
            required = set(["name"]) <= set(request.values.keys())
            if required is False:
                return jsonify(msg="Missing parameter."), 400
            city = City.create(name=request.form['name'], state=state_id)
            return jsonify(city.to_dict()), 200
Exemple #19
0
 def tearDown(self):
     """
     Remove city table from airbnb_test database upon completion of test
     case.
     """
     # drop tables from database
     City.drop_table()
     State.drop_table()
Exemple #20
0
 def tearDown(self):
     """
     Remove city table from airbnb_test database upon completion of test
     case.
     """
     # drop tables from database
     City.drop_table()
     State.drop_table()
Exemple #21
0
 def tearDown(self):
     """Remove tables from airbnb_test database upon completion of test."""
     ReviewUser.drop_table()
     ReviewPlace.drop_table()
     Review.drop_table()
     Place.drop_table()
     City.drop_table()
     State.drop_table()
     User.drop_table()
Exemple #22
0
 def tearDown(self):
     """
     Remove place table from airbnb_test database upon completion of test
     case.
     """
     Place.drop_table()
     City.drop_table()
     State.drop_table()
     User.drop_table()
Exemple #23
0
def city_id(state_id, city_id):
    if request.method == 'GET':
        city = City.get(City.id == city_id, City.state == state_id)
        return jsonify(city.to_hash())

    elif request.method == 'DELETE':
        city = City.get(City.id == city_id, City.state == state_id)
        city.delete_instance()
        return 'City %s deleted \n' % city_id
Exemple #24
0
 def tearDown(self):
     """
     Remove place table from airbnb_test database upon completion of test
     case.
     """
     Place.drop_table()
     City.drop_table()
     State.drop_table()
     User.drop_table()
Exemple #25
0
    def createCityViaPeewee(self):
        """
        Create a city record using the API's database/Peewee models.

        createCityViaPeewee returns the Peewee object for the record. This
        method will not work if the database models are not written correctly.
        """
        record = City(name='namestring', state=1)
        record.save()
        return record
Exemple #26
0
    def createCityViaPeewee(self):
        """
        Create a city record using the API's database/Peewee models.

        createCityViaPeewee returns the Peewee object for the record. This
        method will not work if the database models are not written correctly.
        """
        record = City(name='namestring', state=1)
        record.save()
        return record
Exemple #27
0
async def get_cities():
    cities = await CityOut.from_queryset(CityModel.all())
    tasks = []
    for city in cities:
        task = asyncio.create_task(CityModel.get_current_time(city))
        tasks.append(task)

    futures = [CityModel.get_current_time(city) for city in cities]
    await asyncio.gather(*futures)
    return cities
 def tearDown(self):
     """
     Remove placebook table from airbnb_test database upon completion of
     test case.
     """
     # drop tables from database
     PlaceBook.drop_table()
     Place.drop_table()
     City.drop_table()
     State.drop_table()
     User.drop_table()
 def tearDown(self):
     """
     Remove placebook table from airbnb_test database upon completion of
     test case.
     """
     # drop tables from database
     PlaceBook.drop_table()
     Place.drop_table()
     City.drop_table()
     State.drop_table()
     User.drop_table()
Exemple #30
0
def create_new_city(state_id):
    post_data = request.values
    if 'name' in post_data:
        city_query = City.select().where(City.name == post_data['name'])
        state_query = State.select().where(State.id == state_id).get()
        if city_query.exists():
            out = {'code': 10002, 'msg': 'City already exists in this state'}
            return out, 409
        city_row = City.create(state=state_query, name=post_data['name'])
        return city_row.to_hash()
    else:
        return {"code":404, "msg":"not found"}, 404
Exemple #31
0
def create_city(id):
    data = request.form
    city_check = City.select().join(State).where(State.id == id, City.name == data['name'])
    if city_check:
        return {'code': 10002, 'msg': 'City already exists in this state'},409

    city = City(
        name = data['name'],
        state = id
    )
    city.save()
    return {'code': 201, 'msg': 'City created successfully'}, 201
    def setUp(self):
        """
        Overload def setUp(self): to create a test client of airbnb app, and
        create placebook table in airbnb_test database.
        """
        self.app = app.test_client()  # set up test client
        self.app.testing = True  # set testing to True
        logging.disable(logging.CRITICAL)  # disable logs

        # connect to airbnb_test database and create tables
        database.connect()
        database.create_tables([User, State, City, Place, PlaceBook],
                               safe=True)

        # create user record for route
        user_record = User(email='anystring',
                           password='******',
                           first_name='anystring2',
                           last_name='anystring3')
        user_record.save()

        # create state record for route
        state_record = State(name="foo-state")
        state_record.save()

        # create city record for route
        city_record = City(name="foo-city", state="1")
        city_record.save()

        # create place records for route
        place_record = Place(owner=1,
                             city=1,
                             name="foo",
                             description="foo description",
                             number_rooms=1,
                             number_bathrooms=1,
                             max_guest=1,
                             price_by_night=1,
                             latitude=20.0,
                             longitude=22.0)
        place_record.save()

        place_record2 = Place(owner=1,
                              city=1,
                              name="foo",
                              description="foo description",
                              number_rooms=1,
                              number_bathrooms=1,
                              max_guest=1,
                              price_by_night=1,
                              latitude=20.0,
                              longitude=22.0)
        place_record2.save()
Exemple #33
0
def delete_city(state_id, city_id):
    """
    Delete the given city
    Deletes the given city in the database.
    ---
    tags:
        - City
    parameters:
        -
            in: path
            name: state_id
            type: string
            required: True
            description: ID of the state
        -
            in: path
            name: city_id
            type: string
            required: True
            description: ID of the city
    responses:
        200:
            description: City deleted successfully
            schema:
                $ref: '#/definitions/delete_amenity_delete_delete_200'
        404:
            description: City was not found
        500:
            description: Request could not be processed
    """
    try:
        ''' Check if state exists '''
        query = State.select().where(State.id == state_id)
        if not query.exists():
            raise LookupError('state_id')

        ''' Check if city exists '''
        query = City.select().where(City.id == city_id)
        if not query.exists():
            raise LookupError('city_id')

        ''' Delete the city from the given state '''
        delete_city = City.delete().where(City.id == city_id, City.state == state_id)
        delete_city.execute()
        response = {}
        response['code'] = 200
        response['msg'] = "City account was deleted"
        return response, 200
    except LookupError as e:
        abort(404)
    except Exception as e:
        abort(500)
    def setUp(self):
        """
        Overload def setUp(self): to create a test client of airbnb app, and
        create placebook table in airbnb_test database.
        """
        self.app = app.test_client()        # set up test client
        self.app.testing = True             # set testing to True
        logging.disable(logging.CRITICAL)   # disable logs

        # connect to airbnb_test database and create tables
        database.connect()
        database.create_tables([User, State, City, Place, PlaceBook], safe=True)

        # create user record for route
        user_record = User( email='anystring',
                            password='******',
                            first_name='anystring2',
                            last_name='anystring3'  )
        user_record.save()

        # create state record for route
        state_record = State(name="foo-state")
        state_record.save()

        # create city record for route
        city_record = City(name="foo-city", state="1")
        city_record.save()

        # create place records for route
        place_record = Place(   owner=1,
                                city=1,
                                name="foo",
                                description="foo description",
                                number_rooms=1,
                                number_bathrooms=1,
                                max_guest=1,
                                price_by_night=1,
                                latitude=20.0,
                                longitude=22.0    )
        place_record.save()

        place_record2 = Place(  owner=1,
                                city=1,
                                name="foo",
                                description="foo description",
                                number_rooms=1,
                                number_bathrooms=1,
                                max_guest=1,
                                price_by_night=1,
                                latitude=20.0,
                                longitude=22.0    )
        place_record2.save()
Exemple #35
0
def create_city(state_id):
    """
    Create an city
    Creates an city based on post parameters.
    ---
    tags:
      - city
    parameters:
      - name: name
        in: query
        type: string
        description: name of the city to create
    responses:
      200:
        description: Success message
        schema:
          id: success_message
          properties:
            status:
              type: number
              description: status code
              default: 200
            msg:
              type: string
              description: Status message
              default: 'Success'
      400:
          description: Error message
          schema:
            id: error_message
            properties:
              status:
                type: number
                description: status code
                default: 40000
              msg:
                type: string
                description: Status message
                default: 'Missing parameters'
    """
    content = request.get_json(force=True)
    if not all(param in content.keys() for param in ["name"]):
        #ERROR
        return error_msg(400, 40000, "Missing parameters")
    try:
        city = City()
        city.name = content["name"]
        city.state = state_id
        city.save()
    except Exception as e:
        return error_msg(400, 400, "Error")
    return error_msg(200, 200, "Success")
def cities(state_id=None, city_id=None):
    
    state = None
    try:
        if state_id != None:
            state = State.get(State.id == int(state_id))
    except:
        state = None
    
    if state == None:
        return { 'code': 404, 'msg': "not found" }, 404
    
    if request.method == "GET":
        if city_id != None:
            try:
                city = City.get(City.id == int(city_id), City.state == state)
                return city.to_dict()
            except:
                pass
            return { 'code': 404, 'msg': "not found" }, 404

        return { 'data': [city.to_dict() for city in City.select().where(City.state == state)] }, 200
    
    elif request.method == "POST":
        name = request.form.get('name')

        if City.select().where(City.state == state).where(City.name == name).count() > 0:
            return { 'code': 10002, 'msg': "City already exists in this state" }, 409

        try:
            new_city = City.create(name=name, state=state)
        except IntegrityError:
           return { 'code': 10002, 'msg': "City already exists in this state" }, 409
        except Exception as e:
            raise e 
        
        return new_city.to_dict(), 201

    elif request.method == "DELETE":
        if city_id != None:
            city = None
            try:
                city = City.get(City.id == int(city_id), City.state == state)
            except:
                city = None
            
            if city != None:
                city.delete_instance()
                return {}, 200
                
        return { 'code': 404, 'msg': "not found" }, 404
Exemple #37
0
    def setUp(self):
        """
        Overload def setUp(self): to create a test client of airbnb app, and
        create review table in airbnb_test database.
        """
        self.app = app.test_client()        # set up test client
        self.app.testing = True             # set testing to True
        logging.disable(logging.CRITICAL)   # disable logs

        database.connect()                          # connect to airbnb_test db
        database.create_tables(                     # create tables
            [User, State, City, Place, Review, ReviewUser, ReviewPlace],
            safe=True
        )

        # create user record for routes
        user_record = User(
            email='anystring',
            password='******',
            first_name='anystring2',
            last_name='anystring3'
        )
        user_record.save()

        user_record2 = User(
            email='anystring-2',
            password='******',
            first_name='anystring2',
            last_name='anystring3'
        )
        user_record2.save()

        # create place records (and dependencies) for routes
        state_record = State(name='foo-statee')
        state_record.save()
        city_record = City(name='foo-city', state=1)
        city_record.save()
        place_record = Place(
            owner_id=1,
            city_id=1,
            name="foo",
            description="foo description",
            number_rooms=1,
            number_bathrooms=1,
            max_guest=1,
            price_by_night=1,
            latitude=20.0,
            longitude=22.0
        )
        place_record.save()
Exemple #38
0
def get_places_by_city(state_id, city_id):
    """
    Get all places
    List all places in the given city in the database.
    ---
    tags:
        - Place
    parameters:
        -
            name: state_id
            in: path
            type: integer
            required: True
            description: ID of the state
        -
            name: city_id
            in: path
            type: integer
            required: True
            description: ID of the city
    responses:
        200:
            description: List of all places
            schema:
                $ref: '#/definitions/get_places_get_Places'
    """
    try:
        ''' Check if the state_id exists '''
        query = State.select().where(State.id == state_id)
        if not query.exists():
            raise LookupError('state_id')

        ''' Check if the city_id exists '''
        query = City.select().where(City.id == city_id)
        if not query.exists():
            raise LookupError('city_id')

        ''' Check if the city_id is associated to the state_id '''
        city = City.get(City.id == city_id)
        query = State.select().where(State.id == city.state, State.id == state_id)
        if not query.exists():
            raise LookupError('city_id, state_id')

        ''' Return all places in the given city '''
        data = Place.select().where(Place.city == city.id)
        return ListStyle.list(data, request), 200
    except LookupError as e:
        abort(404)
    except Exception as error:
        abort(500)
Exemple #39
0
def app_cities_id(state_id, city_id):
    if request.method == "GET":
        try:
            query = City.get(City.id == city_id)
            return jsonify(query.to_dict()), 200
        except:
            return jsonify({"code": 404, "msg": "not found"}), 404

    elif request.method == "DELETE":
        try:
            query = City.get(City.id == city_id)
            query.delete_instance()
            return jsonify({"code": 200, "msg": "success"}), 200
        except:
            return jsonify({"code": 404, "msg": "not found"}), 404
Exemple #40
0
def city(state_id, city_id):
    if request.method == 'GET':
        try:
            query = City.get(City.id == city_id, City.state == state_id)
        except:
            return {"code":404, "msg":"city not found"}, 404
        return query.to_hash()
    else:
        try:
            query = City.get(City.id == city_id, City.state == state_id)
        except:
            return {"code":404, "msg":"city not found"}, 404
        out_dict = query.to_hash()
        query.delete_instance()
        return out_dict
Exemple #41
0
def create_place_by_city(state_id, city_id):
    post_data = request.values
    keys=["name", "description", "latitude", "longitude", "owner_id"]
    for key in keys:
        if key not in post_data:
            return {"code":400, "msg":"bad request, incorrect parameters"}
    try:
       city = City.get(City.id == city_id, City.state == state_id)
    except:
        return {"code":400, "msg":"bad request, city or state does not exist"}, 400

    new_place = Place.create(
        owner=int(post_data['owner_id']),
        name=post_data['name'],
        city=city.id,
        description=post_data['description'],
        latitude=float(post_data['latitude']),
        longitude=float(post_data['longitude'])
    )
    if 'number_rooms' in post_data:
        new_place.number_rooms=int(post_data['number_rooms'])
    if 'number_bathrooms' in post_data:
        new_place.number_bathrooms=int(post_data['number_bathrooms'])
    if 'max_guest' in post_data:
        new_place.max_guest=int(post_data['max_guest'])
    if 'price_by_night' in post_data:
        new_place.price_by_night=int(post_data['price_by_night'])
    new_place.save()
    return new_place.to_hash()
Exemple #42
0
def get_cities(id):
    cities = []
    query = City.select().join(State).where(State.id == id)
    for i in query:
        cities.append(i.to_hash())

    return jsonify(cities)
Exemple #43
0
def get_city(sid, id):
    try:
        city = City.get(City.id == id, City.state == sid)
    except Exception:
        return {'code': 404, 'msg': 'City not found'}, 404

    return city.to_hash(), 200
Exemple #44
0
def get_places_by_city(state_id, city_id):
    """
    Get a place with id as place_id and state with  id as state_id
    """
    city = City.get(City.id == city_id, City.state == state_id)
    data = Place.select().where(Place.city == city.id)
    return ListStyle.list(data, request), 200
Exemple #45
0
def city_id(state_id, city_id):
    """Handle GET and DELETE requests to /states/<state_id>/cities/<city_id>.

    Return a hash of the appropriate record in the case of a GET request.
    Delete appropriate record in case of DELETE request.
    """
    # check whether resource exists:
    # --------------------------------------------------------------------------
    try:
        record = City.get(City.id == city_id)

    # return 404 not found if it does not
    except City.DoesNotExist:
        return json_response(
            add_status_=False,
            status_=404,
            code=404,
            msg="not found"
        )

    # if exception does not arise:
    # --------------------------------------------------------------------------
    # handle GET requests
    if request.method == 'GET':
        return jsonify(record.to_hash())

    # handle DELETE requests
    elif request.method == "DELETE":
        record.delete_instance()
        record.save()
        return 'deleted city\n'
Exemple #46
0
def get_cities(state_id):
    if request.method == 'GET':
        cities = []
        query = (City.select(State, City).join(State).where(State.id == state_id))
        for city in query:
            cities.append(city.to_hash())
        return jsonify(cities)
Exemple #47
0
def city_id(state_id, city_id):
    """Handle GET and DELETE requests to /states/<state_id>/cities/<city_id>.

    Return a hash of the appropriate record in the case of a GET request.
    Delete appropriate record in case of DELETE request.
    """
    # check whether resource exists:
    # --------------------------------------------------------------------------
    try:
        record = City.get(City.id == city_id)

    # return 404 not found if it does not
    except City.DoesNotExist:
        return json_response(add_status_=False,
                             status_=404,
                             code=404,
                             msg="not found")

    # if exception does not arise:
    # --------------------------------------------------------------------------
    # handle GET requests
    if request.method == 'GET':
        return jsonify(record.to_hash())

    # handle DELETE requests
    elif request.method == "DELETE":
        record.delete_instance()
        record.save()
        return 'deleted city\n'
Exemple #48
0
def create_place_by_city(state_id, city_id):
    """
    Create a place with id as place_id and state with  id as state_id
    """
    data = request.form
    try:
        if 'owner_id' not in data:
            raise KeyError('owner_id')
        if 'name' not in data:
            raise KeyError('name')

        city = City.get(City.id == city_id, City.state == state_id)
        new = Place.create(
            owner=data['owner_id'],
            name=data['name'],
            city=city.id,
            description=data['description'],
            number_rooms=data['number_rooms'],
            number_bathrooms=data['number_bathrooms'],
            max_guest=data['max_guest'],
            price_by_night=data['price_by_night'],
            latitude=data['latitude'],
            longitude=data['longitude']
        )
        res = {}
        res['code'] = 201
        res['msg'] = "Place was created successfully"
        return res, 201
    except KeyError as e:
        res = {}
        res['code'] = 40000
        res['msg'] = 'Missing parameters'
        return res, 400
Exemple #49
0
def create_place_by_city(state_id, city_id):
    post_data = request.values
    keys=["name", "description", "latitude", "longitude", "owner_id"]
    for key in keys:
        if key not in post_data:
            return {"code":400, "msg":"bad request, incorrect parameters"}

    try:
        city = City.get(City.id == city_id, City.state == state_id)
    except City.DoesNotExist:
        return {"code":400, "msg":"bad request, city or state does not exist"}, 400

    place_dictionary = place_dict(
        post_data['name'],
        post_data['description'],
        post_data.get('number_rooms'),
        post_data.get('number_bathrooms'),
        post_data.get('max_guest'),
        post_data.get('price_by_night'),
        post_data['latitude'],
        post_data['longitude'],
        post_data['owner_id'],
        city.id,       
    )
    try:
        new_place = Place.create(**place_dictionary)
    except:
        return {"code":400, "msg":"Bad Request"}, 400

    return new_place.to_dict()
Exemple #50
0
def populate_database():
    """[summary]
        Endpoint to populate the database receiving json from Geek and RandomUser
    Returns:
        [json]: [return a json of geek]
    """

    fake_data_user = requests.get(
        "https://randomuser.me/api/?nat=br&results=100", timeout=10)
    fake_data_geek = requests.get(
        "https://geekhunter-recruiting.s3.amazonaws.com/code_challenge.json",
        timeout=10)
    response_user_json = fake_data_user.json()['results']
    response_geek_json = fake_data_geek.json()['candidates']

    unique_cities = []
    unique_technologies = []
    for count, item in enumerate(response_geek_json):
        experience = reformule_experience(item['experience'])
        data_city = item['city']
        if data_city not in unique_cities:
            unique_cities.append(data_city)
            city = City(name=data_city)
            db.session.add(city)

        city_id = City.query.filter(City.name == data_city).first().id
        candidate = Candidate(
            id=item['id'],
            name=response_user_json[count]['name']['first'],
            city_id=city_id,
            minimum_experience_time=experience['minimum'],
            maximum_experience_time=experience['maximum'],
            photo_url=response_user_json[count]['picture']['large'],
            accept_remote=accept_remote(count))
        for tech in item['technologies']:
            if tech['name'] not in unique_technologies:
                unique_technologies.append(tech['name'])
                technology = Technology(name=tech['name'])
                db.session.add(technology)
        db.session.add(candidate)

    db.session.commit()

    data_candidates = Candidate.query.all()
    data_technologies = Technology.query.all()

    for count, item in enumerate(data_candidates):
        if item.id == response_geek_json[count]['id']:
            for tech in response_geek_json[count]['technologies']:
                candidates_technologies = CandidateTechnology(
                    candidate_id=item.id,
                    technology_id=get_id(data_technologies, tech['name']),
                    is_main_tech=main_tech(
                        response_geek_json[count]['technologies'],
                        tech['name']))
                db.session.add(candidates_technologies)
    db.session.commit()
    return jsonify(fake_data_geek.json())
Exemple #51
0
def cities(state_id):
    if request.method == 'GET':
        try:
            query = City.select().where(City.state == state_id)

            return ListStyle.list(query, request), 200

        except City.DoesNotExist:
            return json_response(status_=404, msg="not found")

    elif request.method == 'POST':
        if "name" not in request.form:
            return json_response(status_=400,
                                 msg="missing parameters",
                                 code=40000)

        city_test = City.select().where(City.name == str(request.form["name"]),
                                        City.state == state_id)

        if city_test.wrapped_count() > 0:
            return json_response(status_=409,
                                 code=10002,
                                 msg="city already exists in this state")

        city = City(name=str(request.form["name"]), state=str(state_id))
        city.save()
        return jsonify(city.to_dict()), 201
Exemple #52
0
def app_cities(state_id):
    if request.method == "GET":
        try:
            query = City.select().where(City.state == state_id)
            return ListStyles.list(query, request), 200
        except City.DoesNotExist:
            return jsonify({"code": 404, "msg": "not found"}), 404

    elif request.method == "POST":
        if City.select().where(City.state == state_id,
                               City.name == request.form['name']).exists():
            return jsonify({
                "code": 10002,
                "msg": "City already exists in this state"
            }), 409

        new = City.create(name=str(request.form['name']), state=int(state_id))
        return jsonify(new.to_dict()), 201
Exemple #53
0
def modify_city(state_id, city_id):
    id = city_id
    try:
        if request.method == 'GET':
            list = ListStyle.list(
                City.select().where(City.id == city_id
                                    and City.state == state_id), request)
            return jsonify(list)
    except:
        return "City with id %d does not exist" % (int(id))
    if request.method == "DELETE":
        id = city_id
        try:
            get_city = City.get(City.id == id)
            get_city.delete_instance()
            return "City with id %d was deleted\n" % (int(id))
        except:
            return "City with id %d does not exist\n" % (int(id))
Exemple #54
0
def get_city(state_id, city_id):
    """
    Get a city with id as place_id and state with  id as state_id
    """
    try:
        city = City.get(City.id == city_id, City.state == state_id)
    except Exception:
        return {'code': 404, 'msg': 'City not found'}, 404
    return city.to_dict(), 200
Exemple #55
0
def view_modify_cities(state_id, city_id):
    if request.method == 'GET':
        city_list = City.select().where(City.id == city_id).where(
            City.state == state_id)

        if city_list:
            order_values = [i.to_hash() for i in city_list]
            return jsonify(order_values)

        else:
            jsonify(msg="This city does not exist in this state."), 404

    elif request.method == 'DELETE':
        city_info = City.select().where(City.id == city_id).where(
            City.state == state_id).first()
        city_info.delete_instance()
        city_info.save()

        return jsonify(msg="City has been deleted.")
Exemple #56
0
def cities_states(state_id, city_id):
    if request.method == "GET":
        try:
            query = City.get(City.id == city_id)
            return jsonify(query.to_dict()), 200

        except City.DoesNotExist:
            return json_response(status_=404, msg="not found")

    elif request.method == "DELETE":
        try:
            city = City.get(City.id == city_id)

        except City.DoesNotExist:
            return json_response(status_=404, msg="Not found")

        city.delete_instance()
        city.save()
        return json_response(status_=200, msg="City deleted")
Exemple #57
0
def delete_city(s_id, c_id):
    """
    Delete city with id as place_id and state with  id as s_id
    """
    try:
        city = City.get(City.id == c_id, City.state == s_id)
    except Exception:
        return {'code': 404, 'msg': 'City not found'}, 404
    try:
        delete_city = City.delete().where(City.id == c_id, City.state == s_id)
        delete_city.execute()
        response = {}
        response['code'] = 200
        response['msg'] = "City was deleted successfully"
        return response, 200
    except Exception:
        response = {}
        response['code'] = 403
        response['msg'] = str(error)
        return response, 403
Exemple #58
0
def city(state_id):
    """Handle GET and POST requests to /states/<state_id>/cities route.

    Return a list of all cities in state (according to database) in the case of
    a GET request.
    Create a new city record in the given state in the database in the case of
    a POST request.
    """
    # handle GET requests:
    # --------------------------------------------------------------------------
    if request.method == 'GET':
        list = []
        for record in City.select().where(City.state == state_id):
            hash = record.to_hash()
            list.append(hash)
        return jsonify(list)

    # handle POST requests:
    # --------------------------------------------------------------------------
    elif request.method == 'POST':
        try:
            record = City(name=request.form["name"], state=state_id)
            record.save()
            return jsonify(record.to_hash())

        # return 409 if city with given name already exists
        except IntegrityError:
            return json_response(add_status_=False,
                                 status_=409,
                                 code=10002,
                                 msg="City already exists in this state")
Exemple #59
0
def get_post_cities(state_id):
    if request.method == 'GET':
        city_list = City.select().where(City.state == state_id)

        if city_list:
            order_values = [i.to_hash() for i in city_list]
            return jsonify(order_values)

        else:
            return jsonify(msg="No records to display."), 404

    elif request.method == 'POST':

        check_city_name = City.select().where(
            City.name == request.form['name']).where(City.state == state_id)
        '''Check to make sure the city being added to the state is not a duplicate city'''
        if check_city_name:
            return jsonify(code=10002,
                           msg="City already exists in this state."), 409

        else:
            city = City.create(name=request.form['name'], state=state_id)
        return jsonify(city.to_hash())