Пример #1
0
def newaddress(update_details):
    """Validate a user's address info, create new entry or associate their 
    useraccount with an existing entry"""
    apartment_vert = update_details.get("apartment", False)
    if apartment_vert:
        address = Address.query.filter_by(
            standard_address=update_details["address"],
            apartment=apartment_vert).first()
    else:
        address = Address.query.filter_by(
            standard_address=update_details["address"]).first()
    if address:
        pass
    if not address:
        address = Address(
            latitude=update_details["latitude"],
            longitude=update_details["longitude"],
            standard_address=update_details["address"],
            address_street=update_details["address_street"],
            address_street_num=update_details["address_street_num"],
            address_city=update_details["city"],
            address_state=update_details["state"],
            address_zip=update_details["zipcode"])
        db.session.add(address)
        db.session.commit()
    if apartment_vert:
        address.apartment = update_details["apartment"]
    user = User.query.filter_by(email=session["user_id"]).first()
    user.address = address.address_id
    user.avatar_src = update_details["user_avatar"]
    user.phone_number = update_details["phone_number"]
    db.session.commit()
Пример #2
0
def load_addresses():
    """Load addresses from u.addresses into database."""

    # Delete all rows in table to avoid adding duplicates
    Address.query.delete()

    for row in open("data/u.addresses"):
        row = row.rstrip()

        address_id, street, city, state, zipcode, country, unit, lat, lng, building_id = row.split("|")

        address = Address(address_id=address_id,
                            street=street,
                            city=city,
                            state=state,
                            zipcode=zipcode,
                            country=country,
                            unit=unit,
                            lat=lat,
                            lng=lng,
                            building_id=building_id)

    # Add the address to the database
    db.session.add(address)

    # Commit all additions to database
    db.session.commit()
Пример #3
0
def address_to_database(addresses, addresses_db):
    """Send user saved addresses to database."""

    i = 0
    for address in addresses:
        if address["address"] in addresses_db:
            input_address = Address.query.filter(
                Address.address == address["address"]).one()
        else:
            input_address = Address(latitude=address["lat"],
                                    longitude=address["lng"],
                                    address=address["address"],
                                    name=address["name"])

            db.session.add(input_address)
            db.session.commit()

        new_user_address = UserAddress(user_id=session["user_id"],
                                       address_id=input_address.address_id,
                                       label=address["label"])

        db.session.add(new_user_address)
        db.session.commit()
        if i == 0:
            if len(addresses) == 1:
                flash("Address saved.")
            elif len(addresses) == 2:
                flash("Addresses saved.")
            i += 1
Пример #4
0
def add_address():
    """ Adds new address for a user """

    label = request.form.get("label")
    address1 = request.form.get("address1")
    city = request.form.get("city")
    state = request.form.get("state")
    zipcode = request.form.get("zipcode")

    print "New address added"

    user_id = session['login']

    address = Address(user_id=user_id, address_label=label,
                address="{}, {}, {} {}".format(address1, city, state, zipcode))

    print address
    db.session.add(address)
    db.session.commit()

    new_address = {"label": label,
                    "address": "{}, {}, {} {}".format(address1, city, state, zipcode)
                    }

    user_object = User.query.get(user_id)

    return jsonify(new_address,'/templates/dynamic-profile',render_template('my-profile.html', user_object=user_object))
Пример #5
0
def home():
    if request.form and request.method == 'POST':
        data = request.form
        gender_mapping = {'Male': True, 'Female': False}
        address = Address(country=data.get('country'), city=data.get('city'))
        user = User(first_name=data.get('FirstName'),
                    last_name=data.get('LastName'),
                    email=data.get('Email'),
                    age=int(data.get('Age')),
                    gender=gender_mapping.get(data.get('gender')))
        user.address = address
        medical_record = MedicalRecord(
            has_diabetes=bool(data.get('has_diabete')))
        medical_record.user = user
        try:
            db.session.add(address)
            db.session.add(user)
            db.session.add(medical_record)
            db.session.commit()
        except Exception as exc:
            return ('an error occurs when saving data')
    elif request.method == 'GET':
        records = MedicalRecord.query.all()
        return render_template("home.html", records=records)
    return render_template("home.html")
Пример #6
0
def sample_address():
    """ Add sample address to DB """

    print "Sample Address"

    a1 = Address(user_id=1,
                 address_label='hackbright',
                 address='683 Sutter St, San Francisco, CA 94109')

    db.session.add(a1)
    db.session.commit()
Пример #7
0
def create_address( address_line1, address_line2, city,state, zip_code):
    """Create and return a address."""

    address = Address(address_line1 = address_line1,
                    address_line2 = address_line2,
                    city = city,
                    state = state,
                    zip_code = zip_code
                    )

    db.session.add(address)
    db.session.commit()

    return address
Пример #8
0
def register_process():
    """Registration page"""

    login = request.form.get('login')
    password = request.form.get('pwd')
    first_name = request.form.get('first_name')
    last_name = request.form.get('last_name')
    email = request.form.get('email')
    phone = request.form.get('phone')
    add_line1 = request.form.get('add_line1')
    add_line2 = request.form.get('add_line2')
    city = request.form.get('city')
    state = request.form.get('state')
    zip_code = request.form.get('zip_code')
    country = request.form.get('country')
    user_type = request.form.get('user_type')
    twitter_handle = request.form.get('twitter_handle')

    # add user to db
    user = User(first_name=first_name,
                last_name=last_name,
                email=email,
                phone=phone,
                login=login)
    # set user address
    user.address = Address(address_line1=add_line1,
                           address_line2=add_line2,
                           city=city,
                           state=state,
                           zip_code=zip_code,
                           country=country)
    # add user login data to app_user
    app_user = AppUser(login=login, password=password)

    # write new user / app_user to database
    db.session.add(app_user)
    db.session.add(user)
    db.session.commit()
    # put user's email in flask session
    session['email'] = email

    if user_type == 'artist':
        return render_template("artist_info.html", user_id=user.user_id)
    if user_type == 'patron':
        return render_template("patron_info.html", user_id=user.user_id)
    if user_type == 'fan':
        return render_template("fan_info.html", user_id=user.user_id)

    flash('You were successfully registered %s.' % session['email'])
    return redirect("/")
Пример #9
0
def save_event_in_database():
    """Saves event information in database when user favorites"""

    src_evt_id = request.form.get("src_evt_id")
    # Check if there is an event entry in database already
    if Saved_event.query.filter_by(src_evt_id='src_evt_id').first() is None:
        # get all info from event
        datetime = request.form.get("datetime")
        name = request.form.get("name")
        url = request.form.get("url")
        group_name = request.form.get("group_name")
        lat = request.form.get("lat")
        lng = request.form.get("lng")
        address = request.form.get("address")
        category = request.form.get("cat")
        cat_id = Category.query.filter_by(name=category).first()
        src_id = request.form.get("src_id")

        # add event address
        new_address = Address(lat=lat, lng=lng, formatted_addy=address)
        db.session.add(new_address)
        db.session.flush()

        #add event info
        new_evt = Saved_event(src_evt_id=src_evt_id,
                              datetime=datetime,
                              name=name,
                              url=url,
                              group_name=group_name,
                              addy_id=new_address.addy_id,
                              cat_id=cat_id,
                              src_id=src_id)

        db.session.add(new_evt)
        db.session.flush()
        evt_id = new_evt.evt_id
    else:
        event = Saved_event.query.filter_by(src_evt_id=src_evt_id).first()
        evt_id = event.event.evt_id

    new_user_saved_event = User_saved_event(user_id=current_user.user_id,
                                            evt_id=evt_id)
    db.session.add(new_user_saved_event)

    db.session.commit()

    print "New event was added to favorites"
    return name
Пример #10
0
def update_homebase_address():
    """Updates the home address for the user to current session"""

    address = session["address"]
    lat = session["lat"]
    lng = session["lng"]

    new_address = Address(lat=lat, lng=lng, formatted_addy=address)
    db.session.add(new_address)
    db.session.flush()

    #change address for the user
    curr_user = User.query.filter_by(user_id=current_user.user_id).first()
    curr_user.addy_id = new_address.addy_id
    db.session.commit()

    return new_address.formatted_addy
Пример #11
0
def save_user_in_database():
    """Register new user and save info in database"""

    name = request.form.get("name")
    email = request.form.get("email")
    regis_pw_input = request.form.get("password")

    # Check if user is already registered
    if User.query.filter_by(email=email).first() is not None:
        flash("There is already an account registered with this email.")
        return redirect("/registration")

    # Hash password to save in database
    hashed_pw = bcrypt.hash(regis_pw_input)
    del regis_pw_input

    # Add address record in DB
    if 'lat' and 'lng' in session:
        new_address = Address(lat=session["lat"],
                              lng=session["lng"],
                              formatted_addy=session["address"])
        db.session.add(new_address)
        db.session.flush()
        # Add user record in DB
        new_user = User(name=name,
                        email=email,
                        password=hashed_pw,
                        addy_id=new_address.addy_id)
    else:
        new_user = User(name=name,
                        email=email,
                        password=hashed_pw,
                        addy_id=None)

    db.session.add(new_user)
    db.session.commit()

    login_user(new_user)

    print "registration was successful and user logged in"
    flash("registration was successful and user logged in")

    return redirect("/")
Пример #12
0
def load_addresses():
    """Load addresses from u.address into database."""

    print "Addresses"

    Address.query.delete()

    for row in open("seed_data/u.address"):
        row = row.strip()
        address_id, address = row.split("|")
        g = geocoder.google(address)
        address = Address(address_id=address_id.strip(),
                          latitude=g.latlng[0],
                          longitude=g.latlng[1],
                          address=g.address,
                          name=g.address)

        db.session.add(address)

    db.session.commit()
Пример #13
0
def load_addresses(num_of_users):
    """ This function will generate ONE address for each of the users that were
    generated in load_users() - pass in the same number that you used to generate
    the users (i.e. num_of_users = num_to_gen)"""

    i = 0
    user_id = 0

    for i in range(num_of_users):
        user_id = user_id + 1
        print(f"user_id = {user_id}")

        street_1 = faker.street_address()
        street_2 = ""
        city = faker.city()
        zipcode = faker.postcode()
        # hard code USA for now
        country = "United States"
        state = faker.state()
        print(f"street_1 = {street_1}")
        print(f"street_2 = {street_2}")
        print(f"city = {city}")
        print(f"state = {state}")
        print(f"country = {country}")
        print(f"zipcode = {zipcode}")

        address = Address(user_id=user_id,
                          street_1=street_1,
                          street_2=street_2,
                          city=city,
                          state=state,
                          country=country,
                          zipcode=zipcode)
        i += 1

        # Add the address instance to the session so it will be stored.
        db.session.add(address)

    # Once we're done inserting all the users, commit the changes to the
    # database
    db.session.commit()
Пример #14
0
def load_addresses():
    """Load mock addresses into database."""

    print 'Addresses'
    Address.query.delete()

    filename = open("seed_data/addresses.json")
    address_list = loads(filename.read())

    for address in address_list:
        print address
        addy_id = address['addy_id'],
        lat = address['lat'],
        lng = address['lng'],

        address = Address(addy_id=addy_id, lat=lat, lng=lng)

        db.session.add(address)

    db.session.commit()
    filename.close()
Пример #15
0
def run():
    """
    Step 1) Import address csv.
    Step 2) Choose address.
    Step 3) Query addresss url and scrape trash days.
    Step 4) Geocode address to get latitude and longitude.

    creates list of Address objects containing lat,lng, and trash_days
    """

    driver = scrape_util.initChromeDriver()
    object_list = []

    address_list_path = constants.BASE_DIR + "/src/Addresses11215.csv"
    address_list = pd.read_csv(address_list_path)[:2]
    print("searching %s addresses" % len(address_list.index))

    for index, row in address_list.iterrows():
        #Scrape NYDOT website for trash_days
        address = str(row["Address"]) + ", Brooklyn, NY, USA"
        print("checking address %s of %s" %
              (str(index + 1), len(address_list)))
        trash_days = scrape_util.getTrashDays(address,
                                              driver,
                                              screenshot=False)
        if trash_days == None:
            continue

        #Geocode address.
        lat, lng = scrape_util.geocode(address)
        if None in (lat, lng):
            continue

        #Initialize Address object and add to list only if scrape and geocode are successful.
        object_list.append(Address(address, lat, lng, trash_days))

    #save address dataframe as a CSV file
    scrape_util.writeCSV(object_list)

    driver.close()
Пример #16
0
def load_receivers():
    """Load food bank data from csv file"""

    print "Receivers"

    # Delete all rows in table, so if we need to run this a second time,
    # we won't be trying to add duplicate data
    Receiver.query.delete()
    Address.query.delete()

    id_counter = 0

    for row in open("seed_data/receivers.csv"):
        row = row.rstrip()
        rows = row.split(",")

        receiver_id = id_counter
        name = rows[1]
        email = rows[3][1] + "@gmail.com"
        password = rows[3][2]
        phone_number = rows[4]
        address = rows[2]

        hashedPassword = bcrypt.hashpw(password.encode('utf8'),
                                       bcrypt.gensalt(10))

        address_obj = Address(formatted_add=address)

        receiver = Receiver(receiver_id=receiver_id,
                            name=name,
                            email=email,
                            password=hashedPassword,
                            phone_number=phone_number)

        db.session.add(user)
        id_counter += 1

    db.session.commit()
    print "Done!"
Пример #17
0
def install():
    Base.metadata.create_all(Session().bind)

    data = [('Chicago', 'United States', ('60601', '60602', '60603', '60604')),
            ('Montreal', 'Canada', ('H2S 3K9', 'H2B 1V4', 'H7G 2T8')),
            ('Edmonton', 'Canada', ('T5J 1R9', 'T5J 1Z4', 'T5H 1P6')),
            ('New York', 'United States', ('10001', '10002', '10003', '10004',
                                           '10005', '10006')),
            ('San Francisco', 'United States', ('94102', '94103', '94104',
                                                '94105', '94107', '94108'))]

    countries = {}
    all_post_codes = []
    for city, country, postcodes in data:
        try:
            country = countries[country]
        except KeyError:
            countries[country] = country = Country(country)

        city = City(city, country)
        pc = [PostalCode(code, city) for code in postcodes]
        Session.add_all(pc)
        all_post_codes.extend(pc)

    for i in xrange(1, 51):
        person = Person(
            "person %.2d" % i,
            Address(street="street %.2d" % i,
                    postal_code=all_post_codes[random.randint(
                        0,
                        len(all_post_codes) - 1)]))
        Session.add(person)

    Session.commit()

    # start the demo fresh
    Session.remove()
Пример #18
0
def create_new_address():

    email = session['user_email']
    user_id = db.session.query(User.user_id).filter_by(email=email).first()

    new_address = request.form.get('new-address-field')
    new_label = request.form.get('label-field')
    default = request.form.get('default-address')

    if default == "true":
        # Set current addresses to false, new address to true
        existing_addresses = Address.query.filter_by(user_id=user_id).all()
        for address in existing_addresses:
            address.is_default = False
        db.session.commit()
        is_default = True
    else:
        is_default = False

    latitude, longitude = geocode_address(new_address)

    # Add new address to addresses table
    new_address = Address(user_id=user_id,
                          label=new_label,
                          address_str=new_address,
                          latitude=latitude,
                          longitude=longitude,
                          is_default=is_default)
    db.session.add(new_address)
    db.session.commit()

    addresses = db.session.query(Address.label).filter_by(
        user_id=user_id).order_by(desc("is_default"), "label").all()

    # Return list of addresses in JSON format
    return jsonify({"addresses": addresses})
Пример #19
0
def add_address():
    userid = g.current_user.id
    contacts = request.get_json().get('contacts')
    phone_number = request.get_json().get('phone_number')
    address = request.get_json().get('address')
    default = request.get_json().get('default')

    if int(default) == 1:
        addressd = Address.query.filter_by(userid=userid,
                                           default=default).first()
        if addressd:
            addressd.default = 0
            try:
                db_session.add(addressd)
                db_session.commit()
            except Exception as e:
                print(e)
                db_session.rollback()
                return jsonify({'code': 0, 'message': '数据库错误'})

    addressa = Address(userid=userid,
                       contacts=contacts,
                       phone_number=phone_number,
                       address=address,
                       default=default)

    try:
        db_session.add(addressa)
        db_session.commit()
    except Exception as e:
        print(e)
        db_session.rollback()
        return jsonify({'code': 0, 'message': '数据库错误'})
    db_session.close()

    return jsonify({'code': 1, 'message': '添加成功'})
from model import User, Address
from connect import engine
from sqlalchemy.orm import Session

session = Session(bind=engine)

address1 = Address(email_address="*****@*****.**")
address2 = Address(email_address="*****@*****.**")
address3 = Address(email_address="*****@*****.**")

user1 = User(name="Вася")
user1.addresses = [address1, address2, address3]

session.add(user1)

session.commit()
Пример #21
0
    def example_data(self):
        """Create sample data"""
        # populate users table
        uk = User(first_name='Kushlani',
                  last_name='Jayasinha',
                  email='*****@*****.**',
                  address_id=1)
        uk.app_user = AppUser(login='******', password='******')

        uk.address = Address(address_line1='myhome')
        uc = User(first_name='Chris',
                  last_name='Lane',
                  email='*****@*****.**',
                  address_id=2)
        uc.app_user = AppUser(login='******', password='******')
        uc.address = Address(address_line1='myhome')

        uv = User(first_name='Vidharshi',
                  last_name='Dharmasens',
                  email='*****@*****.**',
                  address_id=3)
        uv.app_user = AppUser(login='******', password='******')
        uv.address = Address(address_line1='myhome')

        ua = User(first_name='Alex',
                  last_name='Hall',
                  email='*****@*****.**',
                  address_id=4)
        ua.app_user = AppUser(login='******', password='******')
        ua.address = Address(address_line1='myhome')

        # populate artists table
        a1 = Artist(bio='I am an artist.',
                    statement='I love art!',
                    website='http://KushlaniFineArt.com')

        # populate patrons table
        p1 = Patron(patron_info='I love Chris....')

        # populate fans table
        f1 = Fan(fan_info='I love Alex.')

        # populate artworks table
        aw1 = Artwork(
            title='Mendocino',
            year_created='2015',
            medium='oil',
            substrate='canvas',
            genre='abstracts',
            length='40"',
            height='30"',
            depth='1.5"',
            url=
            'https://fasoimages-4cde.kxcdn.com/25287_1438386l+v=201609181617c201609181617error/mendocino.jpg'
        )
        aw2 = Artwork(
            title='Autumn',
            year_created='2015',
            medium='oil',
            substrate='canvas',
            genre='abstracts',
            length='8"',
            height='8"',
            depth='1.5"',
            url=
            'https://fasoimages-4cde.kxcdn.com/25287_1322110l+v=201609181617c201609181617error/autumn.jpg'
        )

        #db.session.add_all([uk, uk.app_user, uk.address, uc, uc.app_user, uc.address, ua, ua.app_user, ua.address, uv, uv.app_user, uv.address, a1, p1, f1, aw1, aw2])
        db.session.add_all([uk, uc, ua, uv, a1, p1, f1, aw1, aw2])
        db.session.commit()
Пример #22
0
def seed_db(session):
    user = User(name='Michael', nickname='Mike')
    user.address = Address(street="5th Avenue", city="New York")
    session.add(user)
    session.commit()
Пример #23
0
def load_addresses():
    """Create addresses and load into database."""

    # Delete all rows in table to avoid adding duplicates
    Address.query.delete()

    # Initialize counter to add unit numbers 1/4 of the time
    i = 0

    # Iterate through text file with each line containing "lattitude|longigude"
    for pair in open('data/u.coordinates'):
        latlng = pair.split('|')
        lat = latlng[0]
        lng = latlng[1]

        # Make request to mapbox geocoding api using lng and lat
        # req = 'https://api.mapbox.com/geocoding/v5/mapbox.places/{},{}.json?access_token=pk.eyJ1Ijoibm1hcmdvbGlzODkiLCJhIjoibGxsVVJETSJ9.dQv5byiwSyj--mr7Bgwezw'.format(lng, lat)
        # r = requests.get(req)
        response = geocoder.reverse(lon=lng, lat=lat, types=['address'])
        json_response = response.json()
        # print 'response: ', json_response, '\n'

        if json_response["features"] == []:
            # print 'empty'
            continue
        else:
            num = json_response["features"][0]["address"]
            st = json_response["features"][0]["text"]
            street = '{} {}'.format(num, st)
            if len(json_response["features"][0]["context"]) == 5:
                city = json_response["features"][0]["context"][1]["text"]
                zipcode = json_response["features"][0]["context"][2]["text"]
                state = json_response["features"][0]["context"][3]["text"]
                country = json_response["features"][0]["context"][4]["text"]
            else:
                continue

            # For some reason -122.42691912,37.81240737 doesn't have the city attribute in context.
            # https://api.mapbox.com/geocoding/v5/mapbox.places/-122.42691912,37.81240737.json?types=address&access_token=pk.eyJ1Ijoibm1hcmdvbGlzODkiLCJhIjoibGxsVVJETSJ9.dQv5byiwSyj--mr7Bgwezw

            # 1/4 of the times, create an address with unit and building id
            if i % 4 == 0:
                building_id = randint(0, 10)
                address = Address(street=street,
                                  city=city,
                                  state=state,
                                  zipcode=zipcode,
                                  country=country,
                                  unit=fake.building_number(),
                                  lat=lat,
                                  lng=lng,
                                  building_id=building_id)

            # The rest of the time, create an address without unit and building id
            else:
                address = Address(
                    street=street,
                    city=city,
                    state=state,
                    zipcode=zipcode,
                    country=country,
                    lat=lat,
                    lng=lng,
                )

            # Add the address to the database
            db.session.add(address)

            # Commit all additions to database
            db.session.commit()

            i += 1
Пример #24
0
def create_entities():
    smb = Address(street="2 Main Street",
                  city="Greenfield",
                  state="MA",
                  zip_code="01301")
    return smb
Пример #25
0
    book_2 = Book(
        'Clean Code', 'Por que não testamos software? Porque é caro? '
        'Porque é demorado? Porque é chato? ', '## 1.2 Por que devemos testar?'
        '## 1.3 Por que não testamos?', 59.90, 194, '9788566250048',
        datetime(2020, 6, 20), category_1)

    books.add(book_2)
    categories.add(category_2)

    # Cadastrando Cupons

    date_expiration_coupon_1 = datetime(2020, 10, 10)
    date_expiration_coupon_2 = datetime(2020, 6, 10)

    coupon_1 = Coupon('ALURA10', date_expiration_coupon_1, 10)
    coupon_2 = Coupon('CDC40', date_expiration_coupon_2, 40)
    coupons.add(coupon_1)
    coupons.add(coupon_2)

    # Carrinho de Compras

    cart = ShoppingCartDatabase(books, coupons)
    client_1 = Client('Nádia', '*****@*****.**', '012.345.678-90',
                      Address('São Gonçalo', 'MG', '38900456'))

    cart.add_cart('Clean Code')
    cart.add_cart('Test-Driven Development')
    cart.add_cart('Test-Driven Development')
    cart.checkout(client_1, 'ALURA10')
Пример #26
0
def process_rating2():
    """Get ratings from modal form and store them in reviews table"""
    print "At process-rating"

    user_id = session['user']

    # If landlord_id was passed as data, set it equal to landlord_id to be used in review
    landlord_id = request.form.get('landlord-id-field')
    if landlord_id:
        print "Received landlord_id: {}".format(landlord_id)

    if not landlord_id:

        fname = request.form.get('fname')
        lname = request.form.get('lname')

        # See if landlord exists in database as entered (case insensitive)
        landlord_result = db.session.query(Landlord).filter(
            db.func.lower(Landlord.fname) == db.func.lower(fname),
            db.func.lower(Landlord.lname) == db.func.lower(lname)).first()

        # TO DO: change to .all() and return both, giving user option to choose

        if landlord_result:
            print "{} {} exists as a landlord.".format(fname, lname)
            landlord_id = landlord_result.landlord_id
        else:
            print "{} {} does not exist as a landlord as entered.".format(
                fname, lname)
            print "Searching for possible matches."

            # Use more flexible lookup to find possible matches
            landlord_results = find_landlords_by_name(fname, lname)

            # Return json object with landlord results
            if landlord_results:

                landlord_list = []

                for landlord in landlord_results:
                    landlord_list.append(landlord.convert_to_dict())

                landlord_dict = {'landlords': landlord_list}

                return jsonify(landlord_dict)

            else:
                return "found-no-landlords"
            # landlord = Landlord(fname=fname, lname=lname)

            # db.session.add(landlord)
            # db.session.commit()
            # flash("Successfully added {} {} as a landlord.".format(fname, lname))

    street = request.form.get('street-field')
    city = request.form.get('city')
    state = request.form.get('state')
    country = request.form.get('country')
    zipcode = request.form.get('zipcode')

    moved_in_at = request.form.get('move-in')
    moved_out_at = request.form.get('move-out')

    if moved_in_at:
        moved_in_at = datetime.strptime(moved_in_at, "%Y-%m-%d")

    else:
        moved_in_at = None

    if moved_out_at:
        moved_out_at = datetime.strptime(moved_out_at, "%Y-%m-%d")

    else:
        moved_out_at = None

    rating1 = request.form.get('rating1') or None
    rating2 = request.form.get('rating2') or None
    rating3 = request.form.get('rating3') or None
    rating4 = request.form.get('rating4') or None
    rating5 = request.form.get('rating5') or None
    comment = request.form.get('comment', None)

    # Query for the address in the database that matches the street, city and state
    address = db.session.query(Address).filter(
        Address.street.ilike("%" + street + "%"),
        Address.city.ilike("%" + city + "%"), Address.state == state).first()
    if address:
        address_id = address.address_id

    # If the address is not in the database
    elif address is None:

        # Geocode to find lat and lng
        # Use center of San Francisco for proximity lat and lng
        proxim_lng = -122.4194155
        proxim_lat = 37.7749295
        req = 'https://api.mapbox.com/geocoding/v5/mapbox.places/{}.json?proximity={},{}&access_token={}'.format(
            street, proxim_lng, proxim_lat, mapbox_token)
        r = requests.get(req)
        json_response = r.json()
        # pp.pprint(json_response)

        feature_to_add = None

        # Isolate the feature in the city the user searched for
        for feature in json_response['features']:
            # print json_response['features']
            print 'iterating over json response'
            if city == feature['context'][1]["text"]:
                feature_to_add = feature
                break

        # If there are no features that match the city the user searched for
        if feature_to_add is None:
            # flash("Can't find the street address you entered in the city you entered.")
            return "Address-not-valid"

        # Otherwise, continue the process to add the address to the database
        else:
            address = Address(street=street,
                              city=city,
                              state=state,
                              zipcode=zipcode,
                              country=country,
                              lng=feature_to_add['center'][0],
                              lat=feature_to_add['center'][1])

            db.session.add(address)
            db.session.commit()

            address_id = address.address_id

    # Add the review to the database

    review = Review(user_id=user_id,
                    landlord_id=landlord_id,
                    address_id=address_id,
                    moved_in_at=moved_in_at,
                    moved_out_at=moved_out_at,
                    created_at=datetime.utcnow(),
                    rating1=rating1,
                    rating2=rating2,
                    rating3=rating3,
                    rating4=rating4,
                    rating5=rating5,
                    comment=comment)

    db.session.add(review)
    db.session.commit()

    success = {'success': landlord_id}
    print success

    return jsonify(success)