def test_parse_city(self): response = ''' {"response":[ {"cid":1,"title":"Москва","region":"Regione Abruzzo область"}, {"cid":1074996,"title":"Москва","area":"Порховский район","region":"Псковская область"}, {"cid":1102561,"title":"Москва","area":"Пеновский район","region":"Тверская область"}, {"cid":1130701,"title":"Москва","area":"Верхошижемский район","region":"Кировская область"} ]} ''' country = CountryFactory.create(remote_id=1) instance = City(country=country) instance.parse(json.loads(response)['response'][0]) instance.save() self.assertEqual(instance.remote_id, 1) self.assertEqual(instance.name, u'Москва') instance = City(country=country) instance.parse(json.loads(response)['response'][1]) instance.save() self.assertEqual(instance.remote_id, 1074996) self.assertEqual(instance.name, u'Москва') self.assertEqual(instance.area, u"Порховский район") self.assertEqual(instance.region, u"Псковская область")
def create_city_nodes(df): n_nodes = 0 for _, row in df.drop_duplicates(subset=["city"]).iterrows(): city = City(name=row["city"]) city.save() n_nodes += 1 print("created {} nodes".format(n_nodes))
def run_city(verbose=True, step=10, begin=0, end=0): import csv filename = os.path.join(settings.BASE_PATH, 'apps', 'world', 'data', 'cities.csv') reader = csv.reader(open(filename, 'rb'), delimiter=',', quotechar="'") for row in reader: c = City() c.name = row[4] c.capital = bool(int(row[9])) c.world_city = bool(int(row[12])) c.mega_city = bool(int(row[13])) c.point = Point(float(row[22]), float(row[21])) #don't save the city if a country can't be found for it try: c.country = CountryBorder.objects.get(iso3=row[17]) except : continue try: c.state = StateBorder.objects.get(name=row[18]) except : try: c.state = StateBorder.objects.get(mpoly__contains=c.point) except : pass c.sqkm = int(row[40]) topleft = Point(float(row[48]), float(row[55])) topright = Point(float(row[51]), float(row[55])) bottomleft = Point(float(row[48]), float(row[52])) bottomright = Point(float(row[51]), float(row[52])) c.mpoly = MultiPolygon(Polygon(LinearRing(topleft, topright, bottomright, bottomleft, topleft))) c.save() print c.name
def add_city(state_id): """Creates City object""" req = request.get_json() state = storage.get("State", state_id) if state is None: abort(404) if req is None: return (jsonify("Not a JSON"), 400) try: req['name'] except: return (jsonify("Missing name"), 400) req['state_id'] = state_id city_data = City(**req) for k, v in req.items(): setattr(city_data, k, v) city_data.save() return (jsonify(city_data.to_json()), 201)
def test01_setup(self): "Setting up for related model tests." for name, state, lon, lat in cities: loc = Location(point=Point(lon, lat)) loc.save() c = City(name=name, state=state, location=loc) c.save()
def post_city(state_id): ''' Create a City object ''' if not request.json: return jsonify({"error": "Not a JSON"}), 400 if 'name' not in request.json: return jsonify({"error": "Missing name"}), 400 new_city = City(**request.get_json()) new_city.save() return jsonify(new_city.to_dict()), 201
def cities_post(state_id): """Add a city to storage with given dictionary""" obj = request.get_json(silent=True) if obj is None: return "Not a JSON", 400 if storage.get("State", state_id) is None: abort(404) if "name" not in obj: return "Missing name", 400 obj["state_id"] = state_id obj = City(**obj) obj.save() return jsonify(obj.to_dict()), 201
def test11_lookup_insert_transform(self): "Testing automatic transform for lookups and inserts." if DISABLE: return # San Antonio in 'WGS84' (SRID 4326) sa_4326 = "POINT (-98.493183 29.424170)" wgs_pnt = fromstr(sa_4326, srid=4326) # Our reference point in WGS84 # Oracle doesn't have SRID 3084, using 41157. if SpatialBackend.oracle: # San Antonio in 'Texas 4205, Southern Zone (1983, meters)' (SRID 41157) # Used the following Oracle SQL to get this value: # SELECT SDO_UTIL.TO_WKTGEOMETRY(SDO_CS.TRANSFORM(SDO_GEOMETRY('POINT (-98.493183 29.424170)', 4326), 41157)) FROM DUAL; nad_wkt = "POINT (300662.034646583 5416427.45974934)" nad_srid = 41157 else: # San Antonio in 'NAD83(HARN) / Texas Centric Lambert Conformal' (SRID 3084) nad_wkt = ( "POINT (1645978.362408288754523 6276356.025927528738976)" ) # Used ogr.py in gdal 1.4.1 for this transform nad_srid = 3084 # Constructing & querying with a point from a different SRID. Oracle # `SDO_OVERLAPBDYINTERSECT` operates differently from # `ST_Intersects`, so contains is used instead. nad_pnt = fromstr(nad_wkt, srid=nad_srid) if SpatialBackend.oracle: tx = Country.objects.get(mpoly__contains=nad_pnt) else: tx = Country.objects.get(mpoly__intersects=nad_pnt) self.assertEqual("Texas", tx.name) # Creating San Antonio. Remember the Alamo. sa = City(name="San Antonio", point=nad_pnt) sa.save() # Now verifying that San Antonio was transformed correctly sa = City.objects.get(name="San Antonio") self.assertAlmostEqual(wgs_pnt.x, sa.point.x, 6) self.assertAlmostEqual(wgs_pnt.y, sa.point.y, 6) # If the GeometryField SRID is -1, then we shouldn't perform any # transformation if the SRID of the input geometry is different. # SpatiaLite does not support missing SRID values. if not SpatialBackend.spatialite: m1 = MinusOneSRID(geom=Point(17, 23, srid=4326)) m1.save() self.assertEqual(-1, m1.geom.srid)
def load2mysql(self): with open(self.path) as f: provinces = json.load(f) for province in provinces: # print province["name"] p = Province(name=province["name"]) p.save() for city in province["city"]: # print " %s" % city["name"] c = City(name=city["name"], province=p) c.save() for area in city["area"]: # print " %s" % area cou = County(name=area, city=c) cou.save()
def create_or_getCity(cityName, state, lat,lon): try: c = City.objects.get(name=cityName) except City.DoesNotExist: r = requests.get("http://photon.komoot.de/api/?q={},{}&limit=1&lat={}&lon={}".format(cityName, state.name, lat,lon)).json() lastCity = City.objects.latest('created_on') c = City() c.id = lastCity.id +1 c.name=cityName c.stateID=state.id c.lat= r['features'][0]['geometry']['coordinates'][1] c.lon= r['features'][0]['geometry']['coordinates'][0] c.live="true" c.save() return c
def post_city(state_id): """ Adds a new state to State """ try: if request.json: if 'name' not in request.json: return jsonify({'error': 'Missing name'}), 400 news = request.get_json().get('name') state = storage.get('State', state_id) if state is None: abort(404) newo = City(name=news, state_id=state_id) newo.save() return jsonify(newo.to_dict()), 201 return jsonify({'error': 'Not a JSON'}), 400 except BaseException: abort(404)
def post_cities(state_id): """ function to create a city """ state = storage.get("State", state_id) if state is None: abort(404) content = request.get_json() if not content: return (jsonify({"error": "Not a JSON"}), 400) if "name" not in content: return (jsonify({"error": "Missing name"}), 400) content['state_id'] = state.id post_city = City(**content) post_city.save() return (jsonify(post_city.to_dict()), 201)
def test11_lookup_insert_transform(self): "Testing automatic transform for lookups and inserts." if DISABLE: return # San Antonio in 'WGS84' (SRID 4326) sa_4326 = 'POINT (-98.493183 29.424170)' wgs_pnt = fromstr(sa_4326, srid=4326) # Our reference point in WGS84 # Oracle doesn't have SRID 3084, using 41157. if SpatialBackend.oracle: # San Antonio in 'Texas 4205, Southern Zone (1983, meters)' (SRID 41157) # Used the following Oracle SQL to get this value: # SELECT SDO_UTIL.TO_WKTGEOMETRY(SDO_CS.TRANSFORM(SDO_GEOMETRY('POINT (-98.493183 29.424170)', 4326), 41157)) FROM DUAL; nad_wkt = 'POINT (300662.034646583 5416427.45974934)' nad_srid = 41157 else: # San Antonio in 'NAD83(HARN) / Texas Centric Lambert Conformal' (SRID 3084) nad_wkt = 'POINT (1645978.362408288754523 6276356.025927528738976)' # Used ogr.py in gdal 1.4.1 for this transform nad_srid = 3084 # Constructing & querying with a point from a different SRID. Oracle # `SDO_OVERLAPBDYINTERSECT` operates differently from # `ST_Intersects`, so contains is used instead. nad_pnt = fromstr(nad_wkt, srid=nad_srid) if SpatialBackend.oracle: tx = Country.objects.get(mpoly__contains=nad_pnt) else: tx = Country.objects.get(mpoly__intersects=nad_pnt) self.assertEqual('Texas', tx.name) # Creating San Antonio. Remember the Alamo. sa = City(name='San Antonio', point=nad_pnt) sa.save() # Now verifying that San Antonio was transformed correctly sa = City.objects.get(name='San Antonio') self.assertAlmostEqual(wgs_pnt.x, sa.point.x, 6) self.assertAlmostEqual(wgs_pnt.y, sa.point.y, 6) # If the GeometryField SRID is -1, then we shouldn't perform any # transformation if the SRID of the input geometry is different. # SpatiaLite does not support missing SRID values. if not SpatialBackend.spatialite: m1 = MinusOneSRID(geom=Point(17, 23, srid=4326)) m1.save() self.assertEqual(-1, m1.geom.srid)
def city_post(state_id): """use the post method to create""" try: if not request.is_json: return make_response(jsonify({'error': 'Not a JSON'}), 400) req = request.get_json() except: return make_response(jsonify({'error': 'Not a JSON'}), 400) dict_name = req.get("name") if dict_name is None: return make_response(jsonify({'error': 'Missing name'}), 400) state = storage.get("State", state_id) if state is None: abort(404) req["state_id"] = state_id new_city = City(**req) new_city.save() return (jsonify(new_city.to_dict()), 201)
def setCityInfo(master, cityName, maxConn, DialPeer): try: busqueda = City.objects.filter(CityName=cityName) newCity = busqueda[0] newCity.ActualMaxConn = maxConn newCity.DialPeer = DialPeer newCity.save() except: newCity = City() newCity.CityName = cityName newCity.idMaster = master newCity.ActualMaxConn = maxConn newCity.DialPeer = DialPeer newCity.save() return newCity
def post_cities(id): ''' Post a new city ''' try: content = request.get_json() except: return (jsonify({"error": "Not a JSON"}), 400) name = content.get("name") if name is None: return (jsonify({"error": "Missing name"}), 400) my_state = storage.get('State', id) if my_state is None: abort(404) new_city = City() new_city.state_id = id new_city.name = name new_city.save() return (jsonify(new_city.to_dict()), 201)
def get_cities(state_id): """ Retrieves list of all City objects """ state = storage.get("State", state_id) if state is None: abort(404) if request.method == 'GET': return jsonify([ obj.to_dict() for obj in storage.all("City").values() if obj.state_id == state_id ]) if request.method == 'POST': if not request.json: abort(400, 'Not a JSON') if 'name' not in request.json: abort(400, 'Missing name') data = request.get_json().get('name') new_city = City(name=data, state_id=state_id) new_city.save() return make_response(jsonify(new_city.to_dict()), 201)
def post_city(state_id): """Creates a City Args: state_id: id of the state in uuid format Returns: jsonified version of created city """ if storage.get("State", state_id) is None: abort(404) if not request.json: return jsonify({"error": "Not a JSON"}), 400 city_dict = request.get_json() if "name" not in city_dict: return jsonify({"error": "Missing name"}), 400 else: c_name = city_dict["name"] city = City(name=c_name, state_id=state_id) for key, value in city_dict.items(): setattr(city, key, value) city.save() return jsonify(city.to_dict()), 201
def create_city(state_id): ''' Creates a new City object and saves it to storage ''' state = storage.get("State", state_id) if not state: abort(404) if not request.json: abort(400) return jsonify({"error": "Not a JSON"}) else: city_dict = request.get_json() if "name" in city_dict: city_name = city_dict["name"] city = City(name=city_name, state_id=state_id) for k, v in city_dict.items(): setattr(city, k, v) city.save() else: abort(400) return jsonify({"error": "Missing name"}) return jsonify(city.to_dict()), 201
def cities_of_a_state(state_id): ''' GET: list all cities in a specific state POST: add a city to a specific state ''' my_state = storage.get('State', state_id) if my_state is None: abort(404) if request.method == 'POST': city_dict = request.get_json() if city_dict is None: return 'Not a JSON', 400 if 'name' not in city_dict.keys(): return 'Missing name', 400 city_dict['state_id'] = state_id my_city = City(**city_dict) my_city.save() return jsonify(my_city.to_dict()), 201 my_cities = [ city.to_dict() for city in storage.all('City').values() if city.state_id == state_id ] return jsonify(my_cities)
def test11_lookup_insert_transform(self): "Testing automatic transform for lookups and inserts." if DISABLE: return # San Antonio in 'WGS84' (SRID 4326) sa_4326 = 'POINT (-98.493183 29.424170)' wgs_pnt = fromstr(sa_4326, srid=4326) # Our reference point in WGS84 # Oracle doesn't have SRID 3084, using 41157. if oracle: # San Antonio in 'Texas 4205, Southern Zone (1983, meters)' (SRID 41157) # Used the following Oracle SQL to get this value: # SELECT SDO_UTIL.TO_WKTGEOMETRY(SDO_CS.TRANSFORM(SDO_GEOMETRY('POINT (-98.493183 29.424170)', 4326), 41157)) FROM DUAL; nad_wkt = 'POINT (300662.034646583 5416427.45974934)' nad_srid = 41157 else: # San Antonio in 'NAD83(HARN) / Texas Centric Lambert Conformal' (SRID 3084) nad_wkt = 'POINT (1645978.362408288754523 6276356.025927528738976)' # Used ogr.py in gdal 1.4.1 for this transform nad_srid = 3084 # Constructing & querying with a point from a different SRID. Oracle # `SDO_OVERLAPBDYINTERSECT` operates differently from # `ST_Intersects`, so contains is used instead. nad_pnt = fromstr(nad_wkt, srid=nad_srid) if oracle: tx = Country.objects.get(mpoly__contains=nad_pnt) else: tx = Country.objects.get(mpoly__intersects=nad_pnt) self.assertEqual('Texas', tx.name) # Creating San Antonio. Remember the Alamo. sa = City(name='San Antonio', point=nad_pnt) sa.save() # Now verifying that San Antonio was transformed correctly sa = City.objects.get(name='San Antonio') self.assertAlmostEqual(wgs_pnt.x, sa.point.x, 6) self.assertAlmostEqual(wgs_pnt.y, sa.point.y, 6)
def test02_proxy(self): "Testing Lazy-Geometry support (using the GeometryProxy)." if DISABLE: return ## Testing on a Point pnt = Point(0, 0) nullcity = City(name='NullCity', point=pnt) nullcity.save() # Making sure TypeError is thrown when trying to set with an # incompatible type. for bad in [5, 2.0, LineString((0, 0), (1, 1))]: try: nullcity.point = bad except TypeError: pass else: self.fail('Should throw a TypeError') # Now setting with a compatible GEOS Geometry, saving, and ensuring # the save took, notice no SRID is explicitly set. new = Point(5, 23) nullcity.point = new # Ensuring that the SRID is automatically set to that of the # field after assignment, but before saving. self.assertEqual(4326, nullcity.point.srid) nullcity.save() # Ensuring the point was saved correctly after saving self.assertEqual(new, City.objects.get(name='NullCity').point) # Setting the X and Y of the Point nullcity.point.x = 23 nullcity.point.y = 5 # Checking assignments pre & post-save. self.assertNotEqual(Point(23, 5), City.objects.get(name='NullCity').point) nullcity.save() self.assertEqual(Point(23, 5), City.objects.get(name='NullCity').point) nullcity.delete() ## Testing on a Polygon shell = LinearRing((0, 0), (0, 100), (100, 100), (100, 0), (0, 0)) inner = LinearRing((40, 40), (40, 60), (60, 60), (60, 40), (40, 40)) # Creating a State object using a built Polygon ply = Polygon(shell, inner) nullstate = State(name='NullState', poly=ply) self.assertEqual(4326, nullstate.poly.srid) # SRID auto-set from None nullstate.save() ns = State.objects.get(name='NullState') self.assertEqual(ply, ns.poly) # Testing the `ogr` and `srs` lazy-geometry properties. if gdal.HAS_GDAL: self.assertEqual(True, isinstance(ns.poly.ogr, gdal.OGRGeometry)) self.assertEqual(ns.poly.wkb, ns.poly.ogr.wkb) self.assertEqual(True, isinstance(ns.poly.srs, gdal.SpatialReference)) self.assertEqual('WGS 84', ns.poly.srs.name) # Changing the interior ring on the poly attribute. new_inner = LinearRing((30, 30), (30, 70), (70, 70), (70, 30), (30, 30)) ns.poly[1] = new_inner ply[1] = new_inner self.assertEqual(4326, ns.poly.srid) ns.save() self.assertEqual(ply, State.objects.get(name='NullState').poly) ns.delete()
def test02_proxy(self): "Testing Lazy-Geometry support (using the GeometryProxy)." #### Testing on a Point pnt = Point(0, 0) nullcity = City(name='NullCity', point=pnt) nullcity.save() # Making sure TypeError is thrown when trying to set with an # incompatible type. for bad in [5, 2.0, LineString((0, 0), (1, 1))]: try: nullcity.point = bad except TypeError: pass else: self.fail('Should throw a TypeError') # Now setting with a compatible GEOS Geometry, saving, and ensuring # the save took, notice no SRID is explicitly set. new = Point(5, 23) nullcity.point = new # Ensuring that the SRID is automatically set to that of the # field after assignment, but before saving. self.assertEqual(4326, nullcity.point.srid) nullcity.save() # Ensuring the point was saved correctly after saving self.assertEqual(new, City.objects.get(name='NullCity').point) # Setting the X and Y of the Point nullcity.point.x = 23 nullcity.point.y = 5 # Checking assignments pre & post-save. self.assertNotEqual(Point(23, 5), City.objects.get(name='NullCity').point) nullcity.save() self.assertEqual(Point(23, 5), City.objects.get(name='NullCity').point) nullcity.delete() #### Testing on a Polygon shell = LinearRing((0, 0), (0, 100), (100, 100), (100, 0), (0, 0)) inner = LinearRing((40, 40), (40, 60), (60, 60), (60, 40), (40, 40)) # Creating a State object using a built Polygon ply = Polygon(shell, inner) nullstate = State(name='NullState', poly=ply) self.assertEqual(4326, nullstate.poly.srid) # SRID auto-set from None nullstate.save() ns = State.objects.get(name='NullState') self.assertEqual(ply, ns.poly) # Testing the `ogr` and `srs` lazy-geometry properties. if gdal.HAS_GDAL: self.assertEqual(True, isinstance(ns.poly.ogr, gdal.OGRGeometry)) self.assertEqual(ns.poly.wkb, ns.poly.ogr.wkb) self.assertEqual(True, isinstance(ns.poly.srs, gdal.SpatialReference)) self.assertEqual('WGS 84', ns.poly.srs.name) # Changing the interior ring on the poly attribute. new_inner = LinearRing((30, 30), (30, 70), (70, 70), (70, 30), (30, 30)) ns.poly[1] = new_inner ply[1] = new_inner self.assertEqual(4326, ns.poly.srid) ns.save() self.assertEqual(ply, State.objects.get(name='NullState').poly) ns.delete()
def create_dub(self, bot_id, bot_2): try: telebot.TeleBot(bot_2).get_me() except Exception: return 'ERROR, go back' bot_2 = loads( BotProfile.objects(token=bot_2).first().to_json())['_id']['$oid'] text = Texts.objects(bot_id=bot_id).first() if not (text is None): text_dict = loads(text.to_json()) dub_text = {} for key in text_dict: if key != '_id': dub_text.update({key: text_dict[key]}) dub_text['bot_id'] = bot_2 new_text = Texts(**dub_text) new_text.save() cities = City.objects(bot_id=bot_id) if cities is not None: for city in cities: if not (city is None): city_dict = loads(city.to_json()) dub_city = {} for key in city_dict: if key != '_id': dub_city.update({key: city_dict[key]}) dub_city['bot_id'] = bot_2 new_city = City(**dub_city) new_city.save() goods = Good.objects(city_id=city.id.binary.hex()) for good in goods: if good is not None: Good(name=good.name, city_id=new_city.id.binary.hex(), price=good.price, description=good.description, photo=good.photo, districts=good.districts).save() payment = Payment.objects(bot_id=bot_id).first() if not (payment is None): payment_dict = loads(payment.to_json()) dub_payment = {} for key in payment_dict: if key != '_id': dub_payment.update({key: payment_dict[key]}) dub_payment['bot_id'] = bot_2 new_payment = Payment(**dub_payment) new_payment.save() return str(bot_2)
def upload(request): """ Uploads the receipt :url: /shoebox/upload/ :param POST['email']: email identifying user :param POST['business_name']: i.e. McDonalds (blank) :param POST['address']: business address (blank) :param POST['location']: i.e. JFK International (blank) :param POST['phone']: phone number (blank) :param POST['city']: city (blank) :param POST['state']: state (blank) :param POST['purchase_date']: purchase date in NeatReceipts format :param POST['tax']: tax (blank) :param POST['tip']: tip (blank) :param POST['amount']: total amount :param POST['payment_method']: Visa, Master, Cash etc :param POST['category']: NeatReceipts category :param FILES['img']: Receipts image :rtype: JSON :: #: if success in posting returns id of created or update object in string format {'result': 'id'} #: if failed {'result': '-1'} #: if request was not POST {'result': '0'} """ if request.method == 'POST': form = ReceiptUploadForm(request.POST, request.FILES) if form.is_valid(): instance = form.save(commit=False) # assign to the current user uploading data instance.user, created = OTNUserTemp.objects.get_or_create(email=request.POST['email']) instance.save() receipt = DetailReceipt(basic=instance) if 'business_name' in request.POST: b = Business(name=request.POST['business_name']) if 'location' in request.POST: b.location = request.POST['location'] if 'phone' in request.POST: b.phone = request.POST['phone'] if 'address' in request.POST: b.address = request.POST['address'] if 'city' in request.POST: c = City(name=request.POST['city'], state=request.POST['state']) c.save() b.city = c b.save() receipt.business = b if 'category' in request.POST: cat, created = Category.objects.get_or_create(name=request.POST['category']) receipt.category = cat if 'tax' in request.POST: receipt.tax = request.POST['tax'] if 'tip' in request.POST: receipt.tip = request.POST['tip'] if 'payment_method' in request.POST: pmethod = request.POST['payment_method'].lower() if pmethod.find('cash') != -1: receipt.payment_method = receipt.CASH elif pmethod.find('amex') != -1: receipt.payment_method = receipt.AMEX elif pmethod.find('visa') != -1: receipt.payment_method = receipt.VISA elif pmethod.find('master') != -1: receipt.payment_method = receipt.MASTER elif pmethod.find('discover') != -1: receipt.payment_method = receipt.DISCOVER else: receipt.payment_method = receipt.CASH receipt.save() return JSONHttpResponse({'result':str(receipt.id)}) else: return JSONHttpResponse({'result':'-1', 'form_errors':str(form.errors)}) else: return JSONHttpResponse({'result':'0'})
def addCity(name, x, y): city = City(name=name, xpos=x, ypos=y) city.save() return city.id