Exemplo n.º 1
0
 def test__eq__pass(self):
     """
     Tests __eq__ with two equal Location objects
     """
     L1 = Location("Endor", 1, "Endor", "Z", "Y", "X", "W", -1, 1, 9001)
     L2 = Location("Endor", 1, "Endor", "Z", "Y", "X", "W", -1, 1, 9001)
     assert L1 == L2
Exemplo n.º 2
0
 def test__eq__fail_on_featuretype(self):
     """
     Tests __eq__ - fails on featuretype
     """
     L1 = Location("Endor", 1, "Endor", "Z", "Y", "X", "W", -1, 1, 9001)
     L2 = Location("Endor", 1, "Endor", "Z", "Y", "X", "not W", -1, 1, 9001)
     assert L1 != L2
Exemplo n.º 3
0
 def test__eq__fail_on_initial_weight(self):
     """
     Tests __eq__ - fails on initial_weight
     """
     L1 = Location("Endor", 1, "Endor", "Z", "Y", "X", "W", -1, 1, 9001)
     L2 = Location("Endor", 1, "Endor", "Z", "Y", "X", "W", -1, 1, 9001.1)
     assert L1 != L2
Exemplo n.º 4
0
 def test__eq__fail_on_geonameid(self):
     """
     Tests __eq__ - fails on geonameid
     """
     L1 = Location("Endor", 1, "Endor", "Z", "Y", "X", "W", -1, 1, 9001)
     L2 = Location("Endor", 21, "Endor", "Z", "Y", "X", "W", -1, 1, 9001)
     assert L1 != L2
Exemplo n.º 5
0
 def test__eq__fail_on_countrycode(self):
     """
     Tests __eq__ - fails on countrycode
     """
     L1 = Location("Endor", 1, "Endor", "Z", "Y", "X", "W", -1, 1, 9001)
     L2 = Location("Endor", 1, "Endor", "not Z", "Y", "X", "W", -1, 1, 9001)
     assert L1 != L2
Exemplo n.º 6
0
def create_location(address, postal_code, city, country):
	try:
		location = Location.objects.get(address=address, postal_code=postal_code, city=city, country=country)
	except Location.DoesNotExist:
		location = Location(address=address, postal_code=postal_code, city=city, country=country)
		location.save()
	return location
Exemplo n.º 7
0
def seed_locations():
    location_1 = Location(lat=38.929616,
                          lng=-77.049784,
                          location_name="National Zoo")
    db.session.add(location_1)
    db.session.commit()

    location_2 = Location(lat=35.150063,
                          lng=-89.994332,
                          location_name="Memphis Zoo")
    db.session.add(location_2)
    db.session.commit()

    location_3 = Location(lat=33.733759,
                          lng=-84.37166,
                          location_name="Zoo Atlanta")
    db.session.add(location_3)
    db.session.commit()

    location_4 = Location(lat=38.636625,
                          lng=-90.292819,
                          location_name="Saint Louis Zoo")
    db.session.add(location_4)
    db.session.commit()

    location_5 = Location(lat=35.845837,
                          lng=-40.481787,
                          location_name="Atlantic Ocean")
    db.session.add(location_5)
    db.session.commit()
Exemplo n.º 8
0
def edit_artist(artist_name):
    artist = Artist.objects(name=artist_name).first_or_404()
    if current_user not in artist.members:
        flash('You are not authorized to edit {}\'s information'.format(
            artist.name))
        return redirect(url_for('main.artist', artist_name=artist.name))
    form = EditArtistForm()
    form.location.choices = [(location.id,
                              location.city + ', ' + location.state)
                             for location in Location.objects()]
    form.genre.choices = [(genre.id, genre.name)
                          for genre in Genre.objects.order_by('name')]
    if form.validate_on_submit():
        artist.name = form.name.data
        artist.description = form.description.data
        artist.location = Location.objects(id=form.location.data).first()
        artist.genre = [
            Genre.objects(id=genre).first() for genre in form.genre.data
        ]
        artist.save(cascade=True)
        flash('{} Edits Complete'.format(artist.name))
        return redirect(url_for('main.artist', artist_name=artist.name))
    elif request.method == 'GET':
        form.name.data = artist.name
        form.description.data = artist.description
        form.genre.data = [genre.id for genre in artist.genre]
        form.location.data = artist.location.id
    return render_template('edit_artist.html',
                           form=form,
                           title='Edit {}'.format(artist.name))
Exemplo n.º 9
0
 def test_location_routers(self):
     assert len(ROUTER_MODELS)
     routers_cnt = 15
     address1 = 'Russia, Moscow, Red Square'
     address2 = 'Russia, Moscow, Red Square 2'
     for i in range(routers_cnt):
         db.session.add(Router(ROUTER_MODELS[i % len(ROUTER_MODELS)], 1))
     db.session.add(Location(address=address1))
     db.session.add(Location(address=address2))
     db.session.commit()
     start_location = Location.query.filter(Location.id == 1).first()
     cur_location = Location.query.filter(
         Location.address == address2).first()
     routers = Router.query.all()
     assert start_location
     assert cur_location
     assert len(routers) == routers_cnt
     assert len(start_location.routers) == routers_cnt
     for router in routers[:(routers_cnt // 2)]:
         cur_location.routers.append(router)
     db.session.add(cur_location)
     db.session.commit()
     start_location = Location.query.filter(Location.id == 1).first()
     cur_location = Location.query.filter(
         Location.address == address2).first()
     assert len(start_location.routers) == routers_cnt - routers_cnt // 2
     assert len(cur_location.routers) == routers_cnt // 2
Exemplo n.º 10
0
 def test__eq__fail_on_location(self):
     """
     Tests __eq__ - fails on location
     """
     L1 = Location("Endor", 1, "Endor", "Z", "Y", "X", "W", -1, 1, 9001)
     L2 = Location("not Endor", 1, "Endor", "Z", "Y", "X", "W", -1, 1, 9001)
     assert L1 != L2
Exemplo n.º 11
0
 def test__eq__fail_on_id(self):
     """
     Tests __eq__ - fails on id
     """
     L1 = Location("Endor", 1, "Endor", "Z", "Y", "X", "W", -1, 1, 9001)
     L2 = Location("Endor", 1, "Endor", "Z", "Y", "X", "W", -1, 1, 9001)
     L2.id = 4
     assert L1 != L2
Exemplo n.º 12
0
 def test__eq__fail_on_id(self):
     """
     Tests __eq__ - fails on id
     """
     L1 = Location("Endor", 1, "Endor", "Z", "Y", "X", "W", -1, 1, 9001)
     L2 = Location("Endor", 1, "Endor", "Z", "Y", "X", "W", -1, 1, 9001)
     L2.id = 4
     assert L1 != L2
Exemplo n.º 13
0
 def init(self, location, geonameid, name, countrycode, featureclass,
          featurecode, featuretype, latitude, longitude, initial_weight):
     """
     Shortcut Helper Function
     Initializes self.Loc and sets all of its attributes.
     """
     self.Loc = Location(location, geonameid, name, countrycode,
                         featureclass, featurecode, featuretype, latitude,
                         longitude, initial_weight)
Exemplo n.º 14
0
def db_rebuild():
    """
    Destroy and rebuild database with fake data.
    """
    # destroy and rebuild tables
    db.reflect()
    db.drop_all()
    db.create_all()

    # insert locations as defined in model
    Location.insert_locations()

    # insert roles as defined in model
    Role.insert_roles()

    # insert geos and usertypes as defined in model
    Geo.insert_geos()
    UserType.insert_user_types()

    # insert education data
    Education.create_education()

    # insert fake admin/test users
    from random import seed
    import forgery_py
    seed()
    test_user_1 = User(email='*****@*****.**',
                       username='******',
                       password='******',
                       app_name='password'.encode('base64'),
                       confirmed=True,
                       name='David Kimaru',
                       location='KE',
                       about_me=forgery_py.lorem_ipsum.sentence(),
                       member_since=forgery_py.date.date(True))
    admin_user = User(email='*****@*****.**',
                      username='******',
                      password='******',
                      app_name='webmaster'.encode('base64'),
                      confirmed=True,
                      name='Web Master',
                      location='UG',
                      about_me=forgery_py.lorem_ipsum.sentence(),
                      member_since=forgery_py.date.date(True))
    db.session.add_all([test_user_1, admin_user])
    db.session.commit()

    # insert fake user data
    # User.generate_fake(60)

    # print results
    inspector = db.inspect(db.engine)
    print('The following tables were created.')
    print('-' * 17)
    for table in inspector.get_table_names():
        print(table)
Exemplo n.º 15
0
def test_get_all_locations(app):
    """Test that locations can be got from database"""
    location1 = Location(name="Hall", x=10, y=10, width=10, height=10)
    location2 = Location(name="Kitchen", x=30, y=10, width=100, height=100)
    db.session.add(location1)
    db.session.add(location2)

    all_locations = Location.query.all()

    assert all_locations[0] == location1
    assert all_locations[1] == location2
Exemplo n.º 16
0
    def handle(self, *args, **options):

        all_orgs = reader_all()
        for org in all_orgs:
            for key,value in org.iteritems():
                categories = value['Category']

                resources = []
                for resource in categories:
                    resource = Resource.objects.get_or_create(name=resource)
                    resources.append(resource[0])

                name=key
                description = value.get('Description','No Description Provided.')
                programs = value.get('Program','No Programs Provided.')
                url = value.get('Website', 'No Website Provided.')
                population_served = value.get('Population', 'No Information Provided About Population Served.')
                eligibility = value.get('Eligibility','No Information Provided About Eligiblity.')
                language = value.get('Language','No Information Provided About Language Services.')
                services=value.get('Services', 'No Information about Services Provided'),

                provider = Provider.objects.get_or_create(
                    name=name,
                    description=description,
                    url=url,
                    population_served=population_served,
                    eligibility=eligibility,
                    programs=programs,
                    language_services=language,
                    services=services)

                if provider[1] == True:
                    address=value['Address']
                    phone=value.get('Phone', 'No Phone Number Provided.'),
                    hours=value.get('Hours', 'Hours of Operation Not Provided.'),
                    population=value.get('Population', 'No Information Provided About Language Services.')

                    location = Location(
                        provider=provider[0],
                        address=address,
                        phone=phone,
                        is_headquarters=False,
                        hours_open=hours,
                        population=population
                    )
                    location.save()

                    try:
                        for resource in resources:
                            location.resources_available.add(resource)
                            location.save()
                    except:
                        for resource in resources:
                            location.resources_available.add(resource)
Exemplo n.º 17
0
def initialize():
    from flask_migrate import upgrade
    from app.models import Role, Ad
    upgrade()
    db.create_all()  # Create the materialized view

    Role.insert_roles()
    Canton.insert()
    District.insert()
    Location.insert()
    Ad.insert_initial_xml()
    User.insert_default_user()
Exemplo n.º 18
0
def initialize():
    from flask_migrate import upgrade
    from app.models import Role, Ad
    upgrade()
    db.create_all()  # Create the materialized view

    Role.insert_roles()
    Canton.insert()
    District.insert()
    Location.insert()
    Ad.insert_initial_xml()
    User.insert_default_user()
Exemplo n.º 19
0
    def setUp(self):
        """Create test client and some sample data"""

        self.client = app.test_client()

        u1, u2, u3, s1, s2, f1, droplist, droplist_2, droplist_3 = droplist_setup(
        )

        self.u1 = u1
        self.u2 = u2
        self.u3 = u3
        self.s1 = s1
        self.s2 = s2
        self.f1 = f1
        self.droplist = droplist
        self.droplist_2 = droplist_2

        loc = Location(name="S409")
        loc_2 = Location(name="S408")
        loc_3 = Location(name="113")

        db.session.add_all([loc, loc_2, loc_3])
        db.session.commit()

        self.loc = loc
        self.loc_2 = loc_2
        self.loc_3 = loc_3

        item_1 = Item(row_letter="a",
                      column_number=1,
                      location_id=self.loc.id,
                      description="Test Item 1",
                      droplist_id=self.droplist_2.id)

        item_2 = Item(row_letter="a",
                      column_number=2,
                      location_id=self.loc_2.id,
                      description="Test Item 2",
                      droplist_id=self.droplist_2.id)

        item_3 = Item(row_letter="c",
                      column_number=3,
                      location_id=self.loc_3.id,
                      description="Test Item 3",
                      droplist_id=self.droplist_2.id)

        db.session.add_all([item_1, item_2, item_3])
        db.session.commit()

        self.item_1 = item_1
        self.item_2 = item_2
        self.item_3 = item_3
Exemplo n.º 20
0
    def location(current_user):
        county = str(request.data.get('county'))
        location = str(request.data.get('location'))

        user_location = Location(current_user.id, county, location)
        user_location.save()

        response = jsonify({
            'message': 'Successfully added user location',
            'status': True
        })
        response.status_code = 201
        return response
Exemplo n.º 21
0
 def test_location_update(self):
     address = 'Russia, Moscow'
     location = Location(address=address)
     db.session.add(location)
     db.session.commit()
     location_id = location.id
     assert len(Location.query.filter(Location.address == address).all())
     assert len(Location.query.filter(Location.id == location_id).all())
     address += ', Red Square'
     location.address = address
     db.session.add(location)
     db.session.commit()
     assert len(Location.query.filter(Location.address == address).all())
     assert len(Location.query.filter(Location.id == location_id).all())
Exemplo n.º 22
0
def create_location():
    if not request.json:
        abort(HTTPStatus.BAD_REQUEST, 'Request should be json')
    if 'address' not in request.json.keys():
        abort(HTTPStatus.BAD_REQUEST, 'Request should contain address')
    app.logger.info(
        _('Create location, address: ') + str(request.json['address']))
    new_location = Location(address=request.json['address'])
    db.session.add(new_location)
    db.session.commit()
    return make_response(
        json.dumps({'location': new_location.data()}),
        HTTPStatus.CREATED,
        {'Location': f'api/locations/{new_location.id}'},
    )
Exemplo n.º 23
0
    def post(self, org_id):
        parser = reqparse.RequestParser()
        parser.add_argument("name", type=str)
        parser.add_argument("timezone",
                            type=str,
                            default=current_app.config.get("DEFAULT_TIMEZONE"))
        parameters = parser.parse_args(strict=True)

        timezone = parameters.get("timezone")

        try:
            pytz.timezone(timezone)
        except pytz.exceptions.UnknownTimeZoneError as zone:
            return {"message": "Unknown timezone specified: %s" % zone}, 400

        l = Location(name=parameters.get("name"),
                     organization_id=org_id,
                     timezone=timezone)
        db.session.add(l)
        try:
            db.session.commit()
            return marshal(l, location_fields), 201
        except Exception as exception:
            db.session.rollback()
            current_app.logger.exception(str(exception))
            abort(400)
Exemplo n.º 24
0
def add_trip():
    """
    add a new user trip
    """
    data = request.get_json()
    try:
        # add new trip
        new_trip = Trip(name=data['name'],
                        user_id=g.user.id,
                        start_date=datetime.strptime(data['start_date'],
                                                     '%Y-%m-%d'),
                        end_date=datetime.strptime(data['end_date'],
                                                   '%Y-%m-%d'))
        db.session.add(new_trip)
        db.session.commit()

        geolocator = Nominatim(user_agent=_app.name)
        for loc in data['locations']:
            _loc = geolocator.geocode(loc)
            new_loc = Location(name=loc,
                               lat=_loc.latitude,
                               lng=_loc.longitude,
                               trip_id=new_trip.id)
            db.session.add(new_loc)
            db.session.commit()
    except OperationalError as e:
        db.session.rollback()
        return jsonify({"error": "something unexpected occurred!"}), 400
    return jsonify({'data': "Trip added successfully."}), 201
Exemplo n.º 25
0
def set_location():
    user = User.query.filter_by(secure_token=current_user.secure_token).first()
    if user is None: abort(404)

    location = Location.query.filter_by(user_id=current_user.id).first()
    if location is not None:
        db.session.delete(location)
        db.session.commit()
        flash("Setting up new Location...")
    if request.method == "POST":

        if not request.json: return jsonify({'message': 'Wrong request'})
        lat = request.json["lat"]
        lng = request.json["lng"]
        user.is_available = True
        db.session.commit()
        location = Location(
            user_id=current_user.id,
            user_lat=lat,
            user_lng=lng
        )
        db.session.add(location)
        db.session.commit()
        flash("New Location is set")
        return jsonify({'message': 'Your new Location has been Set'})
    return jsonify({'message': 'error'})
Exemplo n.º 26
0
def add_location():
    """添加区域"""
    req_dict = request.get_json()
    addr = req_dict.get('addr')
    location = req_dict.get('location')
    subject_id = req_dict.get("subject_id")
    print("++++添加区域++++", req_dict)
    # 校验数据
    param_keys = ["addr", "location", "subject_id"]
    param_dict = dict()
    for i in param_keys:
        param_dict.__setitem__(i, req_dict.get(i, ''))
    for key, value in param_dict.items():
        if not value:
            return jsonify(errno=RET.PARAMERR, errmsg="数据不完整,缺少%s" % key)
    try:
        subject_obj = Subject.query.filter_by(id=subject_id).first()
        subject_name = subject_obj.name
        exist = Location.query.filter_by(addr=addr,
                                         subject=subject_name,
                                         location=location).all()
        if exist:
            return jsonify(errno=RET.DBERR, errmsg="数据有重复")
        obj = Location(addr=addr, location=location, subject=subject_name)
        db.session.add(obj)
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno=RET.UNKOWNERR, errmsg="添加失败")
    return jsonify(errno=RET.OK, errmsg="成功")
Exemplo n.º 27
0
    def test_is_location_worker(self):
        # create a 2nd location
        location2 = Location(
            name="2nd Location",
            organization_id=self.organization.id,
            timezone="UTC")
        db.session.add(location2)
        db.session.commit()

        # create a 2nd role
        role2 = Role(name="2nd Role", location_id=location2.id)
        db.session.add(role2)

        # admins are not considered workers in the location
        g.current_user = self.admin
        assert not g.current_user.is_location_worker(
            location_id=self.location.id)
        assert not g.current_user.is_location_worker(location_id=location2.id)

        # location managers are also not considered workers
        g.current_user = self.manager
        assert not g.current_user.is_location_worker(
            location_id=self.location.id)
        assert not g.current_user.is_location_worker(location_id=location2.id)

        g.current_user = self.user1
        assert g.current_user.is_location_worker(location_id=self.location.id)
        assert not g.current_user.is_location_worker(location_id=location2.id)
Exemplo n.º 28
0
 def test_post(self, test_client, test_candidate, test_session,
               logged_in_user):
     higher_grade = Grade.query.filter(Grade.value == "SCS3").first()
     test_session.bulk_save_objects([
         Organisation(name="Number 11", department=False),
         Profession(value="Digital, Data and Technology"),
         Location(value="London"),
     ])
     test_session.commit()
     new_org = Organisation.query.first()
     new_profession = Profession.query.first()
     new_location = Location.query.first()
     data = {
         "new-grade": higher_grade.id,
         "start-date-day": "1",
         "start-date-month": "1",
         "start-date-year": "2019",
         "new-org": str(new_org.id),
         "new-profession": str(new_profession.id),
         "new-location": str(new_location.id),
         "role-change": "1",
         "new-title": "Senior dev",
     }
     test_client.post("/update/role", data=data)
     assert data.keys() == session.get("new-role").keys()
Exemplo n.º 29
0
def upload_csv(f):
    result = check_csv(f)
    if not isinstance(f, FileStorage):
        f = open(f)
    if result != "OK":
        return result
    ctr = 0
    lines = f.readlines()
    lines = [l.decode('utf-8') for l in lines]
    print(lines)
    for line in lines:
        line = line.strip()
        if line == "":
            pass

        data = line.split(";")

        if data[0].strip() not in users:
            ctr += 1
            users[data[0]] = ctr
            user = User(data[0])
            session.add(user)
        try:
            ts = datetime.strptime(data[3] + " " + data[4], "%d/%m/%Y %H:%M:%S")
            print("Timestamp is :", ts)
        except ValueError:
            continue
        user_id = users[data[0]]
        location = Location(data[1], data[2], ts, user_id)
        print(location)
        session.add(location)
        session.flush()

    f.close()
    return "OK"
def test_get_existing_location_from_db_by_query_string_success(
    logged_in_user, blank_session, test_location, query_string
):
    assert (
        Location.return_existing_location_or_none(query_string)[0].name
        == "Test building"
    )
Exemplo n.º 31
0
    def test_is_manager_in_org(self):

        # org admins are not managers
        g.current_user = self.admin
        assert not g.current_user.is_manager_in_org(
            org_id=self.organization.id)

        # role to users do not
        g.current_user = self.user2
        assert not g.current_user.is_manager_in_org(
            org_id=self.organization.id)

        # location managers do
        g.current_user = self.manager
        assert g.current_user.is_manager_in_org(org_id=self.organization.id)

        # create a 2nd location
        location2 = Location(
            name="2nd Location",
            organization_id=self.organization.id,
            timezone="UTC")
        db.session.add(location2)
        db.session.commit()

        # make user2 a manager of the new location
        location2.managers.append(self.user2)
        db.session.commit()

        g.current_user = self.user2
        assert g.current_user.is_manager_in_org(org_id=self.organization.id)
Exemplo n.º 32
0
    def __fill_db(self, cnt):
        location = Location(address='Some address')
        location.id = 1
        db.session.add(location)

        routers = {}
        for i in range(cnt):
            router = Router(
                model=app.config['ROUTER_MODELS'][i % len(
                    app.config['ROUTER_MODELS'])],
                location_id=location.id,
            )
            db.session.add(router)
            db.session.commit()
            routers[router.id] = router
        return routers
Exemplo n.º 33
0
def check_ready():
    global ready
    if len(ready) > 0 and time.time() - ready_countdown > 4:
        users = []
        print("Ready!!")
        for r in ready:
            print ("%s ready" % r)
            u = User.query.filter_by(username=r).first()
            users.append(u)

        avg = sum(map(lambda x: x.level, users)) // len(users) + 1
        cave_name, init, chest, enemies = cavegen.generate_cave([0,1], avg)
        cave = Location(name=cave_name, init_pos="%s,%s" % (init[0],init[1]))
        chest = Entity(name="chest",type="c",health=1,location=cave.id, position="%s,%s"%(chest[0],chest[1]))
        db.session.add(cave)
        db.session.commit()
        for ex,ey,name in enemies:
            print(ex,ey,name)
            print()
            e = Entity(name=name,type="e",health=avg,location=cave.id, position="%s,%s" % (ex,ey))
            db.session.add(e)
        for u in users:
            u.location = cave.id
            u.position = cave.init_pos
        ready = []
        db.session.commit()
Exemplo n.º 34
0
def add_location(entity, locationtext):

    def query(location):
        url = 'http://dev.virtualearth.net/REST/v1/Locations'
        params = {'query': location, 'key': 'Ai58581yC-Sr7mcFbYTtUkS3ixE7f6ZuJnbFJCVI4hAtW1XoDEeZyidQz2gLCCyD', 'incl': 'ciso2'}
        r = requests.get(url, params=params)
        responsedata = json.loads(r.text)
        return responsedata['resourceSets'][0]['resources']
    if locationtext:
        locations = locationtext.split(';')
        for location in locations:
            tries = 0
            time.sleep(0.1)

            resources = query(location)
            while len(resources) == 0 and tries < 20:
                #print 'NO RESULTS FOR ' + location + ' TRYING AGAIN'
                resources = query(location)
                tries+=1

            if len(resources):
                locationdata = resources[0]
                newlocation = Location()
                if 'formattedAddress' in locationdata['address']:
                    newlocation.full_address = locationdata['address']['formattedAddress']
                if 'addressLine' in locationdata['address']:
                    newlocation.address_line = locationdata['address']['addressLine']
                if 'locality' in locationdata['address']:
                    newlocation.locality = locationdata['address']['locality']
                if 'adminDistrict' in locationdata['address']:
                    newlocation.district = locationdata['address']['adminDistrict']
                if 'postalCode' in locationdata['address']:
                    newlocation.postal_code = locationdata['address']['postalCode']
                if 'countryRegion' in locationdata['address']:
                    newlocation.country = locationdata['address']['countryRegion']
                if 'countryRegionIso2' in locationdata['address']:
                    newlocation.country_code = locationdata['address']['countryRegionIso2']
                if 'point' in locationdata:
                    newlocation.latitude = locationdata['point']['coordinates'][0]
                    newlocation.longitude = locationdata['point']['coordinates'][1]
                entity.locations.append(newlocation)
                db.flush()
                #print 'GOT LOCATION FOR ', location
            else:
                print 'NO DATA FOUND FOR ' + location + ' ' + entity.name + ' ' + str(entity.id)
                print responsedata['resourceSets']
Exemplo n.º 35
0
def getHumanReadableLocation(latitude, longitude):
    latitude_longitude = latitude + "," + longitude
    locationCacheSearch = Location.objects.filter(latlong=latitude_longitude)

    if len(locationCacheSearch) == 0:
        url = 'http://maps.googleapis.com/maps/api/geocode/json?latlng=' + latitude + ',' + longitude + '&sensor=false'
        request = urllib2.Request(url, headers={"Accept": "application/json"})
        jsonResponse = urllib2.urlopen(request).read()
        jsonResponse = json.loads(jsonResponse)

        if jsonResponse['results']:
            address = jsonResponse['results'][0]['formatted_address']
            location = Location(latlong=latitude_longitude, location=address)
            location.save()
            return address
        return "Unknown"
    else:
        return locationCacheSearch.__getitem__(0).location
Exemplo n.º 36
0
 def init(self, location, geonameid, name, countrycode, featureclass,
          featurecode, featuretype, latitude, longitude, initial_weight):
     """
     Shortcut Helper Function
     Initializes self.Loc and sets all of its attributes.
     """
     self.Loc = Location(location, geonameid, name, countrycode,
                         featureclass, featurecode, featuretype, latitude,
                         longitude, initial_weight)
Exemplo n.º 37
0
def create_db(app):
    from app.models import Location, StreetCleaning

    db.init_app(app)
    db.drop_all()
    db.create_all()

    # add default first location when setting up db
    location = Location(isCurrent=True, streetNumber=531, streetName='FILLMORE ST')
    location.time = datetime.utcnow()
    db.session.add(location)

    # add street cleaning data
    from app.data import populate
    populate.add_street_cleaning_data()
    populate.prune_data()

    db.session.commit
Exemplo n.º 38
0
Arquivo: manage.py Projeto: njnr/onece
def loaddb():
    db.drop_all()
    db.create_all()
    Role.insert_roles()
    u = User(email='*****@*****.**', username='******', password='******', 
        confirmed=True)
    u1 = User(email='*****@*****.**', username='******', password='******',
        confirmed=True)
    db.session.add(u)
    db.session.add(u1)
    db.session.commit()
    
    u.role = Role.query.filter_by(permissions=0xff).first()
    u1.role =Role.query.filter_by(default=True).first()
    db.session.add(u)
    db.session.add(u1)
    User.generate_fake(100)
    Post.generate_fake(1000)
    Location.generate_fake(10)
    print u.role
    print u1.role
Exemplo n.º 39
0
    def test_create_photo(self):
        # Start with photo
        photo = Photo()
        photo.instagram_id = '757677846642235453_1134805'
        photo.caption = '126. Who needs fireworks anyway'
        photo.created_time = datetime(2012, 02, 29)
        photo.featured_on = 'Josh Johnson; #JJ'
        photo.link = 'http://instagram.com/p/qDVDHkyxvS/'

        db.session.add(photo)
        db.session.commit()

        self.assertIn(photo, db.session)

        # Mock some images
        hi_img = Image()
        hi_img.height = 640
        hi_img.width = 640
        hi_img.url = 'http://scontent-b.cdninstagram.com/hphotos-xpa1/t51.2885-15/10522310_677385995673625_267718762_n.jpg'
        hi_img.type = 'standard_resolution'

        low_img = Image()
        low_img.height = 306
        low_img.width = 306
        low_img.url = 'http://scontent-b.cdninstagram.com/hphotos-xpa1/t51.2885-15/10522310_677385995673625_267718762_a.jpg'
        low_img.type = 'low_resolution'

        thumb_img = Image()
        thumb_img.height = 150
        thumb_img.width = 150
        thumb_img.url = 'http://scontent-b.cdninstagram.com/hphotos-xpa1/t51.2885-15/10522310_677385995673625_267718762_s.jpg'
        thumb_img.type = 'thumbnail'

        images = [hi_img, low_img, thumb_img]
        db.session.add_all(images)
        db.session.commit()

        self.assertTrue(all(i in db.session for i in images))

        # Connect images to photo
        photo.images.extend(images)
        db.session.commit()

        self.assertTrue(all(i in photo.images for i in images))
        self.assertTrue(all(photo is i.photo for i in images))

        # Mock location and tag
        loc = Location()
        loc.instagram_id = '1'
        loc.name = 'Dogpatch Labs'
        loc.latitude = 37.782
        loc.longitude = -122.387

        db.session.add(loc)
        db.session.commit()

        self.assertIn(loc, db.session)

        tag = Tag()
        tag.name = 'july4th'

        db.session.add(tag)
        db.session.commit()

        self.assertIn(tag, db.session)

        # Connect location and tag to photo
        photo.locations.append(loc)
        photo.tags.append(tag)

        db.session.commit()

        self.assertIn(loc, photo.locations)
        self.assertIn(tag, photo.tags)
        self.assertIn(photo, loc.photos)
        self.assertIn(photo, tag.photos)
Exemplo n.º 40
0
class LocationTests(unittest.TestCase):
    """
    Tests for app.models.Location
    """

    # ----------------------- Before/After ----------------------- #
    def setUp(self):
        """
        Executed at the start of every test
        """
        self.Loc = None
        return

    def tearDown(self):
        """
        Executed at the end of every test
        """
        self.Loc = None
        return

    # ----------------------- Helpers ----------------------- #
    def init(self, location, geonameid, name, countrycode, featureclass,
             featurecode, featuretype, latitude, longitude, initial_weight):
        """
        Shortcut Helper Function
        Initializes self.Loc and sets all of its attributes.
        """
        self.Loc = Location(location, geonameid, name, countrycode,
                            featureclass, featurecode, featuretype, latitude,
                            longitude, initial_weight)

    # ----------------------- Tests ----------------------- #
    def test__init__success(self):
        """
        Tests models.Location init method
        """
        location = 'Banana'
        geonameid = 4000
        name = 'Banana'
        countrycode = 'Banana Tree'
        featureclass = 'Fruit'
        featurecode = 'FT'
        featuretype = 'Food'
        latitude = -9
        longitude = 89
        initial_weight = 25135431
        self.init(location, geonameid, name, countrycode, featureclass,
                  featurecode, featuretype, latitude, longitude,
                  initial_weight)
        assert isinstance(self.Loc, Location)
        assert self.Loc.location == location
        assert self.Loc.geonameid == geonameid
        assert self.Loc.name == name
        assert self.Loc.countrycode == countrycode
        assert self.Loc.featureclass == featureclass
        assert self.Loc.featurecode == featurecode
        assert self.Loc.latitude == latitude
        assert self.Loc.longitude == longitude
        assert self.Loc.initial_weight == initial_weight

    def test__eq__fail_on_Location(self):
        """
        Tests __eq__ - fails on isinstance(other, Location)
        """
        L1 = Location("Endor", 1, "Endor", "Z", "Y", "X", "W", -1, 1, 9001)
        L2 = 'not a Location'
        assert L1 != L2

    def test__eq__fail_on_id(self):
        """
        Tests __eq__ - fails on id
        """
        L1 = Location("Endor", 1, "Endor", "Z", "Y", "X", "W", -1, 1, 9001)
        L2 = Location("Endor", 1, "Endor", "Z", "Y", "X", "W", -1, 1, 9001)
        L2.id = 4
        assert L1 != L2

    def test__eq__fail_on_location(self):
        """
        Tests __eq__ - fails on location
        """
        L1 = Location("Endor", 1, "Endor", "Z", "Y", "X", "W", -1, 1, 9001)
        L2 = Location("not Endor", 1, "Endor", "Z", "Y", "X", "W", -1, 1, 9001)
        assert L1 != L2

    def test__eq__fail_on_geonameid(self):
        """
        Tests __eq__ - fails on geonameid
        """
        L1 = Location("Endor", 1, "Endor", "Z", "Y", "X", "W", -1, 1, 9001)
        L2 = Location("Endor", 21, "Endor", "Z", "Y", "X", "W", -1, 1, 9001)
        assert L1 != L2

    def test__eq__fail_on_name(self):
        """
        Tests __eq__ - fails on name
        """
        L1 = Location("Endor", 1, "Endor", "Z", "Y", "X", "W", -1, 1, 9001)
        L2 = Location("Endor", 1, "not Endor", "Z", "Y", "X", "W", -1, 1, 9001)
        assert L1 != L2

    def test__eq__fail_on_countrycode(self):
        """
        Tests __eq__ - fails on countrycode
        """
        L1 = Location("Endor", 1, "Endor", "Z", "Y", "X", "W", -1, 1, 9001)
        L2 = Location("Endor", 1, "Endor", "not Z", "Y", "X", "W", -1, 1, 9001)
        assert L1 != L2

    def test__eq__fail_on_featureclass(self):
        """
        Tests __eq__ - fails on featureclass
        """
        L1 = Location("Endor", 1, "Endor", "Z", "Y", "X", "W", -1, 1, 9001)
        L2 = Location("Endor", 1, "Endor", "Z", "not Y", "X", "W", -1, 1, 9001)
        assert L1 != L2

    def test__eq__fail_featurecode(self):
        """
        Tests __eq__ - fails on featurecode
        """
        L1 = Location("Endor", 1, "Endor", "Z", "Y", "X", "W", -1, 1, 9001)
        L2 = Location("Endor", 1, "Endor", "Z", "Y", "not X", "W", -1, 1, 9001)
        assert L1 != L2

    def test__eq__fail_on_featuretype(self):
        """
        Tests __eq__ - fails on featuretype
        """
        L1 = Location("Endor", 1, "Endor", "Z", "Y", "X", "W", -1, 1, 9001)
        L2 = Location("Endor", 1, "Endor", "Z", "Y", "X", "not W", -1, 1, 9001)
        assert L1 != L2

    def test__eq__fail_on_latitude(self):
        """
        Tests __eq__ - fails on latitude
        """
        L1 = Location("Endor", 1, "Endor", "Z", "Y", "X", "W", -1, 1, 9001)
        L2 = Location("Endor", 1, "Endor", "Z", "Y", "X", "W", -14, 1, 9001)
        assert L1 != L2

    def test__eq__fail_on_longitude(self):
        """
        Tests __eq__ - fails on longitude
        """
        L1 = Location("Endor", 1, "Endor", "Z", "Y", "X", "W", -1, 1, 9001)
        L2 = Location("Endor", 1, "Endor", "Z", "Y", "X", "W", -1, 251, 9001)
        assert L1 != L2

    def test__eq__fail_on_initial_weight(self):
        """
        Tests __eq__ - fails on initial_weight
        """
        L1 = Location("Endor", 1, "Endor", "Z", "Y", "X", "W", -1, 1, 9001)
        L2 = Location("Endor", 1, "Endor", "Z", "Y", "X", "W", -1, 1, 9001.1)
        assert L1 != L2

    def test__eq__pass(self):
        """
        Tests __eq__ with two equal Location objects
        """
        L1 = Location("Endor", 1, "Endor", "Z", "Y", "X", "W", -1, 1, 9001)
        L2 = Location("Endor", 1, "Endor", "Z", "Y", "X", "W", -1, 1, 9001)
        assert L1 == L2

    def test_repre(self):
        """
        Tests the __repr__ function for correct output
        """
        self.init(
            location='Mos Eisley',
            geonameid=33,
            name='Mos Eisley',
            countrycode='Tatooine',
            featureclass='dangerous',
            featurecode='dg',
            featuretype='City',
            latitude=43,
            longitude=34,
            initial_weight=1)
        s = self.Loc.__repr__()
        assert isinstance(s, str)
Exemplo n.º 41
0
def sample_data(request):
    from app.models import App_User,Vendor,Currier,Device,Order,Location

    # . Make User ALPHA
    # . Make Vendor 1 ("vendor_mgr")
    # . Device ALPHA
    # . Make User BRAVO
    # . Make Currier 1
    # . Device BRAVO
    # . Make Order 1
    # . - add locations


    # MAKE VENDOR 1
    a = App_User(first_name='ALPHA',
          last_name='ALPHA',
          app_user_type='vendor_mgr'
          )
    a.save()
    ONE_vendor_app_user_id = a.app_user_id
    c = Vendor(app_user_id=ONE_vendor_app_user_id,
                name='ALPHA BIZ',
                addr1='ONE_pickup_addr',
                days='Tue-Thu,Sat-Sun',
                start_times='11:00 AM, 1:00 AM',
                end_times='11:00 PM, 8:00 PM',
                area='Murray Hill',
                holidays=str({"Labor Day" : "closed"}),
                )
    c.save()
    ONE_vendor_id = c.vendor_id
    d = Device( vendor_id=ONE_vendor_id,
                model='iphone',
               platform='os7')
    d.save()
    ONE_vendor_device_id = d.device_id
    # add device to vendor entry
    c.device.add(d.device_id)
    c.save()
    # add device to app_user entry
    a.device.add(d.device_id)
    a.vendor_id = c.vendor_id
    a.save()

    # MAKE CURRIER 1
    a = App_User(first_name='BRAVO',
          last_name='BRAVO',
          app_user_type='currier'
          )
    a.save()
    ONE_dg_app_user_id = a.app_user_id
    c = Currier(app_user_id=ONE_dg_app_user_id,
                speed_rating='1.0',
                worktime_rating='10.0'
          )
    c.save()
    ONE_dg_id = c.currier_id
    d = Device( currier_id=ONE_dg_id,
                model='Samsung Galaxy',
               platform='Ice Cream')
    d.save()
    ONE_dg_device_id = d.device_id
    # add device to currier entry
    c.device.add(d.device_id)
    c.save()
    # add device to app_user entry
    a.device.add(d.device_id)
    a.currier_id = c.currier_id
    a.save()

    # MAKE ORDER 1
    c = Order(  vendor_id=ONE_vendor_id,
                vendor_dev_id=ONE_vendor_device_id,
                currier_id=ONE_dg_id,
                currier_dev_id=ONE_dg_device_id,
                call_in =True,
                deliv_addr='ONE_deliv_addr',
                tag='TAG1'
          )
    c.save()
    ONE_order_id = c.order_id
    # add locations for order
    l = Location(order_id=ONE_order_id,
                loc_num=1,
                currier_id=ONE_dg_id,
                web=c.web,
                call_in=c.call_in,
                pickup=True,
                addr=c.vendor.addr1,
                tag=c.tag,
          )
    l.save()
    c = Location(order_id=ONE_order_id,
                 loc_num=2,
                 currier_id=ONE_dg_id,
                 web=c.web,
                 call_in=c.call_in,
                 delivery=True,
                 addr=c.deliv_addr,
                 tag=c.tag,
          )
    c.save()

    # . Make User CHARLIE
    # . Make Vendor 2 ("vendor_empl")
    # . Device CHARLIE
    # . Make User DELTA
    # . Make Currier 2
    # . Device DELTA
    # . Make Order Two

    # MAKE VENDOR 2
    a = App_User(first_name='CHARLIE',
          last_name='CHARLIE',
          app_user_type='vendor_empl'
          )
    a.save()
    TWO_vendor_app_user_id = a.app_user_id
    c = Vendor( app_user_id=TWO_vendor_app_user_id,
                name='Charlie Biz',
                addr1='TWO_pickup_addr',
                days='Tue-Thu,Sat-Sun',
                start_times='11:00 AM, 1:00 AM',
                end_times='11:00 PM, 8:00 PM',
                area='Murray Hill',
                holidays=str({"Labor Day" : "closed"}),
                )
    c.save()
    TWO_vendor_id = c.vendor_id
    d = Device( vendor_id=TWO_vendor_id,
                model='Blackberry',
                platform='something old')
    d.save()
    TWO_vendor_device_id = d.device_id
    # add device to vendor entry
    c.device.add(d.device_id)
    c.save()
    # add device to app_user entry
    a.device.add(d.device_id)
    a.vendor_id = c.vendor_id
    a.save()

    # MAKE CURRIER 2
    a = App_User(first_name='DELTA',
          last_name='DELTA',
          app_user_type='currier'
          )
    a.save()
    TWO_dg_app_user_id = a.app_user_id
    c = Currier(app_user_id=TWO_dg_app_user_id,
                speed_rating='1.0',
                worktime_rating='10.0'
          )
    c.save()
    TWO_dg_id = c.currier_id
    d = Device( currier_id=TWO_dg_id,
                model='Samsung Galaxy',
               platform='Ice Cream')
    d.save()
    TWO_dg_device_id = d.device_id
    # add device to currier entry
    c.device.add(d.device_id)
    c.save()
    # add device to app_user entry
    a.device.add(d.device_id)
    a.currier_id = c.currier_id
    a.save()

    # MAKE ORDER 2
    time_in_90 = DT.now() + timedelta(hours=1,minutes=30)
    c = Order(  vendor_id=TWO_vendor_id,
                vendor_dev_id=TWO_vendor_device_id,
                currier_id=TWO_dg_id,
                currier_dev_id=TWO_dg_device_id,
                web=True,
                req_pickup_time=time_in_90.isoformat(),
                deliv_addr='TWO_deliv_addr',
                tag='TAG2'
          )
    c.save()
    TWO_order_id = c.order_id
    # add locations
    l = Location(order_id=TWO_order_id,
                 currier_id=TWO_dg_id,
                 web=c.web,
                 call_in=c.call_in,
                 loc_num=3,
                 pickup=True,
                 addr=c.vendor.addr1,
                 tag=c.tag,
          )
    l.save()
    c = Location(order_id=TWO_order_id,
                 loc_num=4,
                 currier_id=TWO_dg_id,
                 web=c.web,
                 call_in=c.call_in,
                 delivery=True,
                 addr=c.deliv_addr,
                 tag=c.tag,
          )
    c.save()

    return render(request, 'management/success.html', {})