def test_encode(): # type: () -> None Foo = Object.extend("Foo") obj = Foo() assert utils.encode(obj) == { "className": "Foo", "__type": "Pointer", "objectId": None, } acl = ACL() assert utils.encode(acl) == {} acl.set_read_access("xxx", True) assert utils.encode(acl) == {"xxx": {"read": True}} point = GeoPoint() assert utils.encode(point) == { "__type": "GeoPoint", "longitude": 0, "latitude": 0, } assert utils.encode([obj, acl, point]) == [ {"className": "Foo", "__type": "Pointer", "objectId": None}, {"xxx": {"read": True}}, {"__type": "GeoPoint", "longitude": 0, "latitude": 0}, ] assert utils.encode({"a": obj, "b": acl}) == { "a": {"className": "Foo", "__type": "Pointer", "objectId": None}, "b": {"xxx": {"read": True}}, }
def setup_func(): leancloud.client.USE_MASTER_KEY = None leancloud.client.APP_ID = None leancloud.client.APP_KEY = None leancloud.client.MASTER_KEY = None if use_master_key: leancloud.init(os.environ["APP_ID"], master_key=os.environ["MASTER_KEY"]) else: leancloud.init(os.environ["APP_ID"], os.environ["APP_KEY"]) olds = Query(GameScore).find() # make sure the test data does not change, else re-initialize it if len(olds) == 10: pass else: for old in olds: old.destroy() for i in range(10): game_score = GameScore() game_score.set("score", i) game_score.set("playerName", "张三") game_score.set("location", GeoPoint(latitude=i, longitude=-i)) game_score.set("random", random.randrange(100)) game_score.save()
def test_setter(): # type: () -> None p = GeoPoint() p.latitude = 10 assert p.latitude == 10 def f(): p.longitude = 200 assert_raises(ValueError, f)
def test_encode(): Foo = Object.extend('Foo') obj = Foo() assert utils.encode(obj) == { 'className': 'Foo', '__type': 'Pointer', 'objectId': None, } acl = ACL() assert utils.encode(acl) == {} acl.set_read_access('xxx', True) assert utils.encode(acl) == {'xxx': {'read': True}} point = GeoPoint() assert utils.encode(point) == { '__type': 'GeoPoint', 'longitude': 0, 'latitude': 0, } assert utils.encode([obj, acl, point]) == [ { 'className': 'Foo', '__type': 'Pointer', 'objectId': None, }, { 'xxx': {'read': True} }, { '__type': 'GeoPoint', 'longitude': 0, 'latitude': 0, } ] assert utils.encode({'a': obj, 'b': acl}) == { 'a': { 'className': 'Foo', '__type': 'Pointer', 'objectId': None, }, 'b': { 'xxx': {'read': True} }, }
class GeoPointField(Field): _fit_fn = { tuple: lambda pair: GeoPoint(pair[0], pair[1]), GeoPoint: lambda gp: gp, } def __init__(self, name=None, nullable=True, default=undefined): super().__init__(name, nullable, default) def near(self, geo_point): """ 查询离靠近指定点的对象,按距离升序。 :param geo_point: 指定地理点 """ try: return Condition(self, ConditionOperator.Near, self._fit_fn[type(geo_point)](geo_point)) except (KeyError, IndexError): raise ValueError('param geo_point must be instance of GeoPoint or ' 'tuple with two or more elements (only use first two).') def within_kilometers(self, geo_point, kilometers): """ 查询离指定点 kilometers 距离内的对象 :param geo_point: 地理点 :param kilometers: 距离,单位千米 """ try: return Condition(self, ConditionOperator.WithinKilometers, (self._fit_fn[type(geo_point)](geo_point), kilometers)) except (KeyError, IndexError): raise ValueError('param geo_point must be instance of GeoPoint or ' 'tuple with two or more elements (only use first two).') def __set__(self, instance, value): try: super().__set__(instance, self._fit_fn[type(value)](value)) except (KeyError, IndexError): raise ValueError('param geo_point must be instance of GeoPoint or ' 'tuple with two or more elements (only use first two).')
def setup_func(): leancloud.client.USE_MASTER_KEY = None leancloud.client.APP_ID = None leancloud.client.APP_KEY = None leancloud.client.MASTER_KEY = None leancloud.init(os.environ['APP_ID'], os.environ['APP_KEY']) olds = Query(GameScore).find() # make sure the test data does not change, else re-initialize it if len(olds) == 10: pass else: for old in olds: old.destroy() for i in range(10): game_score = GameScore() game_score.set('score', i) game_score.set('playerName', '张三') game_score.set('location', GeoPoint(latitude=i, longitude=-i)) game_score.set('random', random.randrange(100)) game_score.save()
def get_geo_info(ip: str) -> dict: """Generates a dictionary contains user's geo info. Args: ip: IP address. Returns: geo_info: User's geo location. """ reader = geolite2.reader() raw_info = reader.get(ip) geo_info = {} try: geo_info['continent'] = raw_info['continent']['names']['en'] except KeyError: geo_info['continent'] = None try: geo_info['country'] = raw_info['country']['names']['en'] except KeyError: geo_info['country'] = None try: geo_info['subdivisions'] = [ x['names']['en'] for x in raw_info['subdivisions'] ] except KeyError: geo_info['subdivisions'] = None try: geo_info['city'] = raw_info['city']['names']['en'] except KeyError: geo_info['city'] = None try: geo_info['location'] = GeoPoint(raw_info['location']['latitude'], raw_info['location']['longitude']) except KeyError: geo_info['location'] = None return geo_info
def test_within_kilometers(): result = Query(GameScore).within_kilometers( 'location', GeoPoint(latitude=0, longitude=0), 4000).find() assert len(result) == 10
def test_within_miles(): result = Query(GameScore).within_miles('location', GeoPoint(latitude=0, longitude=0), 4000).find() eq_([i.get('score') for i in result], list(range(10)))
def test_near(): result = Query(GameScore).near('location', GeoPoint(latitude=0, longitude=0)).find() eq_([i.get('score') for i in result], list(range(10)))
def test_eq(): # type: () -> None eq_(GeoPoint(0, 1) == GeoPoint(0, 1), True) eq_(GeoPoint(1, 1) == GeoPoint(1, 0), False)
def test_within_kilometers(): # type: () -> None result = (Query(GameScore).within_kilometers( "location", GeoPoint(latitude=0, longitude=0), 4000).find()) assert len(result) == 10
def test_within_miles(): # type: () -> None result = (Query(GameScore).within_miles("location", GeoPoint(latitude=0, longitude=0), 4000).find()) eq_([i.get("score") for i in result], list(range(10)))
def test_near(): # type: () -> None result = Query(GameScore).near("location", GeoPoint(latitude=0, longitude=0)).find() eq_([i.get("score") for i in result], list(range(10)))
def test_radians_to(): eq_(GeoPoint(0, 0).radians_to(GeoPoint(10, 10)), 0.24619691677893205) eq_(GeoPoint(10, 10).radians_to(GeoPoint(14.5, 24.5)), 0.25938444522905957)
def test_dump(): # type: () -> None p = GeoPoint(10, 20) assert p.dump() == {'latitude': 10, '__type': 'GeoPoint', 'longitude': 20}
def test_radians_to(): # type: () -> None assert GeoPoint(0, 0).radians_to(GeoPoint(10, 10)) - 0.24619691677893205 < 0.00001 assert GeoPoint(10, 10).radians_to(GeoPoint(14.5, 24.5)) - 0.25938444522905957 < 0.00001
def test_within_radians(): result = Query(GameScore).within_radians('location', GeoPoint(latitude=0, longitude=0), 1).find() eq_([i.get('score') for i in result], range(10))
def test_eq(): eq_(GeoPoint(0, 1) == GeoPoint(0, 1), True) eq_(GeoPoint(1, 1) == GeoPoint(1, 0), False)
def test_dump(): # type: () -> None p = GeoPoint(10, 20) assert p.dump() == {"latitude": 10, "__type": "GeoPoint", "longitude": 20}