def main(): #parse args parser = argparser_prepare() args = parser.parse_args() setup_logging(args.config_uri) getLogger('sqlalchemy.engine').setLevel(ERROR) settings = get_appsettings(args.config_uri) engine = engine_from_config(settings, 'sqlalchemy.') DBSession.configure(bind=engine) log(INFO, "Export started...") if args.simple_roads: SimpleRoad.export_to_geojson_file(args.output_path) else: Way.export_to_geojson_file(args.output_path) if args.zip: log(INFO, "Zip file...") import zipfile zf = zipfile.ZipFile(args.output_path+'.zip', 'w', zipfile.ZIP_DEFLATED, allowZip64=True) zf.write(args.output_path) zf.close() os.remove(args.output_path) log(INFO, "Export successful!")
class SimpleRouter(): def __init__(self): self._session = DBSession() def get_route(self, from_point, to_point): #get edges start_edge_id = self.get_nearest_edge_id(from_point) if not start_edge_id: raise Exception('Start point is too far from road!') end_edge_id = self.get_nearest_edge_id(to_point) if not end_edge_id: raise Exception('End point is too far from road!') position = 0.5 # TODO: add proportion getter #request pgr_trsp = select(['id2'], from_obj=func.pgr_trsp(self.get_net_query(), start_edge_id, position, end_edge_id, position, False, False)).alias('trsp') try: route = self._session.query(SimpleRoad.id, SimpleRoad.name, SimpleRoad.name_short, SimpleRoad.road_no, SimpleRoad.road_uid, SimpleRoad.the_geom.ST_AsGeoJSON()).select_from(pgr_trsp).join(SimpleRoad, text('trsp.id2') == SimpleRoad.id).all() except InternalError, err: exc_desc = str(err) if 'Path Not Found' in exc_desc: raise Exception('Path Not Found') else: raise return route
def import_from_geojson_file(path_to_file): with open(path_to_file, 'r') as geojson_file: db_session = DBSession() content = geojson_file.read() json_file = json.loads(content) ways_geojson = geojson.loads(json.dumps(json_file['features'])) for way in ways_geojson: properties = way['properties'] properties['the_geom'] = shape.from_shape(asShape(way['geometry']), 4326) way_inst = SimpleRoad() way_inst.set_fields_from_dict(properties) db_session.add(way_inst) db_session.flush()
def get_value(request): session = DBSession() bridges_db = session.query(Bridge, Bridge.geometry.ST_AsGeoJSON()) result = { 'type': 'FeatureCollection', 'features': [] } for bridge_db in bridges_db: feature = { 'id':bridge_db[0].id, "type": "Feature", "geometry": json.loads(bridge_db[1]), 'properties': bridge_db[0].as_properties() } result['features'].append(feature) return result
def get_value(request): session = DBSession() gas_stations_db = session.query(GasStation, GasStation.geometry.ST_AsGeoJSON()) result = { 'type': 'FeatureCollection', 'features': [] } for gas_station_db in gas_stations_db: feature = { 'id': gas_station_db[0].id, "type": "Feature", "geometry": json.loads(gas_station_db[1]), 'properties': gas_station_db[0].as_properties() } result['features'].append(feature) return result
def export_to_geojson_file(path_to_file): with open(path_to_file, 'w') as ways_geojson_file: db_session = DBSession() count = db_session.query(SimpleRoad).count() log(INFO, 'Total ways: %s' % count) log(INFO, 'Get data...') all_ways = db_session.query(SimpleRoad, SimpleRoad.the_geom.ST_AsGeoJSON()).all() # limit(500) # test #create json output_content = { 'type': 'FeatureCollection', 'generator': 'rosavto-data', 'copyright': 'The data included in this document is from www.openstreetmap.org. The data is made available under ODbL.', 'timestamp': datetime.utcnow().strftime('%Y-%m-%dT%H:%M:%S'), 'features': [] } handled = 0 for way in all_ways: #create feat feature = { 'type': 'Feature', 'id': way[0].id, 'geometry': json.loads(way[1]), 'properties': {} } #set attrs for prop, val in way[0].as_properties().items(): feature['properties'][prop] = val #add id column explicit feature['properties']['id'] = way[0].id #add to collection output_content['features'].append(feature) #log handled += 1 if handled % 1000 == 0: log(INFO, 'Handled: %s' % handled) json.dump(output_content, ways_geojson_file, indent=4)
def main(global_config, **settings): """ This function returns a Pyramid WSGI application. """ engine = engine_from_config(settings, 'sqlalchemy.') DBSession.configure(bind=engine) Base.metadata.bind = engine config = Configurator(settings=settings) config.include('pyramid_mako') config.include("cornice") config.add_static_view('static', 'static', cache_max_age=3600) config.add_route('map', '/') config.add_route('layer', '/layer') config.add_route('marker', '/marker') config.add_route('wms', '/wms') config.add_route('realtime', '/realtime') config.add_route('attributes', '/attributes') config.add_route('attributes_html', '/gis/card') config.add_route('incident', '/incident') config.add_route('center', '/center') config.add_route('routing_sample', '/routing_sample') config.add_route('routing_chainage_sample', '/routing_chainage_sample') config.add_route('code', '/code') config.add_route('time', '/time') config.add_route('clusters', '/clusters') config.add_route('sensors', '/sensors') config.add_route('object_selector', '/object_selector') config.add_route('repairs', '/repairs') config.add_route('repairs_status', '/repairs/status') # proxies url config.add_route('proxy_ngw', '/ngw/*target_url') config.add_route('proxy_cit', '/cit/*target_url') # routing url config.add_route('routing', '/routing') config.add_route('simple_routing', '/simple_routing') config.scan() return config.make_wsgi_app()
def main(argv=sys.argv): if len(argv) != 2: usage(argv) config_uri = argv[1] setup_logging(config_uri) settings = get_appsettings(config_uri) engine = engine_from_config(settings, "sqlalchemy.") DBSession.configure(bind=engine) Base.metadata.drop_all(engine) Base.metadata.create_all(engine) with transaction.manager: GasStation.import_from_geojson_file("rosavto/initializedb/data/fuel.geojson") Bridge.import_from_geojson_file("rosavto/initializedb/data/bridges.geojson") # load ways for routing json_path = "rosavto/initializedb/data/ways.geojson" zf_path = "rosavto/initializedb/data/ways.geojson.zip" if os.path.isfile(zf_path): # try open zip zf = zipfile.ZipFile(zf_path) zf.extractall(path="rosavto/initializedb/data/") Way.import_from_geojson_file(json_path) # load simple_roads json_path = "rosavto/initializedb/data/simple_roads.geojson" SimpleRoad.import_from_geojson_file(json_path)
class Router: def __init__(self): self._session = DBSession() def get_route(self, from_point, to_point, barrier_points=[]): # get edges start_edge_id = self.get_nearest_edge_id(from_point) if not start_edge_id: raise Exception("Start point is too far from road!") end_edge_id = self.get_nearest_edge_id(to_point) if not end_edge_id: raise Exception("End point is too far from road!") # get barriers edges barrier_edge_ids = [] for bar_point in barrier_points: bar_edge_id = self.get_nearest_edge_id(bar_point) barrier_edge_ids.append(bar_edge_id) position = 0.5 # TODO: add proportion getter # request pgr_trsp = select( ["id2"], from_obj=func.pgr_trsp( self.get_net_query(), start_edge_id, position, end_edge_id, position, True, True, self.get_restrict_query(barrier_edge_ids), ), ).alias("trsp") try: route = ( self._session.query(Way.gid, Way.name, Way.osm_id, Way.length, Way.the_geom.ST_AsGeoJSON()) .select_from(pgr_trsp) .join(Way, text("trsp.id2") == Way.gid) .all() ) except InternalError, err: exc_desc = str(err) if "Path Not Found" in exc_desc: raise Exception("Path Not Found") else: raise return route
def test_dbsession_configure(self): try: DBSession.configure(bind=self.engine) except: self.fail('DBSession configure is failed')
def __init__(self): self._session = DBSession()