Example #1
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
Example #2
0
def states():
    if request.method == 'GET':
        #get list states
        states_list = []
        states = State.select()
        for state in states:
            states_list.append(state.to_hash())
        return jsonify(states_list)

    elif request.method == 'POST':
        #create new state
        post_name = request.form['name']
        states = State.select()
        for state in states:
            if state.name == post_name:
                message = {
                    'code': 10001,
                    'msg': 'State already exists',
                }
                res = jsonify(message)
                res.status_code = 409
                return res
        else:
            new_state = State.create(name=post_name)
            return jsonify(new_state.to_hash())
Example #3
0
def handle_states():
    '''Returns all the states 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(State.select(), request)
        return jsonify(list), 200

    elif request.method == 'POST':
        params = request.values

        '''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

        try:
            State.select().where(State.name == request.form['name']).get()
            return jsonify(code=10001, msg="State already exists"), 409
        except State.DoesNotExist:
            state = State.create(name=request.form['name'])
            return jsonify(state.to_dict()), 201
Example #4
0
 def tearDown(self):
     #delete all from users
     PlaceBook.delete().execute()
     Place.delete().execute()
     User.delete().execute()
     City.delete().execute()
     State.delete().execute()
Example #5
0
def handle_state_id(state_id):
    '''Select the state with the id from the database and store as the variable
    `state` with a GET request method. Update the data of the particular state
    with a PUT request method. This will take the parameters passed and update
    only those values. Remove the state with this id from the database with
    a DELETE request method.

    Keyword arguments:
    state_id: The id of the state from the database.
    '''
    try:
        state = State.select().where(State.id == state_id).get()
    except State.DoesNotExist:
        return jsonify(msg="There is no state with this id."), 404

    if request.method == 'GET':
        return jsonify(state.to_dict()), 200

    elif request.method == 'DELETE':
        try:
            state = State.delete().where(State.id == state_id)
        except State.DoesNotExist:
            raise Exception("There is no state with this id.")
        state.execute()
        return jsonify(msg="State deleted successfully."), 200
Example #6
0
def places_in_state(state_id):
    try:
        State.get(State.id == state_id)
    except State.DoesNotExist:
        return jsonify({'code': 404, 'msg': "State does not exist in the database"}), 404
    query = Place.select().join(City).join(State).where(State.id == state_id)
    return ListStyles.list(query, request), 200
Example #7
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()
Example #8
0
 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()
Example #9
0
def create_state():
    """
    Create a state
    """
    data = request.form
    try:
        if 'name' not in data:
            raise KeyError('name')

        state_check = State.select().where(State.name == data['name'])
        new = State.create(name=data['name'])
        res = {}
        res['code'] = 201
        res['msg'] = "State was created successfully"
        return res, 201
    except KeyError as e:
        response = {}
        response['code'] = 40000
        response['msg'] = 'Missing parameters'
        return response, 400
    except Exception as e:
        response = {}
        response['code'] = 10001
        response['msg'] = "State already exists"
        return response, 409
Example #10
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
Example #11
0
def handle_state_id(state_id):
    '''Select the state with the id from the database and store as the variable
    `state` with a GET request method. Update the data of the particular state
    with a PUT request method. This will take the parameters passed and update
    only those values. Remove the state with this id from the database with
    a DELETE request method.

    Keyword arguments:
    state_id: The id of the state from the database.
    '''
    try:
        state = State.select().where(State.id == state_id).get()
    except State.DoesNotExist:
        return jsonify(msg="There is no state with this id."), 404

    if request.method == 'GET':
        return jsonify(state.to_dict()), 200

    elif request.method == 'DELETE':
        try:
            state = State.delete().where(State.id == state_id)
        except State.DoesNotExist:
            raise Exception("There is no state with this id.")
        state.execute()
        return jsonify(msg="State deleted successfully."), 200
Example #12
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()
Example #13
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
Example #14
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
Example #15
0
def states():
    """Handle GET and POST requests to /states route.

     Return a list of all states in the database in the case of a GET request.
     Create a new state in the database in the case of a POST request
    """
    # handle GET requests:
    # --------------------------------------------------------------------------
    if request.method == 'GET':
        list = ListStyle.list(State.select(), request)
        return jsonify(list)

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

        # return 409 state with given name already exists
        except IntegrityError:
                return json_response(
                    add_status_=False,
                    status_=409,
                    code=10001,
                    msg="State already exists"
                )
Example #16
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()
Example #17
0
def MakeState(state_id, state_name, region, is_state, all_states, futures):
    state = State.get_by_id(state_id) or State(id=state_id)
    state.name = state_name
    state.region = region.key
    state.is_state = is_state
    futures.append(state.put_async())
    all_states[state_id] = state
    return state
Example #18
0
def del_state(id):
    id_check = State.select().where(State.id == id)
    if not id_check:
        return {'code': 404, 'msg': 'State not found'}, 404

    item = State.delete().where(State.id == id)
    item.execute()
    return {'code': 200, 'msg': 'Deleted successfully'}, 200
Example #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()
Example #20
0
def get_state(state_id):
    """
    Get the given state
    Returns the given state in the database.
    ---
    tags:
    	- State
    parameters:
    	-
    		in: path
    		name: state_id
    		type: integer
    		required: True
    		description: ID of the state
    responses:
        200:
            description: State returned successfully
            schema:
                id: State
                required:
                    - name
                    - id
                    - created_at
                    - updated_at
                properties:
                    name:
                        type: string
                        description: name of the given state
                        default: None
                    id:
                        type: integer
                        description: id of the state
                        default: 1
                    created_at:
                        type: datetime string
                        description: date and time the state was created in the database
                        default: '2016-08-11 20:30:38'
                    updated_at:
                        type: datetime string
                        description: date and time the state was updated in the database
                        default: '2016-08-11 20:30:38'
        404:
            description: State was not found
        500:
            description: Request could not be processed
    """
    try:
        ''' Check that state_id exists '''
        query = State.select().where(State.id == state_id)
        if not query.exists():
            raise LookupError('state_id')

        state = State.get(State.id == state_id)
        return state.to_dict(), 200
    except LookupError as e:
        abort(404)
    except Exception as e:
        abort(500)
Example #21
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()
Example #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()
Example #23
0
def create_state():
    data = request.form
    name_check = State.select().where(State.name == data['name'])
    if name_check:
        return {'code': 10001, 'msg': 'State already exists'}, 409
    state = State.create(
        name = data['name']
    )
    return {'code': 201,'msg': 'State was created successfully'}, 201
Example #24
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()
Example #25
0
    def createStateViaPeewee(self):
        """
        Create a state record using the API's database/Peewee models.

        createStateViaPeewee returns the Peewee object for the record. This
        method will not work if the database models are not written correctly.
        """
        record = State(name='namestring')
        record.save()
        return record
Example #26
0
def modify_state(state_id):
    state = State.get(State.id == state_id)

    if request.method == "GET":
        return jsonify(state.to_hash())

    elif request.method == 'DELETE':
        state_info = State.get(State.id == state_id)
        state_info.delete_instance()
        state_info.save()
        return jsonify(msg="State deleted")
Example #27
0
def state_id(state_id):
    if request.method == 'GET':
        #get state from state_id
        state = State.get(State.id == state_id)
        return jsonify(state.to_hash())

    elif request.method == 'DELETE':
        #delete state with id state_id
        state = State.get(State.id == state_id)
        state.delete_instance()
        return 'State %s deleted \n' % state_id
Example #28
0
 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()
Example #29
0
 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()
Example #30
0
def state(number):
    if request.method == 'GET':
        query = State.get(State.id == number)
        return query.to_hash()
    else:
        try:
            query = State.select().where(State.id == number).get()
        except:
            return {'code':404, 'msg':'state not found'}, 404
        out_json = query.to_hash()
        query.delete_instance()
        return out_json
Example #31
0
    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()
Example #32
0
    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()
Example #33
0
def create_new_state():
    post_data = request.values
    if 'name' not in post_data:
        return {'code':400, 'msg':'bad request'}, 400
    state_query = State.select().where(State.name == post_data['name'])
    if state_query.exists():
        out = {'code': 10001, 'msg': 'State already exists'}
        return out, 409
    try:
        state_row = State.create(name=post_data['name'])
        return state_row.to_hash()
    except:
        return {'code':500, 'msg':'database connection error'}, 500
Example #34
0
def create_state():
    """
    Create a state
    Creates a state based on post parameters.
    ---
    tags:
      - state
    parameters:
      - name: name
        in: query
        type: string
        description: name of the state 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:
        state = State()
        state.name = content["name"]
        state.save()
    except Exception as e:
        return error_msg(400, 400, "Error")
    return error_msg(200, 200, "Success")
Example #35
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)
Example #36
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()
Example #37
0
def app_states():
    if request.method == "GET":
        try:
            query = State.select()
            return ListStyles.list(query, request), 200
        except State.DoesNotExist:
            return jsonify({"code": 404, "msg": "No tables exist yet"}), 404

    elif request.method == "POST":
        try:
            new = State.create(name=str(request.form['name']))
            return jsonify(new.to_dict()), 201
        except:
            return jsonify({"code": 10001, "msg": "State already exists"}), 409
Example #38
0
def app_states_id(state_id):
    if request.method == "GET":
        try:
            query = State.get(State.id == state_id)
            return jsonify(query.to_dict()), 200
        except:
            return jsonify({"code": 404, "msg": "not found"}), 404

    elif request.method == "DELETE":
        try:
            query = State.get(State.id == state_id)
            query.delete_instance()
            return jsonify({"code": 200, "msg": "success"}), 200
        except:
            return jsonify({"code": 404, "msg": "not found"}), 404
Example #39
0
def regional():
    with client.context():
        year = datetime.date.today().year

        championships = Championship.query(
            ndb.AND(Championship.year == year,
                    Championship.region != None)).fetch()
        competitions = ndb.get_multi([c.competition for c in championships])

        states = State.query().fetch()
        regions = Region.query().order(Region.name).fetch()

        championships.sort(
            key=lambda championship: championship.competition.get().start_date)
        championship_regions = [
            championship.region for championship in championships
        ]
        regions_missing_championships = [
            region for region in regions
            if region.key not in championship_regions
        ]

        return render_template(
            'regional.html',
            c=common.Common(wca_disclaimer=True),
            year=year,
            championships=championships,
            regions_missing_championships=regions_missing_championships)
Example #40
0
def edit_championships():
    with client.context():
        me = auth.user()
        if not me or not me.HasAnyRole(Roles.AdminRoles()):
            abort(403)

        all_us_competitions = (Competition.query(
            Competition.country == ndb.Key(Country, 'USA')).order(
                Competition.name).fetch())

        national_championships = (Championship.query(
            Championship.national_championship == True).order(
                -Championship.year).fetch())
        regional_championships = (Championship.query(
            Championship.region != None).order(
                Championship.region).order(-Championship.year).fetch())
        state_championships = (Championship.query(
            Championship.state != None).order(
                Championship.state).order(-Championship.year).fetch())

        states = State.query().fetch()
        regions = Region.query().fetch()

        return render_template('admin/edit_championships.html',
                               c=common.Common(),
                               all_us_competitions=all_us_competitions,
                               national_championships=national_championships,
                               regional_championships=regional_championships,
                               state_championships=state_championships,
                               states=states,
                               regions=regions)
Example #41
0
def state_id(state_id):
    """Handle GET and DELETE requests to /states/<state_id> route.

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

    # return 404 not found if it does not
    except State.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 state\n'
Example #42
0
def get_states():
    if request.method == 'GET':
        states = []
        query = State.select()
        for state in query:
            states.append(state.to_hash())
        return jsonify(states)
Example #43
0
def get_state(id):
    try:
        state = State.get(State.id == id)
    except Exception as e:
        return {'code': 404, 'msg': "State not found"}, 404

    return state.to_hash(), 200
Example #44
0
    def ParseFromDict(self, row):
        self.start_date = datetime.date(int(row['year']), int(row['month']),
                                        int(row['day']))
        self.end_date = datetime.date(int(row['year']), int(row['endMonth']),
                                      int(row['endDay']))
        self.year = int(row['year'])

        self.name = row['name']
        self.short_name = row['cellName']

        self.events = [
            ndb.Key(Event, event_id)
            for event_id in row['eventSpecs'].split(' ')
        ]

        self.latitude = int(row['latitude'])
        self.longitude = int(row['longitude'])

        state = None
        if ',' in row['cityName']:
            city_split = row['cityName'].split(',')
            state_name = city_split[-1].strip()
            state = State.get_state(state_name)
            self.city_name = ','.join(city_split[:-1])
        if state:
            self.state = state.key
        else:
            self.city_name = row['cityName']
        self.country = ndb.Key(Country, row['countryId'])
Example #45
0
    def setUp(self):
        """
        Overload def setUp(self): to create a test client of airbnb app, and
        create city 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 db and create tables
        database.connect()
        database.create_tables([State, City], safe=True)

        # create state record for route
        state_record = State(name='namestring')
        state_record.save()
Example #46
0
def state_id(state_id):
    """Handle GET and DELETE requests to /states/<state_id> route.

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

    # return 404 not found if it does not
    except State.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 state\n'
Example #47
0
def list_of_states():
    if request.method == 'GET':
        list = ListStyle.list(State.select(), request)
        return jsonify(list)

    if request.method == 'POST':
        # name_state = request.form['name']
        try:
            new_state = State(name=request.form['name'])
            # saving the changes
            new_state.save()
            # returning the new information in hash form
            return "New State entered! -> %s\n" % (new_state.name)
        except:
            return make_response(jsonify({'code': 10000,
                                          'msg': 'State already exist'}), 409)
Example #48
0
    def setUp(self):
        """
        Overload def setUp(self): to create a test client of airbnb app, and
        create city 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 db and create tables
        database.connect()
        database.create_tables([State, City], safe=True)

        # create state record for route
        state_record = State(name='namestring')
        state_record.save()
Example #49
0
def handle_place_state_id(state_id):
    '''Retrieve all the places with a state of that passed in the URL.

    Keyword arguments:
    state_id -- The id of the state that this place belongs.
    '''
    if request.method == 'GET':
        try:
            State.select().where(State.id == state_id).get()
        except State.DoesNotExist:
            return jsonify("No state exists with this id."), 400

        list = ListStyle().list((Place.select().join(City).join(State).where(
            State.id == state_id)), request)

        return jsonify(list), 200
Example #50
0
def get_states():
    """
    Get all states
    List all states in the database.
    ---
    tags:
        - State
    responses:
        200:
            description: List of all states
            schema:
                id: States
                required:
                    - data
                    - paging
                properties:
                    data:
                        type: array
                        description: states array
                        items:
                            $ref: '#/definitions/get_state_get_State'
                    paging:
                        description: pagination
                        schema:
                            $ref: '#/definitions/get_amenities_get_Paging'
    """
    try:
        ''' Returns a list of states in list named result '''
        data = State.select()
        return ListStyle.list(data, request), 200
    except Exception as e:
        abort(500)
Example #51
0
def delete_state(state_id):
    """
    Delete state with id as state_id
    """
    try:
        state = State.get(State.id == state_id)
    except Exception as error:
        response = {}
        response['code'] = 404
        response['msg'] = 'State not found'
        return response, 404
    delete_state = State.delete().where(State.id == state_id)
    delete_state.execute()
    response = {}
    response['code'] = 200
    response['msg'] = "State was deleted successfully"
    return response, 200
Example #52
0
def modify_state(state_id):
    try:
        # displaying state by id
        if request.method == 'GET':
            return jsonify(State.get(State.id == state_id).to_dict())
    except:
        return "No State was found with id %d\n" % (int(id))
    if request.method == 'DELETE':
        id = state_id
        try:
            # creating and oobject calling the State
            get_state = State.get(State.id == id)
            # deleting state based on the id
            get_state.delete_instance()
            return "State with id %d was deleted\n" % (int(id))
        except:
            return "No State was found with id %d\n" % (int(id))
Example #53
0
def delete_state(number):
    try:
        query = State.get(State.id == number)
    except State.DoesNotExist:
        return {'code':404, 'msg':'state not found'}, 404
    out_json = query.to_dict()
    query.delete_instance()
    return out_json
Example #54
0
def modify_state(state_id):
    try:
        # displaying state by id
        if request.method == 'GET':
            return jsonify(State.get(State.id == state_id).to_dict())
    except:
        return "No State was found with id %d\n" % (int(id))
    if request.method == 'DELETE':
        id = state_id
        try:
            # creating and oobject calling the State
            get_state = State.get(State.id == id)
            # deleting state based on the id
            get_state.delete_instance()
            return "State with id %d was deleted\n" % (int(id))
        except:
            return "No State was found with id %d\n" % (int(id))
Example #55
0
def state_places(state_id):
	state = State.select().where(State.id == state_id)

	if state.wrapped_count() < 1:
		return json_response(status_=404, code=10002, msg="state not found")

	query = Place.select().join(City).join(State).where(State.id == state_id)

	return ListStyle.list(query, request)
Example #56
0
def state_create_modify():
    if request.method == 'GET':
        state_list = State.select()
        order_values = [i.to_hash() for i in state_list]
        return jsonify(order_values)

    elif request.method == 'POST':

        check_state_name = State.select().where(
            State.name == request.form['name'])

        if check_state_name:
            error_msg = {'code': 10001, 'msg': 'State already exists'}
            return jsonify(error_msg)

        else:
            state = State.create(name=request.form['name'])
        return jsonify(state.to_hash())
Example #57
0
 def GetEligibleStateKeys(self):
     if self.state:
         return [self.state]
     if self.region:
         return State.query(State.region == self.region).fetch(
             keys_only=True)
     # National championships are not based on residence, they're based on
     # citizenship.
     return None
Example #58
0
def states_id(state_id):
	if request.method == 'GET':
		try:
			state = State.get(State.id == state_id)
			return jsonify(state.to_dict()), 200

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

	elif request.method == 'DELETE':
		try:
			state = State.get(State.id == state_id)
			state.delete_instance()
			state.save()
			return json_response(status_=200, msg="State succesfully deleted")

		except State.DoesNotExist:
			return json_response(status_=404, msg="state does not exist")