def getTownList(request): """ Loads the list of the cadastres of the Canton.""" results = {} if 'numcad' in Town.__table__.columns.keys(): results = DBSession.query(Town).order_by(Town.numcad.asc()).all() else: results = DBSession.query(Town).order_by(Town.numcom.asc()).all() towns = [] for town in results: if 'numcad' in Town.__table__.columns.keys(): numcad = town.numcad cadnom = town.cadnom else: numcad = None cadnom = None towns.append({ 'idobj': town.idobj, 'numcom': town.numcom, 'comnom': town.comnom, 'numcad': numcad, 'cadnom': cadnom, 'nufeco': town.nufeco }) return towns
def get_cached_content(request): d = {} canton_logo = DBSession.query(AppConfig).filter_by( parameter='cantonlogopath').first() ch_logo = DBSession.query(AppConfig).filter_by( parameter='CHlogopath').first() crdppf_logo = DBSession.query(AppConfig).filter_by( parameter='crdppflogopath').first() d['canton_logo'] = '/'.join([ request.registry.settings['localhost_url'], 'proj/images', canton_logo.paramvalue ]) d['ch_logo'] = '/'.join([ request.registry.settings['localhost_url'], 'proj/images', ch_logo.paramvalue ]) d['crdppf_logo'] = '/'.join([ request.registry.settings['localhost_url'], 'proj/images', crdppf_logo.paramvalue ]) return d
def get_cached_content_l10n(lang): d = {} # First get all the translated strings for the selected language translations = DBSession.query(Translations).all() for translation in translations: if getattr(translation, lang): d[str(translation.varstr)] = getattr(translation, lang) else: log.warning("There is a undefined translation") d[str(translation.varstr)] = u'undefined' # Second get all the definitions for the selected language glossar = DBSession.query(Glossar).filter_by(lang=lang).all() abbreviations = [] for term in glossar: if not term.expression == '' or term.definition == '': abbreviations.append([term.expression, term.definition]) else: log.warning("There is a empty definition") d["glossar"] = [{ "glossarlabel": d["pdfGlossarLabel"], "definitions": { "columns": ["term", "definition"], "data": abbreviations } }] return d
def get_interface_config(request): """Return a JSON file including all the parameters required to configure the interface """ themes = DBSession.query(Themes).filter_by(publish=True).order_by(Themes.order).all() themeList = [] for theme in themes: layers = DBSession.query(Layers).filter_by(theme_id=theme.id).filter_by(baselayer=False).all() layerDico = {} for layer in layers: layerDico[layer.layername] = layer.layername themeList.append({'id': theme.id, 'image': theme.image, 'name': theme.varstr, 'layers': layerDico}) return {"type": "ThemesCollection", "themes": themeList}
def get_features_function(parcelGeom, params): # split the layer list string into proper python list csvReader = csv.reader([params['layerList']], skipinitialspace=True) # iterate over layer and make intersects queries itemList = [] for item in csvReader: itemList.append(item) layerList = itemList[0] # test = 'empty' # # retrieve models from table2model # for layer in layerList: # model = table2model_match[layer] # spatial analysis featureList = [] for layer in layerList: targetModel = table2model_match[layer] intersectResult = DBSession.query(targetModel).filter(or_(targetModel.geom.ST_Intersects(parcelGeom), targetModel.geom.ST_Within(parcelGeom))).all() if intersectResult: # create geojson output with custom attributes for feature in intersectResult: geometryType = DBSession.scalar(feature.geom.ST_GeometryType()) geomType = '' intersectionMeasure = -9999 intersectionMeasureTxt = '' if geometryType == 'ST_Polygon' or geometryType == 'ST_MultiPolygon': intersectionMeasure = DBSession.scalar(feature.geom.ST_Intersection(parcelGeom).ST_Area()) if intersectionMeasure >= 1: intersectionMeasureTxt = ' : ' + str(int(round(intersectionMeasure, 0))) + ' [m2]' geomType = 'Polygone' jsonFeature = sloads(dumps(feature)) jsonFeature['properties']['layerName'] = layer jsonFeature['properties']['intersectionMeasure'] = intersectionMeasureTxt jsonFeature['properties']['geomType'] = 'area' featureList.append(jsonFeature) elif geometryType == 'ST_Line' or geometryType == 'ST_MultiLineString' or geometryType == 'ST_LineString': intersectionMeasure = DBSession.scalar(feature.geom.ST_Intersection(parcelGeom).ST_Length()) if intersectionMeasure >= 1: intersectionMeasureTxt = ' : ' + str(int(round(intersectionMeasure, 0))) + ' [m]' geomType = 'Ligne' jsonFeature = sloads(dumps(feature)) jsonFeature['properties']['layerName'] = layer jsonFeature['properties']['intersectionMeasure'] = intersectionMeasureTxt jsonFeature['properties']['geomType'] = 'line' featureList.append(jsonFeature) elif geometryType == 'ST_Point' or geometryType == 'ST_MultiPoint': featureMeasure = -9999 geomType = 'Point' intersectionMeasureTxt = ' ' # ' : point' jsonFeature = sloads(dumps(feature)) jsonFeature['properties']['layerName'] = layer jsonFeature['properties']['intersectionMeasure'] = intersectionMeasureTxt jsonFeature['properties']['geomType'] = 'point' featureList.append(jsonFeature) return featureList
def get_print_format(bbox, fitRatio): """Detects the best paper format and scale in function of the general form and size of the parcel This function determines the optimum scale and paper format (if different paper formats are available) for the pdf print in dependency of the general form of the selected parcel. """ printFormat = {} # !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! # Enhancement : take care of a preselected paper format by the user # =================== formatChoice = 'A4' # if fixedpaperformat == True: # paperFormats = {predefinedPaperFormat} # else: # Gets the list of all available formats and their parameters : name, orientation, height, width paperFormats = DBSession.query(PaperFormats).order_by( PaperFormats.scale.asc()).order_by( PaperFormats.orientation.desc()).all() fit = 'false' # fitRation defines the minimum spare space between the property limits and the map border. Here 10% # fitRatio = 0.9 ratioW = 0 ratioH = 0 # Attention X and Y are standard carthesian and inverted in comparison to the Swiss Coordinate System deltaX = bbox['maxX'] - bbox['minX'] deltaY = bbox['maxY'] - bbox['minY'] resolution = 150 # 150dpi print resolution ratioInchMM = 25.4 # conversion inch to mm # Decides what parcel orientation if deltaX >= deltaY: # landscape bboxWidth = deltaX bboxHeight = deltaY else: # portrait bboxWidth = deltaY bboxHeight = deltaX # Get the appropriate paper format for the print for paperFormat in paperFormats: ratioW = bboxWidth * 1000 / paperFormat.width / paperFormat.scale ratioH = bboxHeight * 1000 / paperFormat.height / paperFormat.scale if ratioW <= fitRatio and ratioH <= fitRatio: printFormat.update(paperFormat.__dict__) printFormat['mapHeight'] = int(printFormat['height'] / ratioInchMM * resolution) printFormat['mapWidth'] = int(printFormat['width'] / ratioInchMM * resolution) fit = 'true' break return printFormat
def main(): """ Script to parse all the icons for the legends of the public land restrictions application """ parser = argparse.ArgumentParser(description=__doc__) parser.add_argument( "-i", "--app-config", default="production.ini", dest="app_config", help="The application .ini config file (optional, default is " "'production.ini')") parser.add_argument( "-d", "--db-config", default="config_db.yaml", dest="db_config", help="The application db config file (optional, default is " "'config_db.yaml')") parser.add_argument( "-p", "--pdf-config", default="config_pdf.yaml", dest="pdf_config", help="The application pdf config file (optional, default is " "'config_pdf.yaml')") options = parser.parse_args() app_config = options.app_config if not os.path.isfile(app_config): parser.error("Cannot find config file: {0!s}".format(app_config)) myapp = get_app(app_config) configs = {} for key, value in myapp.registry.settings.iteritems(): configs[key] = value if key == 'app_config': for k, v in configs['app_config'].iteritems(): configs[k] = v if key == 'pdf_config': for k, v in configs['pdf_config'].iteritems(): configs[k] = v wmsconfigs = set_wms_config(configs) from crdppf.models import DBSession, Layers session = DBSession() layers = session.query(Layers).all() for layer in layers: if layer.baselayer is False: iconizer(layer, wmsconfigs, configs)
def get_interface_config(request): """Return a JSON file including all the parameters required to configure the interface """ themes = DBSession.query(Themes).filter_by(publish=True).order_by( Themes.order).all() themeList = [] for theme in themes: layers = DBSession.query(Layers).filter_by( theme_id=theme.id).filter_by(baselayer=False).all() layerDico = {} for layer in layers: layerDico[layer.layername] = layer.layername themeList.append({ 'id': theme.id, 'image': theme.image, 'name': theme.varstr, 'layers': layerDico }) return {"type": "ThemesCollection", "themes": themeList}
def get_document_ref(docfilters=None): """ Gets all the id's of the documents referenced by an object, layer, topic or document. """ referenceslist = set() rereferenceslist = set() if docfilters: for filtercriteria in docfilters: references = DBSession.query(OriginReference).filter_by( fkobj=filtercriteria ).all() if references is not None: for reference in references: referenceslist.add(reference.docid) else: references = DBSession.query(OriginReference).all() for reference in references: referenceslist.add(reference.docid) # check if a referenced document references an other one if referenceslist is not None: for reference in referenceslist: rereferences = DBSession.query(OriginReference).filter_by( fkobj=str(reference) ).all() if rereferences is not None: for rereference in rereferences: rereferenceslist.add(rereference.docid) if rereferenceslist is not None: for rereference in rereferenceslist: if rereference not in referenceslist: referenceslist.add(rereference) return referenceslist
def read_app_config(settings): """ Read the initial app config """ from crdppf.models import DBSession, Base, AppConfig results = {} results = DBSession.query(AppConfig).all() for result in results : settings['app_config'].update({str(result.parameter):str(result.paramvalue)}) return True
def get_print_format(bbox, fitRatio): """Detects the best paper format and scale in function of the general form and size of the parcel This function determines the optimum scale and paper format (if different paper formats are available) for the pdf print in dependency of the general form of the selected parcel. """ printFormat = {} #!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! # Enhancement : take care of a preselected paper format by the user # =================== formatChoice = 'A4' # if fixedpaperformat == True: # paperFormats = {predefinedPaperFormat} # else: # Gets the list of all available formats and their parameters : name, orientation, height, width paperFormats = DBSession.query(PaperFormats).order_by(PaperFormats.scale.asc()).order_by(PaperFormats.orientation.desc()).all() fit = 'false' # fitRation defines the minimum spare space between the property limits and the map border. Here 10% # fitRatio = 0.9 ratioW = 0 ratioH = 0 # Attention X and Y are standard carthesian and inverted in comparison to the Swiss Coordinate System deltaX = bbox['maxX'] - bbox['minX'] deltaY = bbox['maxY'] - bbox['minY'] resolution = 150 # 150dpi print resolution ratioInchMM = 25.4 # conversion inch to mm # Decides what parcel orientation if deltaX >= deltaY : # landscape bboxWidth = deltaX bboxHeight = deltaY else : # portrait bboxWidth = deltaY bboxHeight = deltaX # Get the appropriate paper format for the print for paperFormat in paperFormats : ratioW = bboxWidth*1000/paperFormat.width/paperFormat.scale ratioH = bboxHeight*1000/paperFormat.height/paperFormat.scale if ratioW <= fitRatio and ratioH <= fitRatio : printFormat.update(paperFormat.__dict__) printFormat['mapHeight'] = int(printFormat['height']/ratioInchMM*resolution) printFormat['mapWidth'] = int(printFormat['width']/ratioInchMM*resolution) fit = 'true' break return printFormat
def get_document_ref(docfilters=None): """ Gets all the id's of the documents referenced by an object, layer, topic or document. """ referenceslist = set() rereferenceslist = set() if docfilters: for filtercriteria in docfilters: references = DBSession.query(OriginReference).filter_by( fkobj=filtercriteria).all() if references is not None: for reference in references: referenceslist.add(reference.docid) else: references = DBSession.query(OriginReference).all() for reference in references: referenceslist.add(reference.docid) # check if a referenced document references an other one if referenceslist is not None: for reference in referenceslist: rereferences = DBSession.query(OriginReference).filter_by( fkobj=str(reference)).all() if rereferences is not None: for rereference in rereferences: rereferenceslist.add(rereference.docid) if rereferenceslist is not None: for rereference in rereferenceslist: if rereference not in referenceslist: referenceslist.add(rereference) return referenceslist
def main(): """ Script to parse all the icons for the legends of the public land restrictions application """ parser = argparse.ArgumentParser(description=__doc__) parser.add_argument( "-i", "--app-config", default="production.ini", dest="app_config", help="The application .ini config file (optional, default is " "'production.ini')" ) parser.add_argument( "-d", "--db-config", default="config_db.yaml", dest="db_config", help="The application db config file (optional, default is " "'config_db.yaml')" ) parser.add_argument( "-p", "--pdf-config", default="config_pdf.yaml", dest="pdf_config", help="The application pdf config file (optional, default is " "'config_pdf.yaml')" ) options = parser.parse_args() app_config = options.app_config if not os.path.isfile(app_config): parser.error("Cannot find config file: {0!s}".format(app_config)) myapp = get_app(app_config) configs = {} for key, value in myapp.registry.settings.iteritems(): configs[key] = value if key == 'app_config': for k, v in configs['app_config'].iteritems(): configs[k] = v if key == 'pdf_config': for k, v in configs['pdf_config'].iteritems(): configs[k] = v wmsconfigs = set_wms_config(configs) from crdppf.models import DBSession, Layers session = DBSession() layers = session.query(Layers).all() for layer in layers: if layer.baselayer is False: iconizer(layer, wmsconfigs, configs)
def get_baselayers_config(request): """Return a JSON file defining the base layers """ layers = DBSession.query(Layers).filter_by(baselayer=True).order_by(Layers.layerid).all() layerList = [] for layer in layers: layerDico = {} layerDico['id'] = layer.layerid layerDico['image'] = layer.image layerDico['name'] = layer.layername layerDico['wmtsname'] = layer.wmtsname layerDico['tile_format'] = layer.tile_format layerList.append(layerDico) return {'baseLayers': layerList}
def get_translations(lang): """Loads the translations for all the multilingual labels """ locals = {} lang_dict = { 'fr': Translations.fr, 'de': Translations.de, 'it': Translations.it, 'en': Translations.en } translations = DBSession.query(Translations.varstr, lang_dict[lang]).all() for key, value in translations: locals[str(key)] = value return locals
def get_translations(lang): """Loads the translations for all the multilingual labels """ locals = {} lang_dict = { 'fr': Translations.fr, 'de': Translations.de, 'it': Translations.it, 'en': Translations.en } translations = DBSession.query(Translations.varstr, lang_dict[lang]).all() for key, value in translations : locals[str(key)] = value return locals
def get_baselayers_config(request): """Return a JSON file defining the base layers """ layers = DBSession.query(Layers).filter_by(baselayer=True).order_by( Layers.layerid).all() layerList = [] for layer in layers: layerDico = {} layerDico['id'] = layer.layerid layerDico['image'] = layer.image layerDico['name'] = layer.layername layerDico['wmtsname'] = layer.wmtsname layerDico['tile_format'] = layer.tile_format layerList.append(layerDico) return {'baseLayers': layerList}
def get_feature_center(id): """ Extract a feature centroid regarding its id attribute """ geom = DBSession.query(Property.geom).filter(Property.id == id).all() if len(geom) > 1: return False else: geom = geom[0][0] return [ DBSession.scalar(geom.ST_Centroid().ST_X()), DBSession.scalar(geom.ST_Centroid().ST_Y()) ]
def getTopicsList(request): """ Loads the list of the topics.""" results = {} results = DBSession.query(Topics).order_by(Topics.topicid.asc()).all() topics = [] for topic in results: topics.append({ 'topicid': topic.topicid, 'topicname': topic.topicname, 'authorityfk': topic.authorityfk, # 'publicationdate': topic.publicationdate.isoformat(), 'topicorder': topic.topicorder }) return topics
def get_feature_bbox(id): """ Extract a feature centroid regarding its id attribute """ box = DBSession.query(func.ST_extent(Property.geom)). \ filter(Property.id == id).all() if len(box) > 1: return False else: box = box[0][0] box = box.split('(')[1].split(')')[0].replace(',', ' ').split(' ') return { 'minX': float(box[0]), 'minY': float(box[1]), 'maxX': float(box[2]), 'maxY': float(box[3]), }
def getParcelGeom(parcelId): """ Return the parcel geometry for a given parcel ID """ queryParcel = DBSession.query(Property).filter_by(id=parcelId).first() parcelGeom = queryParcel.geom return parcelGeom
def get_translations_list(request): """Loads the translations for all the multilingual labels """ try: limit = int(request.params['limit']) start = int(request.params['start']) except: limit = 25 start = 0 if request.params['sort'] == 'id': sort = 'Translations.id' else: sort = request.params['sort'] sort += ' '+request.params['dir'] filter = None filter_params = {} try: filter_params = request.params['filter'] filter_params = simplejson.loads(filter_params) except KeyError: filter_params = None if filter_params is None: totalCount = int(DBSession.query(Translations).count()) else: totalCount = '999' translationslist = DBSession.query(Translations).order_by(Translations.id).offset(start).limit(limit).all() #~ if filter_params is not None : #~ for filterparam in filter_params : #~ if filterparam['type'] == 'numeric': #~ if filterparam['field'] == 'id_user': #~ filterparam['field'] = '\"order\".id_user' #~ if filterparam['comparison'] == 'eq': #~ filter = str(filterparam['field'])+'='+str(filterparam['value']) #~ elif filterparam['comparison'] == 'lt': #~ filter = str(filterparam['field'])+'<'+str(filterparam['value']) #~ elif filterparam['comparison'] == 'gt' : #~ filter = str(filterparam['field'])+'>'+str(filterparam['value']) #~ orderlist = orderlist.filter(filter) #~ if filterparam['type'] == 'date': #~ if filterparam['comparison'] == 'eq': #~ filter = str(filterparam['field'])+'=\''+filterparam['value']+'\'' #~ elif filterparam['comparison'] == 'lt': #~ filter = str(filterparam['field'])+'<\''+str(filterparam['value'])+'\'' #~ elif filterparam['comparison'] == 'gt' : #~ filter = str(filterparam['field'])+'>\''+str(filterparam['value'])+'\'' #~ orderlist = orderlist.filter(filter) #~ elif filterparam['type'] == 'string': #~ orderlist = orderlist.filter(getattr(Order, filterparam['field']).like("%%%s%%" % filterparam['value'])) #~ elif filterparam['type'] == 'boolean': #~ filter = str(filterparam['field'])+'='+str(filterparam['value']) #~ orderlist = orderlist.filter(filter) #~ elif filterparam['type'] == 'list': #~ for option in filterparam['value']: #~ filter = str(filterparam['field']) + '=\'' + str(option) +'\'' #~ orderlist = orderlist.filter(filter) #~ orderlist = orderlist.order_by(sort).offset(start).limit(limit) #~ else : #~ orderlist =sessionDB.query(Order).order_by(sort).offset(start).limit(limit).all() results = DBSession.query(Translations).all() list = [] for result in results: list.append({ 'id': result.id, 'varstr': result.varstr, 'de': result.de, 'fr': result.fr, 'it': result.it, 'ro': result.ro, 'en': result.en }) translations={ 'translations': list, 'totalCount':totalCount } return translations #~ def get_translations_list(request): #~ session = request.session #~ try: #~ session['role'] #~ except KeyError : #~ return HTTPForbidden() #~ if int(session['role']) != 1 or session['login'] == False: #~ return HTTPForbidden() #~ sessionDB = DBSession() #~ limit = int(request.params['limit']) #~ start = int(request.params['start']) #~ status ='' #~ try: #~ status = int(request.params['order_state']) #~ except: #~ status = None #~ pass #~ if request.params['sort'] == "id_user": #~ sort = "\"order\".id_user" #~ else: #~ sort = request.params['sort'] #~ sort += ' '+request.params['dir'] #~ filter = '' #~ filter_params = {} #~ try: #~ filter_params = request.params['filter'] #~ filter_params = simplejson.loads(filter_params) #~ except KeyError: #~ filter_params = None #~ if status is None: #~ totalCount = int(sessionDB.query(Order).count()) #~ else: #~ totalCount = int(sessionDB.query(Order).filter(Order.order_state==0).count()) #~ orderlist = sessionDB.query(Order) #~ if status == 0 and filter_params is not None: #~ filter_params.append({u'comparison': u'eq', u'type': u'numeric', u'value': 0, u'field': u'order_state'}) #~ elif status == 0 : #~ filter_params=[{u'comparison': u'eq', u'type': u'numeric', u'value': 0, u'field': u'order_state'}] #~ #orderlist = orderlist.filter('order_state=0') #~ if filter_params is not None : #~ for filterparam in filter_params : #~ if filterparam['type'] == 'numeric': #~ if filterparam['field'] == 'id_user': #~ filterparam['field'] = '\"order\".id_user' #~ if filterparam['comparison'] == 'eq': #~ filter = str(filterparam['field'])+'='+str(filterparam['value']) #~ elif filterparam['comparison'] == 'lt': #~ filter = str(filterparam['field'])+'<'+str(filterparam['value']) #~ elif filterparam['comparison'] == 'gt' : #~ filter = str(filterparam['field'])+'>'+str(filterparam['value']) #~ orderlist = orderlist.filter(filter) #~ if filterparam['type'] == 'date': #~ if filterparam['comparison'] == 'eq': #~ filter = str(filterparam['field'])+'=\''+filterparam['value']+'\'' #~ elif filterparam['comparison'] == 'lt': #~ filter = str(filterparam['field'])+'<\''+str(filterparam['value'])+'\'' #~ elif filterparam['comparison'] == 'gt' : #~ filter = str(filterparam['field'])+'>\''+str(filterparam['value'])+'\'' #~ orderlist = orderlist.filter(filter) #~ elif filterparam['type'] == 'string': #~ orderlist = orderlist.filter(getattr(Order, filterparam['field']).like("%%%s%%" % filterparam['value'])) #~ elif filterparam['type'] == 'boolean': #~ filter = str(filterparam['field'])+'='+str(filterparam['value']) #~ orderlist = orderlist.filter(filter) #~ elif filterparam['type'] == 'list': #~ for option in filterparam['value']: #~ filter = str(filterparam['field']) + '=\'' + str(option) +'\'' #~ orderlist = orderlist.filter(filter) #~ orderlist = orderlist.order_by(sort).offset(start).limit(limit) #~ else : #~ orderlist =sessionDB.query(Order).order_by(sort).offset(start).limit(limit).all() #~ result = list() #~ for row in orderlist: #~ # Check if there are products type like #~ products = ast.literal_eval(row.order_products) #~ is_mo = "" #~ for product in products: #~ product_id = product['id'] #~ is_mensuration = sessionDB.query(Product).get(product_id) #~ if is_mensuration: #~ is_mensuration = is_mensuration.is_mensuration #~ else: #~ is_mensuration = False #~ if is_mo == "" and is_mensuration: #~ is_mo = "Oui" #~ if is_mo == "" and is_mensuration is False: #~ is_mo = "Non" #~ if is_mo == "Non" and is_mensuration: #~ is_mo = "Oui/Non" #~ if is_mo == "Oui" and is_mensuration is False: #~ is_mo = "Oui/Non" #~ if row.invoice_diff: #~ str_invoice_diff = "Oui" #~ else: #~ str_invoice_diff = "Non" #~ if row.delivery_date is None: #~ d={ #~ 'id_order': row.id_order, #~ 'id_order_millis': row.id_order_millis, #~ 'mandat_title': row.mandat_title, #~ 'order_date': row.order_date.isoformat(), #~ 'mandat_info': row.mandat_info, #~ 'mandat_type': row.mandat_type, #~ 'invoice_diff': str_invoice_diff, #~ 'order_products': row.order_products, #~ 'order_state': row.order_state, #~ 'pdf_name': row.pdf_name, #~ 'id_user': row.id_user, #~ 'is_mo': is_mo #~ } #~ else: #~ d={ #~ 'id_order': row.id_order, #~ 'id_order_millis': row.id_order_millis, #~ 'mandat_title': row.mandat_title, #~ 'order_date': row.order_date.isoformat(), #~ 'delivery_date': row.delivery_date.isoformat(), #~ 'mandat_info': row.mandat_info, #~ 'mandat_type': row.mandat_type, #~ 'invoice_diff': str_invoice_diff, #~ 'order_products': row.order_products, #~ 'order_state': row.order_state, #~ 'pdf_name': row.pdf_name, #~ 'id_user': row.id_user, #~ 'is_mo': is_mo #~ } #~ result.append(d) #~ result2={ #~ 'commandes':result, #~ 'totalCount':totalCount #~ } #~ json= simplejson.dumps(result2) #~ return Response(json,content_type='application/json; charset=utf-8')
def get_documents(filters=None): """ Gets all the legal documents related to a feature. """ doclist = [] documents = {} if filters: documents = DBSession.query(LegalDocuments).filter( LegalDocuments.docid.in_(filters['docids'])) if 'cadastrenb' in filters.keys(): documents = documents.filter( or_(LegalDocuments.cadastrenb == None, LegalDocuments.cadastrenb == filters['cadastrenb'])).order_by( LegalDocuments.doctype.asc()) if 'chmunicipalitynb' in filters.keys(): documents = documents.filter( or_( LegalDocuments.chmunicipalitynb == filters['chmunicipalitynb'], LegalDocuments.chmunicipalitynb == None)).order_by( LegalDocuments.doctype.asc()) else: documents = DBSession.query(LegalDocuments).order_by( LegalDocuments.doctype.asc()).order_by( LegalDocuments.state.asc()).order_by( LegalDocuments.chmunicipalitynb.asc()).order_by( LegalDocuments.cadastrenb.asc()) documents = documents.order_by(LegalDocuments.doctype.asc()).order_by( LegalDocuments.state.asc()).order_by( LegalDocuments.chmunicipalitynb.asc()).order_by( LegalDocuments.cadastrenb.asc()).all() for document in documents: origins = [] for origin in document.origins: origins.append(origin.fkobj) doclist.append({ 'documentid': document.docid, 'doctype': document.doctypes.value, 'lang': document.lang, 'state': document.state, 'chmunicipalitynb': document.chmunicipalitynb, 'municipalitynb': document.municipalitynb, 'municipalityname': document.municipalityname, 'cadastrenb': document.cadastrenb, 'title': document.title, 'officialtitle': document.officialtitle, 'abbreviation': document.abbreviation, 'officialnb': document.officialnb, 'legalstate': document.legalstates.value, 'remoteurl': document.remoteurl, 'localurl': document.localurl, 'sanctiondate': document.sanctiondate.isoformat() if document.sanctiondate else None, 'abolishingdate': document.abolishingdate.isoformat() if document.abolishingdate else None, 'entrydate': document.entrydate.isoformat() if document.entrydate else None, 'publicationdate': document.publicationdate.isoformat() if document.publicationdate else None, 'revisiondate': document.revisiondate.isoformat() if document.revisiondate else None, 'operator': document.operator, 'origins': origins }) return doclist
def initjs(request): session = request.session # Define language to get multilingual labels for the selected language # defaults to 'fr': french - this may be changed in the appconfig if 'lang' not in session: lang = request.registry.settings['default_language'].lower() else: lang = session['lang'].lower() lang_dict = { 'fr': Translations.fr, 'de': Translations.de, 'it': Translations.it, 'en': Translations.en } locals = {} translations = DBSession.query(Translations.varstr, lang_dict[lang]).all() for key, value in translations: if value is not None: locals[str(key)] = value.replace("'", "\\'").replace("\n", "\\n") else: locals[str(key)] = '' layerlist = [] baselayers = [] # get all layers layers = DBSession.query(Layers).order_by(Layers.layerid).all() baselayerexists = False for layer in layers: if layer.baselayer is True: baselayerexists = True layerDico = {} layerDico['id'] = layer.layerid layerDico['image'] = layer.image layerDico['name'] = layer.layername layerDico['wmtsname'] = layer.wmtsname layerDico['tile_format'] = layer.tile_format baselayers.append(layerDico) else: layerlist.append({ 'layerid': layer.layerid, 'layername': layer.layername.replace("'", "\\'"), 'layerdescription': layer.layerdescription.replace("'", "\\'"), 'layeravailability': layer.layeravailability.replace("'", "\\'"), 'wmtsname': layer.wmtsname, 'layermetadata': layer.layermetadata, 'assentdate': layer.assentdate, 'baselayer': layer.baselayer, 'image': layer.image, 'publicationdate': layer.publicationdate, 'theme_id': layer.theme_id, 'updatedate': layer.updatedate, 'topicfk': layer.topicfk }) if baselayerexists is False: if request.registry.settings['defaultTiles']: defaultTiles = {} defaultlayer = str( request.registry.settings['defaultTiles']).split(',') for param in defaultlayer: key, value = param.replace("'", '').split(':') defaultTiles[key] = value layerDico = {} layerDico['id'] = '9999' layerDico['image'] = None layerDico['name'] = 'default_layer' layerDico['wmtsname'] = defaultTiles['wmtsname'] layerDico['tile_format'] = defaultTiles['tile_format'] baselayers.append(layerDico) try: disclaimer = request.registry.settings['disclaimer'] if disclaimer == 'False' or request.registry.settings[ 'disclaimer'] == 'false': disclaimer = False except: disclaimer = True init = { 'fr': locals, 'layerlist': layerlist, 'baseLayers': baselayers, 'disclaimer': disclaimer } request.response.content = 'application/javascript' return init
def initjs(request): session = request.session # Define language to get multilingual labels for the selected language # defaults to 'fr': french - this may be changed in the appconfig if 'lang' not in session: lang = request.registry.settings['default_language'].lower() else : lang = session['lang'].lower() lang_dict = { 'fr': Translations.fr, 'de': Translations.de, 'it': Translations.it, 'en': Translations.en } locals = {} translations = DBSession.query(Translations.varstr, lang_dict[lang]).all() for key, value in translations : if value is not None: locals[str(key)] = value.replace("'","\\'").replace("\n","\\n") else: locals[str(key)] = '' layerlist = [] baselayers = [] # get all layers layers = DBSession.query(Layers).order_by(Layers.layerid).all() baselayerexists = False for layer in layers: if layer.baselayer == True: baselayerexists = True layerDico = {} layerDico['id'] = layer.layerid layerDico['image'] = layer.image layerDico['name'] = layer.layername layerDico['wmtsname'] = layer.wmtsname layerDico['tile_format'] = layer.tile_format baselayers.append(layerDico) else: layerlist.append({ 'layerid': layer.layerid, 'layername': layer.layername.replace("'","\\'"), 'layerdescription': layer.layerdescription.replace("'","\\'"), 'layeravailability': layer.layeravailability.replace("'","\\'"), 'wmtsname': layer.wmtsname, 'layermetadata': layer.layermetadata, 'assentdate': layer.assentdate, 'baselayer': layer.baselayer, 'image': layer.image, 'publicationdate': layer.publicationdate, 'theme_id': layer.theme_id, 'updatedate': layer.updatedate, 'topicfk': layer.topicfk }) if baselayerexists == False : if request.registry.settings['defaultTiles']: defaultTiles = {} defaultlayer = str(request.registry.settings['defaultTiles']).split(',') for param in defaultlayer: key, value = param.replace("'",'').split(':') defaultTiles[key] = value layerDico = {} layerDico['id'] = '9999' layerDico['image'] = None layerDico['name'] = 'default_layer' layerDico['wmtsname'] = defaultTiles['wmtsname'] layerDico['tile_format'] = defaultTiles['tile_format'] baselayers.append(layerDico) disclaimer = True if request.registry.settings['disclaimer']: if request.registry.settings['disclaimer'] == 'False' or request.registry.settings['disclaimer'] == 'false': disclaimer = None else: disclaimer = request.registry.settings['disclaimer'] init = {'fr': locals,'layerlist': layerlist, 'baseLayers': baselayers, 'disclaimer': disclaimer} request.response.content = 'application/javascript' return init
def get_documents(filters=None): """ Gets all the legal documents related to a feature. """ doclist = [] documents = {} if filters: documents = DBSession.query(LegalDocuments).filter( LegalDocuments.docid.in_(filters['docids']) ) if 'cadastrenb' in filters.keys(): documents = documents.filter(or_( LegalDocuments.cadastrenb == None, LegalDocuments.cadastrenb == filters['cadastrenb'] )).order_by(LegalDocuments.doctype.asc()) if 'chmunicipalitynb' in filters.keys(): documents = documents.filter(or_( LegalDocuments.chmunicipalitynb == filters['chmunicipalitynb'], LegalDocuments.chmunicipalitynb == None )).order_by(LegalDocuments.doctype.asc()) else: documents = DBSession.query(LegalDocuments).order_by( LegalDocuments.doctype.asc() ).order_by( LegalDocuments.state.asc() ).order_by( LegalDocuments.chmunicipalitynb.asc() ).order_by( LegalDocuments.cadastrenb.asc() ) documents = documents.order_by( LegalDocuments.doctype.asc() ).order_by( LegalDocuments.state.asc() ).order_by( LegalDocuments.chmunicipalitynb.asc() ).order_by( LegalDocuments.cadastrenb.asc() ).all() for document in documents: origins = [] for origin in document.origins: origins.append(origin.fkobj) doclist.append({ 'documentid': document.docid, 'doctype': document.doctypes.value, 'lang': document.lang, 'state': document.state, 'chmunicipalitynb': document.chmunicipalitynb, 'municipalitynb': document.municipalitynb, 'municipalityname': document.municipalityname, 'cadastrenb': document.cadastrenb, 'title': document.title, 'officialtitle': document.officialtitle, 'abbreviation': document.abbreviation, 'officialnb': document.officialnb, 'legalstate': document.legalstates.value, 'remoteurl': document.remoteurl, 'localurl': document.localurl, 'sanctiondate': document.sanctiondate.isoformat() if document.sanctiondate else None, 'abolishingdate': document.abolishingdate.isoformat() if document.abolishingdate else None, 'entrydate': document.entrydate.isoformat() if document.entrydate else None, 'publicationdate': document.publicationdate.isoformat() if document.publicationdate else None, 'revisiondate': document.revisiondate.isoformat() if document.revisiondate else None, 'operator': document.operator, 'origins': origins }) return doclist
def get_feature_info(id, srid, translations): """The function gets the geometry of a parcel by it's ID and does an overlay with other administrative layers to get the basic parcelInfo and attribute information of the parcel : municipality, local names, and so on hint: for debbuging the query use str(query) in the console/browser window to visualize geom.wkt use session.scalar(geom.wkt) """ try: SRS = srid except: SRS = 2056 parcelInfo = {} parcelInfo['featureid'] = None Y = None X = None if id: parcelInfo['featureid'] = id # elif request.params.get('X') and request.params.get('Y') : # X = int(request.params.get('X')) # Y = int(request.params.get('Y')) else: raise Exception(translations['']) if parcelInfo['featureid'] is not None: queryresult = DBSession.query(Property).filter_by( id=parcelInfo['featureid']).first() # We should check unicity of the property id and raise an exception if there are multiple results elif (X > 0 and Y > 0): if Y > X: pointYX = WKTElement('POINT(' + str(Y) + ' ' + str(X) + ')', SRS) else: pointYX = WKTElement('POINT(' + str(X) + ' ' + str(Y) + ')', SRS) queryresult = DBSession.query(Property).filter( Property.geom.ST_Contains(pointYX)).first() parcelInfo['featureid'] = queryresult.id else: # to define return HTTPBadRequest(translations['HTTPBadRequestMsg']) parcelInfo['geom'] = queryresult.geom parcelInfo['area'] = int( round(DBSession.scalar(queryresult.geom.ST_Area()), 0)) if isinstance(LocalName, (types.ClassType)) is False: queryresult1 = DBSession.query(LocalName).filter( LocalName.geom.ST_Intersects(parcelInfo['geom'])).first() parcelInfo['lieu_dit'] = queryresult1.nomloc # Flurname queryresult2 = DBSession.query(Town).filter( Town.geom.ST_Buffer(1).ST_Contains(parcelInfo['geom'])).first() parcelInfo['nummai'] = queryresult.nummai # Parcel number parcelInfo['type'] = queryresult.typimm # Parcel type if 'no_egrid' in queryresult.__table__.columns.keys(): parcelInfo['no_egrid'] = queryresult.no_egrid else: parcelInfo['no_egrid'] = translations['noEGRIDtext'] if parcelInfo['type'] is None: parcelInfo['type'] = translations['UndefinedPropertyType'] if 'numcad' in queryresult2.__table__.columns.keys(): parcelInfo['nomcad'] = queryresult2.cadnom parcelInfo['numcom'] = queryresult.numcom parcelInfo['nomcom'] = queryresult2.comnom parcelInfo['nufeco'] = queryresult2.nufeco parcelInfo['centerX'] = DBSession.scalar( functions.ST_X(queryresult.geom.ST_Centroid())) parcelInfo['centerY'] = DBSession.scalar( functions.ST_Y(queryresult.geom.ST_Centroid())) parcelInfo['BBOX'] = get_bbox_from_geometry( DBSession.scalar(functions.ST_AsText(queryresult.geom.ST_Envelope()))) # the get_print_format function is not needed any longer as the paper size has been fixed to A4 by the cantons # but we keep the code because the decision will be revoked # parcelInfo['printFormat'] = get_print_format(parcelInfo['BBOX']) return parcelInfo
def get_feature_info(request, translations): """The function gets the geometry of a parcel by it's ID and does an overlay with other administrative layers to get the basic parcelInfo and attribute information of the parcel : municipality, local names, and so on hint: for debbuging the query use str(query) in the console/browser window to visualize geom.wkt use session.scalar(geom.wkt) """ SRS = 21781 parcelInfo = {} parcelInfo['featureid'] = None Y = None X = None if request.params.get('id') : parcelInfo['featureid'] = request.params.get('id') elif request.params.get('X') and request.params.get('Y') : X = int(request.params.get('X')) Y = int(request.params.get('Y')) else : raise Exception(translations['']) if parcelInfo['featureid'] is not None: queryresult = DBSession.query(Property).filter_by(idemai=parcelInfo['featureid']).first() # We should check unicity of the property id and raise an exception if there are multiple results elif (X > 0 and Y > 0): if Y > X : pointYX = WKTSpatialElement('POINT('+str(Y)+' '+str(X)+')',SRS) else: pointYX = WKTSpatialElement('POINT('+str(X)+' '+str(Y)+')',SRS) queryresult = DBSession.query(Property).filter(Property.geom.gcontains(pointYX)).first() parcelInfo['featureid'] = queryresult.idemai else : # to define return HTTPBadRequest(translations['HTTPBadRequestMsg']) parcelInfo['geom'] = queryresult.geom parcelInfo['area'] = int(DBSession.scalar(queryresult.geom.area)) if isinstance(LocalName, (types.ClassType)) is False: queryresult1 = DBSession.query(LocalName).filter(LocalName.geom.intersects(parcelInfo['geom'])).first() parcelInfo['lieu_dit'] = queryresult1.nomloc # Flurname queryresult2 = DBSession.query(Town).filter(Town.geom.buffer(1).gcontains(parcelInfo['geom'])).first() parcelInfo['nummai'] = queryresult.nummai # Parcel number parcelInfo['type'] = queryresult.typimm # Parcel type parcelInfo['source'] = queryresult.source # Parcel type if 'no_egrid' in queryresult.__table__.columns.keys(): parcelInfo['no_egrid'] = queryresult.no_egrid else: parcelInfo['no_egrid'] = translations['noEGRIDtext'] if parcelInfo['type'] == None : parcelInfo['type'] = translations['UndefinedPropertyType'] if 'numcad' in queryresult2.__table__.columns.keys(): parcelInfo['nomcad'] = queryresult2.cadnom parcelInfo['numcom'] = queryresult.numcom parcelInfo['nomcom'] = queryresult2.comnom parcelInfo['nufeco'] = queryresult2.nufeco parcelInfo['centerX'] = DBSession.scalar(queryresult.geom.centroid.x) parcelInfo['centerY'] = DBSession.scalar(queryresult.geom.centroid.y) parcelInfo['BBOX'] = get_bbox_from_geometry(DBSession.scalar(queryresult.geom.envelope.wkt)) # the get_print_format function is not needed any longer as the paper size has been fixed to A4 by the cantons # but we keep the code because the decision will be revoked # parcelInfo['printFormat'] = get_print_format(parcelInfo['BBOX']) return parcelInfo
def create_extract(request): """The function collects alle the necessary data from the subfunctions and classes and then writes the pdf file of the extract.""" # Start a session session = request.session logon = request.registry.settings['logon'] if logon == 'False': logon = False else: logon = True log2 = None if logon is True: log.warning("Entering PDF extract") log2 = log # Create an instance of an extract extract = Extract(request, log2) if logon is True: log.warning("Created Extract class") # Define the extract type if not set in the request parameters # defaults to 'standard': no certification, with pdf attachements # other values : # certified : with certification and with all pdf attachements # reduced : no certification, no pdf attachements # reducedcertified : with certification, without pdf attachments extract.reportInfo = {} defaulttype = 'standard' if request.params.get('type') : extract.reportInfo['type'] = str(request.params.get('type').lower()) else : extract.reportInfo['type'] = defaulttype # Define language to get multilingual labels for the selected language # defaults to 'fr': french - this may be changed in the appconfig if 'lang' not in session: lang = request.registry.settings['default_language'].lower() else : lang = session['lang'].lower() extract.translations = get_translations(lang) extract.lang = lang if logon is True: log.warning("Created language init") # GET the application configuration parameters such as base paths, # working directory and other default parameters extract.load_app_config(request.registry.settings['app_config']) if logon is True: log.warning("load_app_config()") # GET the PDF Configuration parameters such as the page layout, margins # and text styles extract.set_pdf_config(request.registry.settings['pdf_config']) if logon is True: log.warning("set_pdf_config()") # promote often used variables to facilitate coding pdfconfig = extract.pdfconfig if logon is True: log.warning("pdfconfig") translations = extract.translations if logon is True: log.warning("translations") # to get vars defined in the buildout use : request.registry.settings['key'] pdfconfig.sld_url = extract.sld_url if logon is True: log.warning("extract.sld_url") # ************************* # MAIN PROGRAM PART #========================= # 1) If the ID of the parcel is set get the basic attributs of the property # else get the ID (idemai) of the selected parcel first using X/Y coordinates of the center #---------------------------------------------------------------------------------------------------- extract.featureInfo = get_feature_info(request,translations) # '1_14127' # test parcel or '1_11340' featureInfo = extract.featureInfo # complete the dictionnary for the parcel - to be put in the appconfig extract.featureInfo['operator'] = translations['defaultoperatortext'] extract.featureid = featureInfo['featureid'] extract.set_filename() # the get_print_format function which would define the ideal paper format and orientation for the # extract. It is not needed any longer as the paper size has been fixed to A4 portrait by the cantons # BUT there could be a change of opinion after the start phase, so we keep this code part for now extract.printformat = get_print_format(featureInfo['BBOX'],pdfconfig.fitratio) # 2) Get the parameters for the paper format and the map based on the feature's geometry #--------------------------------------------------------------------------------------------------- extract.get_map_format() # again we promote the variables one level printformat = extract.printformat # 3) Get the list of all the restrictions by topicorder set in a column #------------------------------------------- extract.topics = DBSession.query(Topics).order_by(Topics.topicorder).all() # Get the community name and escape special chars to place the logo in the header of the title page municipality = featureInfo['nomcom'].strip() if logon is True: log.warning('Town: %s', municipality) # AS does the german language, the french contains a few accents we have to replace to fetch the banner which has no accents in its pathname... conversion = [ [u'â', 'a'], [u'ä' ,'a'], [u'à', 'a'], [u'ô', 'o'], [u'ö', 'o'], [u'ò', 'o'], [u'û', 'u'], [u'ü', 'u'], [u'ù', 'u'], [u'î', 'i'], [u'ï', 'i'], [u'ì', 'i'], [u'ê', 'e'], [u'ë', 'e'], [u'è', 'e'], [u'é', 'e'], [u' ', ''], [u'-','_'], [u'(NE)', ''], [u' (NE)', ''] ] municipality_escaped = municipality.strip() for char in conversion: municipality_escaped = municipality_escaped.replace(char[0], char[1]) extract.municipalitylogopath = extract.appconfig.municipalitylogodir + municipality_escaped + '.png' extract.municipality = municipality # to clean up once code modified # Get the data for the federal data layers using the map extend if logon is True: log.warning('get XML from CH feature service') for topic in extract.topics: # for the federal data layers we get the restrictions calling the feature service and store the result in the DB if topic.topicid in extract.appconfig.ch_topics: xml_layers = [] for xml_layer in topic.layers: xml_layers.append(xml_layer.layername) get_XML(extract.featureInfo['geom'], topic.topicid, pdfconfig.timestamp, lang, translations) if logon is True: log.warning('get XML from CH feature service DONE') # Create basemap extract.get_basemap() # 4) Create the title page for the pdf extract #-------------------------------------------------- if logon is True: log.warning('get_site_map') extract.get_site_map() if logon is True: log.warning('get_site_map DONE') # 5) Create the pages of the extract for each topic in the list #--------------------------------------------------- # Thematic pages count = 1 for topic in extract.topics: if logon is True: log.warning("Begin of topic no %s, topic_id: %s", count, topic.topicid) add = extract.add_topic(topic) if logon is True: log.warning("End of topic no %s", count) count += 1 # to print the topics in ther right order - this could probably be done in a more elegant way extract.topicorder[topic.topicorder] = topic.topicid # Write pdf file to disc extract.get_title_page() if logon is True: log.warning("get_title_page") # Create the table of content #-------------------------------------------------- extract.get_toc() if logon is True: log.warning("get_toc") # Create the list of appendices #-------------------------------------------------- extract.Appendices() if logon is True: log.warning("Appendices") count = 1 for topic in extract.topicorder.values(): extract.write_thematic_page(topic) if logon is True: log.warning("write_thematic_page, page n° %s", count) count += 1 # Set the page number once all the pages are printed for key in extract.pages.keys(): extract.pages[key] = extract.pages[key].replace('{no_pg}', str(' ')+str(key)) extract.output(pdfconfig.pdfpath+pdfconfig.pdfname+'.pdf','F') if logon is True: log.warning("File created") path = extract.appconfig.legaldocsdir + str('pas_disponible.pdf') exception = extract.appconfig.legaldocsdir + str('exception.pdf') j = 1 appendicesfiles = [] # If report type is not 'reduced': Add a title page in front of every attached pdf if extract.reportInfo['type'] != 'reduced' and extract.reportInfo['type'] != 'reducedcertified': appendicesfiles= [pdfconfig.pdfpath+pdfconfig.pdfname+'.pdf'] for appendix in extract.appendix_entries: appendixfile = AppendixFile() appendixfile.creationdate = str(extract.creationdate) appendixfile.timestamp = str(extract.timestamp) appendixfile.reporttype = str(extract.reportInfo['type']) appendixfile.translations = get_translations(lang) appendixfile.current_page = ' A' + str(j) appendixfile.load_app_config(request.registry.settings['app_config']) appendixfile.set_pdf_config(request.registry.settings['pdf_config']) #extract.pdfconfig appendixfile.municipalitylogopath = appendixfile.appconfig.municipalitylogodir + municipality_escaped + '.png' appendixfile.municipality = municipality # to clean up once code modified appendixfile.add_page() appendixfile.set_margins(*pdfconfig.pdfmargins) appendixfile.set_y(55) appendixfile.set_link(str(j)) appendixfile.set_font(*pdfconfig.textstyles['title3']) appendixfile.cell(15, 10, str('Annexe '+str(j)), 0, 1, 'L') appendixfile.multi_cell(0, 10, str(appendix['title']), 0, 'L') appendixfile.output(pdfconfig.pdfpath+pdfconfig.pdfname+'_a'+str(j)+'.pdf','F') appendicesfiles.append(pdfconfig.pdfpath+pdfconfig.pdfname+'_a'+str(j)+'.pdf') extract.cleanupfiles.append(pdfconfig.pdfpath+pdfconfig.pdfname+'_a'+str(j)+'.pdf') if appendix['path'] is not None: appendicesfiles.append(extract.appconfig.legaldocsdir+appendix['path']) else: appendicesfiles.append(exception) j += 1 merger = PdfFileMerger() for appendixfile in appendicesfiles: try: merger.append(PdfFileReader(file(appendixfile, 'rb'))) except: merger.append(PdfFileReader(file(exception, 'rb'))) merger.write(pdfconfig.pdfpath+pdfconfig.pdfname+'.pdf') if logon is True: log.warning("Merge appendices") extract.clean_up_temp_files() pdffile = {'pdfurl':request.static_url('crdppfportal:static/public/pdf/'+pdfconfig.pdfname+'.pdf')} return pdffile
def get_features_function(parcelGeom, params): # split the layer list string into proper python list csvReader = csv.reader([params['layerList']], skipinitialspace=True) # iterate over layer and make intersects queries itemList = [] for item in csvReader: itemList.append(item) layerList = itemList[0] # test = 'empty' # # retrieve models from table2model # for layer in layerList: # model = table2model_match[layer] # spatial analysis featureList = [] for layer in layerList: targetModel = table2model_match[layer] intersectResult = DBSession.query(targetModel).filter( or_(targetModel.geom.ST_Intersects(parcelGeom), targetModel.geom.ST_Within(parcelGeom))).all() if intersectResult: # create geojson output with custom attributes for feature in intersectResult: geometryType = DBSession.scalar(feature.geom.ST_GeometryType()) geomType = '' intersectionMeasure = -9999 intersectionMeasureTxt = '' if geometryType == 'ST_Polygon' or geometryType == 'ST_MultiPolygon': intersectionMeasure = DBSession.scalar( feature.geom.ST_Intersection(parcelGeom).ST_Area()) if intersectionMeasure >= 1: intersectionMeasureTxt = ' : ' + str( int(round(intersectionMeasure, 0))) + ' [m2]' geomType = 'Polygone' jsonFeature = sloads(dumps(feature)) jsonFeature['properties']['layerName'] = layer jsonFeature['properties'][ 'intersectionMeasure'] = intersectionMeasureTxt jsonFeature['properties']['geomType'] = 'area' featureList.append(jsonFeature) elif geometryType == 'ST_Line' or geometryType == 'ST_MultiLineString' or geometryType == 'ST_LineString': intersectionMeasure = DBSession.scalar( feature.geom.ST_Intersection(parcelGeom).ST_Length()) if intersectionMeasure >= 1: intersectionMeasureTxt = ' : ' + str( int(round(intersectionMeasure, 0))) + ' [m]' geomType = 'Ligne' jsonFeature = sloads(dumps(feature)) jsonFeature['properties']['layerName'] = layer jsonFeature['properties'][ 'intersectionMeasure'] = intersectionMeasureTxt jsonFeature['properties']['geomType'] = 'line' featureList.append(jsonFeature) elif geometryType == 'ST_Point' or geometryType == 'ST_MultiPoint': featureMeasure = -9999 geomType = 'Point' intersectionMeasureTxt = ' ' # ' : point' jsonFeature = sloads(dumps(feature)) jsonFeature['properties']['layerName'] = layer jsonFeature['properties'][ 'intersectionMeasure'] = intersectionMeasureTxt jsonFeature['properties']['geomType'] = 'point' featureList.append(jsonFeature) return featureList
def get_translations_list(request): """Loads the translations for all the multilingual labels """ try: limit = int(request.params['limit']) start = int(request.params['start']) except: limit = 25 start = 0 if request.params['sort'] == 'id': sort = 'Translations.id' else: sort = request.params['sort'] sort += ' '+request.params['dir'] filter_params = {} try: filter_params = request.params['filter'] filter_params = loads(filter_params) except KeyError: filter_params = None if filter_params is None: totalCount = int(DBSession.query(Translations).count()) else: totalCount = '999' translationslist = DBSession.query(Translations).order_by(Translations.id).offset(start).limit(limit).first() if translationslist: translationslist = translationslist # just for flake8 to stop complaining # if filter_params is not None : # for filterparam in filter_params : # if filterparam['type'] == 'numeric': # if filterparam['field'] == 'id_user': # filterparam['field'] = '\"order\".id_user' # if filterparam['comparison'] == 'eq': # filter = str(filterparam['field'])+'='+str(filterparam['value']) # elif filterparam['comparison'] == 'lt': # filter = str(filterparam['field'])+'<'+str(filterparam['value']) # elif filterparam['comparison'] == 'gt' : # filter = str(filterparam['field'])+'>'+str(filterparam['value']) # orderlist = orderlist.filter(filter) # if filterparam['type'] == 'date': # if filterparam['comparison'] == 'eq': # filter = str(filterparam['field'])+'=\''+filterparam['value']+'\'' # elif filterparam['comparison'] == 'lt': # filter = str(filterparam['field'])+'<\''+str(filterparam['value'])+'\'' # elif filterparam['comparison'] == 'gt' : # filter = str(filterparam['field'])+'>\''+str(filterparam['value'])+'\'' # orderlist = orderlist.filter(filter) # elif filterparam['type'] == 'string': # orderlist = orderlist.filter(getattr(Order, filterparam['field']).like("%%%s%%" % filterparam['value'])) # elif filterparam['type'] == 'boolean': # filter = str(filterparam['field'])+'='+str(filterparam['value']) # orderlist = orderlist.filter(filter) # elif filterparam['type'] == 'list': # for option in filterparam['value']: # filter = str(filterparam['field']) + '=\'' + str(option) +'\'' # orderlist = orderlist.filter(filter) # orderlist = orderlist.order_by(sort).offset(start).limit(limit) # else : # orderlist =sessionDB.query(Order).order_by(sort).offset(start).limit(limit).all() results = DBSession.query(Translations).all() list = [] for result in results: list.append({ 'id': result.id, 'varstr': result.varstr, 'de': result.de, 'fr': result.fr, 'it': result.it, 'ro': result.ro, 'en': result.en }) translations = { 'translations': list, 'totalCount': totalCount } return translations
def get_content(id, request): """ TODO.... Explain how the whole thing works... """ # Start a session session = request.session configs = DBSession.query(AppConfig).all() # initalize extract object extract = Extract(request) type = request.matchdict.get("type_") directprint = False if type == 'file': type = 'reduced' directprint = True for config in configs: if config.parameter not in ['crdppflogopath', 'cantonlogopath']: extract.baseconfig[config.parameter] = config.paramvalue extract.srid = db_config['srid'] extract.topiclegenddir = request.static_url( 'crdppfportal:static/public/legend/') # Define language to get multilingual labels for the selected language # defaults to 'fr': french - this may be changed in the appconfig if 'lang' not in session: extract.baseconfig['lang'] = request.registry.settings[ 'default_language'].lower() else: extract.baseconfig['lang'] = session['lang'].lower() extract.baseconfig['translations'] = get_translations( extract.baseconfig['lang']) # for simplification translations = extract.baseconfig['translations'] # 1) If the ID of the parcel is set get the basic attributs of the property # else get the ID (id) of the selected parcel first using X/Y coordinates of the center # --------------------------------------------------------------------------------------------------- featureinfo = get_feature_info( id, extract.srid, translations) # '1_14127' # test parcel or '1_11340' featureinfo = featureinfo extract.filename = extract.id + featureinfo['featureid'] # 3) Get the list of all the restrictions by topicorder set in a column # ------------------------------------------ extract.topics = DBSession.query(Topics).order_by(Topics.topicorder).all() # Configure the WMTS background layer defaultTiles = request.registry.settings['defaultTiles'] wmts = { 'url': request.registry.settings['wmts_getcapabilities_url'], 'defaultTiles': defaultTiles, 'layer': defaultTiles['wmtsname'] } wmts_layer_ = wmts_layer(wmts['url'], wmts['layer']) extract.baseconfig['wmts'] = wmts base_wms_layers = request.registry.settings['app_config'][ 'crdppf_wms_layers'] map_buffer = request.registry.settings['app_config']['map_buffer'] basemaplayers = { "baseURL": request.registry.settings['crdppf_wms'], "opacity": 1, "type": "WMS", "layers": base_wms_layers, "imageFormat": "image/png", "styles": "default", "customParams": { "TRANSPARENT": "true" } } municipality = featureinfo['nomcom'].strip() cadastre = featureinfo['nomcad'].strip() propertynumber = featureinfo['nummai'].strip() propertytype = featureinfo['type'].strip() propertyarea = featureinfo['area'] report_title = translations[str(type + 'extracttitlelabel')] # AS does the german language, the french contains a few accents we have to replace to fetch the banner which has no accents in its pathname... conversion = [[u'â', 'a'], [u'ä', 'a'], [u'à', 'a'], [u'ô', 'o'], [u'ö', 'o'], [u'ò', 'o'], [u'û', 'u'], [u'ü', 'u'], [u'ù', 'u'], [u'î', 'i'], [u'ï', 'i'], [u'ì', 'i'], [u'ê', 'e'], [u'ë', 'e'], [u'è', 'e'], [u'é', 'e'], [u' ', ''], [u'-', '_'], [u'(NE)', ''], [u' (NE)', '']] municipality_escaped = municipality.strip() for char in conversion: municipality_escaped = municipality_escaped.replace(char[0], char[1]) extract.header['municipality_escaped'] = municipality_escaped municipalitylogodir = '/'.join( [request.registry.settings['localhost_url'], 'proj/images/ecussons/']) municipalitylogopath = municipalitylogodir + municipality_escaped + '.png' extract.header['municipalitylogopath'] = municipalitylogopath legenddir = '/'.join( [request.registry.settings['localhost_url'], 'proj/images/icons/']) # Get the raw feature BBOX extract.basemap['bbox'] = get_feature_bbox(id) bbox = extract.basemap['bbox'] if bbox is False: log.warning('Found more then one bbox for id: %s' % id) return False # Get the feature center extract.basemap['feature_center'] = get_feature_center(id) feature_center = extract.basemap['feature_center'] if feature_center is False: log.warning('Found more then one geometry for id: %s' % id) return False # Get the print BOX print_box = get_print_format( bbox, request.registry.settings['pdf_config']['fitratio']) map_bbox = get_mapbox(feature_center, print_box['scale'], map_buffer, print_box['height'], print_box['width'], request.registry.settings['pdf_config']['fitratio']) log.warning('Calling feature: %s' % request.route_url('get_property') + '?id=' + id) wkt_polygon = ''.join([ 'POLYGON((', str(bbox['minX']) + ' ', str(bbox['minY']) + ',', str(bbox['minX']) + ' ', str(bbox['maxY']) + ',', str(bbox['maxX']) + ' ', str(bbox['maxY']) + ',', str(bbox['maxX']) + ' ', str(bbox['minY']) + ',', str(bbox['minX']) + ' ', str(bbox['minY']), '))' ]) basemap = { "projection": "EPSG:" + str(extract.srid), "dpi": 150, "rotation": 0, "center": feature_center, "scale": print_box['scale'] * map_buffer, "longitudeFirst": "true", "layers": [{ "type": "geojson", "geoJson": request.route_url('get_property') + '?id=' + id, "style": { "version": "2", "strokeColor": "gray", "strokeLinecap": "round", "strokeOpacity": 0.6, "[INTERSECTS(geometry, " + wkt_polygon + ")]": { "symbolizers": [{ "strokeColor": "red", "strokeWidth": 2, "type": "line" }] } } }, wmts_layer_] } data = [] topicdata = {} topicdata["doclist"] = [] appconfig = extract.baseconfig concernedtopics = [] notconcernedtopics = [] emptytopics = [] for topic in extract.topics: # for the federal data layers we get the restrictions calling the feature service and store the result in the DB if topic.topicid in extract.baseconfig['ch_topics']: xml_layers = [] for xml_layer in topic.layers: xml_layers.append(xml_layer.layername) # get_XML(feature['geom'], topic.topicid, extractcreationdate, lang, translations) topicdata[str(topic.topicid)] = { "categorie": 0, "docids": set([]), "topicname": topic.topicname, "bboxlegend": [], "layers": {}, "legalbase": [], "legalprovision": [], "reference": [], "authority": { "authorityuuid": topic.authority.authorityid, "authorityname": topic.authority.authorityname, "authorityurl": topic.authority.authoritywww }, "topicorder": topic.topicorder, "authorityfk": topic.authorityfk, "publicationdate": topic.publicationdate } # if geographic layers are defined for the topic, get the list of all layers and then # check for each layer the information regarding the features touching the property if topic.layers: topicdata[str(topic.topicid)]['wmslayerlist'] = [] for layer in topic.layers: topicdata[str(topic.topicid)]["layers"][layer.layerid] = { "layername": layer.layername, "features": None } topicdata[str(topic.topicid)]['wmslayerlist'].append( layer.layername) # intersects a given layer with the feature and adds the results to the topicdata- see method add_layer layerdata = add_layer(layer, propertynumber, featureinfo, translations, appconfig, topicdata) if layerdata is not None: topicdata[str(topic.topicid)]['layers'][ layer.layerid]['features'] = layerdata[str( layer.layerid)]['features'] topicdata[str(topic.topicid)]['categorie'] = 3 for restrictionid in layerdata[str(layer.layerid)]['ids']: docfilters = [restrictionid] for doctype in appconfig['doctypes'].split(','): docfilters.append(doctype) docidlist = get_document_ref(docfilters) docs = set_documents( str(layer.topicfk), doctype, docidlist, featureinfo, False, topicdata[str(topic.topicid)]['docids']) for doc in docs: topicdata[str(topic.topicid)]['docids'].add( doc['documentid']) del doc['documentid'] topicdata[str( topic.topicid)][doctype].append(doc) else: topicdata[str(topic.topicid)]['layers'][layer.layerid] = { 'layername': layer.layername, 'features': None } if topicdata[str(topic.topicid)]['categorie'] != 3: topicdata[str(topic.topicid)]['categorie'] = 1 # get the legend entries in the map bbox not touching the features featurelegend = get_legend_classes( to_shape(featureinfo['geom']), layer.layername, translations, extract.srid) bboxlegend = get_legend_classes(to_shape(WKTElement(map_bbox)), layer.layername, translations, extract.srid) bboxitems = set() for legenditem in bboxlegend: if legenditem not in featurelegend: bboxitems.add(tuple(legenditem.items())) if len(bboxitems) > 0: for el in bboxitems: legendclass = dict((x, y) for x, y in el) legendclass['codegenre'] = legenddir + legendclass[ 'codegenre'] + ".png" topicdata[str( topic.topicid)]["bboxlegend"].append(legendclass) # Get the list of documents related to a topic with layers and results if topicdata[str(layer.topicfk)]["categorie"] == 3: docfilters = [str(topic.topicid)] for doctype in appconfig["doctypes"].split(','): docidlist = get_document_ref(docfilters) docs = set_documents( str(topic.topicid), doctype, docidlist, featureinfo, True, topicdata[str(topic.topicid)]['docids']) for doc in docs: topicdata[str(topic.topicid)]['docids'].add( doc['documentid']) del doc['documentid'] topicdata[str(topic.topicid)][doctype].append(doc) else: if str(topic.topicid) in appconfig['emptytopics']: emptytopics.append(topic.topicname) topicdata[str(topic.topicid)]['layers'] = None topicdata[str(topic.topicid)]['categorie'] = 0 else: topicdata[str(topic.topicid)]['layers'] = None topicdata[str(topic.topicid)]['categorie'] = 1 if topicdata[str(topic.topicid)]['categorie'] == 1: notconcernedtopics.append(topic.topicname) if topicdata[topic.topicid]["categorie"] == 3: appendiceslist = [] for i, legalprovision in enumerate(topicdata[str( topic.topicid)]["legalprovision"]): if legalprovision["officialtitle"] != "": appendiceslist.append( ['A' + str(i + 1), legalprovision["officialtitle"]]) for doctype in appconfig["doctypes"].split(','): if topicdata[str(topic.topicid)][doctype] == []: topicdata[str(topic.topicid)][doctype] = [{ "officialtitle": "", "title": "", "remoteurl": "" }] concernedtopics.append({ "topicname": topic.topicname, "documentlist": { "columns": ["appendixno", "appendixtitle"], "data": appendiceslist } }) if topicdata[topic.topicid]['layers']: topicdata[str(topic.topicid)]["restrictions"] = [] for layer in topicdata[topic.topicid]['layers']: if topicdata[topic.topicid]['layers'][layer]['features']: for feature in topicdata[ topic.topicid]['layers'][layer]['features']: if 'teneur' in feature.keys( ) and feature['teneur'] is not None and feature[ 'statutjuridique'] is not None: if feature['codegenre'] is None: feature['codegenre'] = '9999' if isinstance(feature['codegenre'], int): feature['codegenre'] = str( feature['codegenre']) if feature['geomType'] == 'area': topicdata[str( topic.topicid )]["restrictions"].append({ "codegenre": legenddir + feature['codegenre'] + ".png", "teneur": feature['teneur'], "area": feature['intersectionMeasure'].replace( ' : ', '').replace(' - ', '').replace( '[m2]', 'm<sup>2</sup>'), "area_pct": round((float( feature['intersectionMeasure']. replace(' : ', '').replace( ' - ', '').replace( ' [m2]', '')) * 100) / propertyarea, 1) }) else: topicdata[str( topic.topicid )]["restrictions"].append({ "codegenre": legenddir + feature['codegenre'] + ".png", "teneur": feature['teneur'], "area": feature['intersectionMeasure'].replace( ' - ', '').replace(' : ', '').replace( '[m]', 'm'), "area_pct": -1 }) else: for property, value in feature.iteritems(): if value is not None and property != 'featureClass': if isinstance(value, float) or isinstance( value, int): value = str(value) topiclayers = { "baseURL": request.registry.settings['crdppf_wms'], "opacity": 1, "type": "WMS", "layers": topicdata[str(topic.topicid)]['wmslayerlist'], "imageFormat": "image/png", "styles": "default", "customParams": { "TRANSPARENT": "true" } } # This define the "general" map that we are going to copy x times, # one time as base map and x times as topic map. map = { "projection": "EPSG:" + str(extract.srid), "dpi": 150, "rotation": 0, "center": feature_center, "scale": print_box['scale'] * map_buffer, "longitudeFirst": "true", "layers": [{ "type": "geojson", "geoJson": request.route_url('get_property') + '?id=' + id, "style": { "version": "2", "strokeColor": "gray", "strokeLinecap": "round", "strokeOpacity": 0.6, "[INTERSECTS(geometry, " + wkt_polygon + ")]": { "symbolizers": [{ "strokeColor": "red", "strokeWidth": 2, "type": "line" }] } } }, topiclayers, basemaplayers] } if topicdata[str(topic.topicid)]["bboxlegend"] == []: topicdata[str(topic.topicid)]["bboxlegend"] = [{ "codegenre": "", "teneur": "" }] data.append({ "topicname": topic.topicname, "map": map, "restrictions": topicdata[str(topic.topicid)]["restrictions"], "bboxlegend": topicdata[str(topic.topicid)]["bboxlegend"], "completelegend": extract.topiclegenddir + str(topic.topicid) + '_topiclegend.pdf', "legalbases": topicdata[str(topic.topicid)]["legalbase"], "legalprovisions": topicdata[str(topic.topicid)]["legalprovision"], "references": topicdata[str(topic.topicid)]["reference"], "authority": [topicdata[str(topic.topicid)]["authority"]] }) d = { "attributes": { "reporttype": type, "directprint": directprint, "extractcreationdate": extract.creationdate, "filename": extract.filename, "extractid": extract.id, "map": basemap, "municipality": municipality, "cadastre": cadastre, "cadastrelabel": "Cadastre", "propertytype": propertytype, "propertynumber": propertynumber, "EGRIDnumber": featureinfo['no_egrid'], "municipalitylogopath": municipalitylogopath, "federalmunicipalitynumber": featureinfo['nufeco'], "competentauthority": extract.baseconfig['competentauthority'], "titlepage": [{ "title": report_title, "certificationinstance": "", "certificationtext": "", }], "concernedtopics": concernedtopics, "notconcernedtopics": ";".join(notconcernedtopics), "emptytopics": ";".join(emptytopics), "propertyarea": propertyarea, "datasource": data }, "layout": "report", "outputFormat": "pdf" } # import json # pretty printed json data for the extract # jsonfile = open('C:/Temp/extractdata.json', 'w') # jsondata = json.dumps(d, indent=4) # jsonfile.write(jsondata) # jsonfile.close() return d
def get_content(id, request): """ TODO.... Explain how the whole thing works... """ # Start a session session = request.session configs = DBSession.query(AppConfig).all() # initalize extract object extract = Extract(request) type = request.matchdict.get("type_") directprint = False if type == 'file': type = 'reduced' directprint = True for config in configs: if config.parameter not in ['crdppflogopath', 'cantonlogopath']: extract.baseconfig[config.parameter] = config.paramvalue extract.srid = db_config['srid'] extract.topiclegenddir = request.static_url('crdppfportal:static/public/legend/') # Define language to get multilingual labels for the selected language # defaults to 'fr': french - this may be changed in the appconfig if 'lang' not in session: extract.baseconfig['lang'] = request.registry.settings['default_language'].lower() else: extract.baseconfig['lang'] = session['lang'].lower() extract.baseconfig['translations'] = get_translations(extract.baseconfig['lang']) # for simplification translations = extract.baseconfig['translations'] # 1) If the ID of the parcel is set get the basic attributs of the property # else get the ID (id) of the selected parcel first using X/Y coordinates of the center # --------------------------------------------------------------------------------------------------- featureinfo = get_feature_info(id, extract.srid, translations) # '1_14127' # test parcel or '1_11340' extract.filename = extract.id + featureinfo['featureid'] # 3) Get the list of all the restrictions by topicorder set in a column # ------------------------------------------ extract.topics = DBSession.query(Topics).order_by(Topics.topicorder).all() # Configure the WMTS background layer defaultTiles = request.registry.settings['defaultTiles'] wmts = { 'url': request.registry.settings['wmts_getcapabilities_url'], 'defaultTiles': defaultTiles, 'layer': defaultTiles['wmtsname'] } wmts_layer_ = wmts_layer(wmts['url'], wmts['layer']) extract.baseconfig['wmts'] = wmts base_wms_layers = request.registry.settings['app_config']['crdppf_wms_layers'] map_buffer = request.registry.settings['app_config']['map_buffer'] basemaplayers = { "baseURL": request.registry.settings['crdppf_wms'], "opacity": 1, "type": "WMS", "layers": base_wms_layers, "imageFormat": "image/png", "styles": "default", "customParams": { "TRANSPARENT": "true" } } municipality = featureinfo['nomcom'].strip() cadastre = featureinfo['nomcad'].strip() propertynumber = featureinfo['nummai'].strip() propertytype = featureinfo['type'].strip() propertyarea = featureinfo['area'] report_title = translations[str(type+'extracttitlelabel')] # AS does the german language, the french contains a few accents we have to replace to fetch the banner which has no accents in its pathname... conversion = [ [u'â', 'a'], [u'ä', 'a'], [u'à', 'a'], [u'ô', 'o'], [u'ö', 'o'], [u'ò', 'o'], [u'û', 'u'], [u'ü', 'u'], [u'ù', 'u'], [u'î', 'i'], [u'ï', 'i'], [u'ì', 'i'], [u'ê', 'e'], [u'ë', 'e'], [u'è', 'e'], [u'é', 'e'], [u' ', ''], [u'-', '_'], [u'(NE)', ''], [u' (NE)', ''] ] municipality_escaped = municipality.strip() for char in conversion: municipality_escaped = municipality_escaped.replace(char[0], char[1]) extract.header['municipality_escaped'] = municipality_escaped municipalitylogodir = '/'.join([ request.registry.settings['localhost_url'], 'proj/images/ecussons/']) municipalitylogopath = municipalitylogodir + municipality_escaped + '.png' extract.header['municipalitylogopath'] = municipalitylogopath legenddir = '/'.join([ request.registry.settings['localhost_url'], 'proj/images/icons/']) # Get the raw feature BBOX extract.basemap['bbox'] = get_feature_bbox(id) bbox = extract.basemap['bbox'] if bbox is False: log.warning('Found more then one bbox for id: %s' % id) return False # Get the feature center extract.basemap['feature_center'] = get_feature_center(id) feature_center = extract.basemap['feature_center'] if feature_center is False: log.warning('Found more then one geometry for id: %s' % id) return False # Get the print BOX print_box = get_print_format(bbox, request.registry.settings['pdf_config']['fitratio']) map_bbox = get_mapbox(feature_center, print_box['scale'], map_buffer, print_box['height'], print_box['width'], request.registry.settings['pdf_config']['fitratio']) log.warning('Calling feature: %s' % request.route_url('get_property')+'?id='+id) wkt_polygon = ''.join([ 'POLYGON((', str(bbox['minX'])+' ', str(bbox['minY'])+',', str(bbox['minX'])+' ', str(bbox['maxY'])+',', str(bbox['maxX'])+' ', str(bbox['maxY'])+',', str(bbox['maxX'])+' ', str(bbox['minY'])+',', str(bbox['minX'])+' ', str(bbox['minY']), '))' ]) basemap = { "projection": "EPSG:"+str(extract.srid), "dpi": 150, "rotation": 0, "center": feature_center, "scale": print_box['scale']*map_buffer, "longitudeFirst": "true", "layers": [{ "type": "geojson", "geoJson": request.route_url('get_property')+'?id='+id, "style": { "version": "2", "strokeColor": "gray", "strokeLinecap": "round", "strokeOpacity": 0.6, "[INTERSECTS(geometry, "+wkt_polygon+")]": { "symbolizers": [{ "strokeColor": "red", "strokeWidth": 2, "type": "line" }] } } }, wmts_layer_ ] } data = [] topicdata = {} topicdata["doclist"] = [] appconfig = extract.baseconfig concernedtopics = [] notconcernedtopics = [] emptytopics = [] for topic in extract.topics: # for the federal data layers we get the restrictions calling the feature service and store the result in the DB if topic.topicid in extract.baseconfig['ch_topics']: xml_layers = [] for xml_layer in topic.layers: xml_layers.append(xml_layer.layername) # get_XML(feature['geom'], topic.topicid, extractcreationdate, lang, translations) topicdata[str(topic.topicid)] = { "categorie": 0, "docids": set([]), "topicname": topic.topicname, "bboxlegend": [], "layers": {}, "legalbase": [], "legalprovision": [], "reference": [], "authority": { "authorityuuid": topic.authority.authorityid, "authorityname": topic.authority.authorityname, "authorityurl": topic.authority.authoritywww }, "topicorder": topic.topicorder, "authorityfk": topic.authorityfk, "publicationdate": topic.publicationdate } # if geographic layers are defined for the topic, get the list of all layers and then # check for each layer the information regarding the features touching the property if topic.layers: topicdata[str(topic.topicid)]['wmslayerlist'] = [] for layer in topic.layers: topicdata[str(topic.topicid)]["layers"][layer.layerid] = { "layername": layer.layername, "features": None } topicdata[str(topic.topicid)]['wmslayerlist'].append(layer.layername) # intersects a given layer with the feature and adds the results to the topicdata- see method add_layer layerdata = add_layer(layer, propertynumber, featureinfo, translations, appconfig, topicdata) if layerdata is not None: topicdata[str(topic.topicid)]['layers'][layer.layerid]['features'] = layerdata[str(layer.layerid)]['features'] topicdata[str(topic.topicid)]['categorie'] = 3 for restrictionid in layerdata[str(layer.layerid)]['ids']: docfilters = [restrictionid] for doctype in appconfig['doctypes'].split(','): docfilters.append(doctype) docidlist = get_document_ref(docfilters) docs = set_documents(str(layer.topicfk), doctype, docidlist, featureinfo, False, topicdata[str(topic.topicid)]['docids']) for doc in docs: topicdata[str(topic.topicid)]['docids'].add(doc['documentid']) del doc['documentid'] topicdata[str(topic.topicid)][doctype].append(doc) else: topicdata[str(topic.topicid)]['layers'][layer.layerid] = {'layername': layer.layername, 'features': None} if topicdata[str(topic.topicid)]['categorie'] != 3: topicdata[str(topic.topicid)]['categorie'] = 1 # get the legend entries in the map bbox not touching the features featurelegend = get_legend_classes(to_shape(featureinfo['geom']), layer.layername, translations, extract.srid) bboxlegend = get_legend_classes(to_shape(WKTElement(map_bbox)), layer.layername, translations, extract.srid) bboxitems = set() for legenditem in bboxlegend: if legenditem not in featurelegend: bboxitems.add(tuple(legenditem.items())) if len(bboxitems) > 0: for el in bboxitems: legendclass = dict((x, y) for x, y in el) legendclass['codegenre'] = legenddir+legendclass['codegenre']+".png" topicdata[str(topic.topicid)]["bboxlegend"].append(legendclass) # Get the list of documents related to a topic with layers and results if topicdata[str(layer.topicfk)]["categorie"] == 3: docfilters = [str(topic.topicid)] for doctype in appconfig["doctypes"].split(','): docidlist = get_document_ref(docfilters) docs = set_documents(str(topic.topicid), doctype, docidlist, featureinfo, True, topicdata[str(topic.topicid)]['docids']) for doc in docs: topicdata[str(topic.topicid)]['docids'].add(doc['documentid']) del doc['documentid'] topicdata[str(topic.topicid)][doctype].append(doc) else: if str(topic.topicid) in appconfig['emptytopics']: emptytopics.append(topic.topicname) topicdata[str(topic.topicid)]['layers'] = None topicdata[str(topic.topicid)]['categorie'] = 0 else: topicdata[str(topic.topicid)]['layers'] = None topicdata[str(topic.topicid)]['categorie'] = 1 if topicdata[str(topic.topicid)]['categorie'] == 1: notconcernedtopics.append(topic.topicname) if topicdata[topic.topicid]["categorie"] == 3: appendiceslist = [] for i, legalprovision in enumerate(topicdata[str(topic.topicid)]["legalprovision"]): if legalprovision["officialtitle"] != "": appendiceslist.append(['A'+str(i+1), legalprovision["officialtitle"]]) for doctype in appconfig["doctypes"].split(','): if topicdata[str(topic.topicid)][doctype] == []: topicdata[str(topic.topicid)][doctype] = [{ "officialtitle": "", "title": '', "remoteurl": "" }] concernedtopics.append({ "topicname": topic.topicname, "documentlist": { "columns": ["appendixno", "appendixtitle"], "data": appendiceslist } }) if topicdata[topic.topicid]['layers']: topicdata[str(topic.topicid)]["restrictions"] = [] for layer in topicdata[topic.topicid]['layers']: if topicdata[topic.topicid]['layers'][layer]['features']: for feature in topicdata[topic.topicid]['layers'][layer]['features']: if 'teneur' in feature.keys() and feature['teneur'] is not None and feature['statutjuridique'] is not None: if feature['codegenre'] is None: feature['codegenre'] = '9999' if isinstance(feature['codegenre'], int): feature['codegenre'] = str(feature['codegenre']) if feature['geomType'] == 'area': topicdata[str(topic.topicid)]["restrictions"].append({ "codegenre": legenddir+feature['codegenre']+".png", "teneur": feature['teneur'], "area": feature['intersectionMeasure'].replace(' : ', '').replace(' - ', '').replace('[m2]', 'm<sup>2</sup>'), "area_pct": round((float( feature['intersectionMeasure'].replace(' : ', '').replace(' - ', '').replace(' [m2]', ''))*100)/propertyarea, 1) }) else: topicdata[str(topic.topicid)]["restrictions"].append({ "codegenre": legenddir+feature['codegenre']+".png", "teneur": feature['teneur'], "area": feature['intersectionMeasure'].replace(' - ', '').replace(' : ', '').replace('[m]', 'm'), "area_pct": -1 }) else: for property, value in feature.iteritems(): if value is not None and property != 'featureClass': if isinstance(value, float) or isinstance(value, int): value = str(value) topiclayers = { "baseURL": request.registry.settings['crdppf_wms'], "opacity": 1, "type": "WMS", "layers": topicdata[str(topic.topicid)]['wmslayerlist'], "imageFormat": "image/png", "styles": "default", "customParams": { "TRANSPARENT": "true" } } # This define the "general" map that we are going to copy x times, # one time as base map and x times as topic map. map = { "projection": "EPSG:"+str(extract.srid), "dpi": 150, "rotation": 0, "center": feature_center, "scale": print_box['scale']*map_buffer, "longitudeFirst": "true", "layers": [ { "type": "geojson", "geoJson": request.route_url('get_property')+'?id='+id, "style": { "version": "2", "strokeColor": "gray", "strokeLinecap": "round", "strokeOpacity": 0.6, "[INTERSECTS(geometry, "+wkt_polygon+")]": { "symbolizers": [ { "strokeColor": "red", "strokeWidth": 2, "type": "line" } ] } } }, topiclayers, basemaplayers ] } if topicdata[str(topic.topicid)]["bboxlegend"] == []: topicdata[str(topic.topicid)]["bboxlegend"] = [{ "codegenre": "", "teneur": "" }] data.append({ "topicname": topic.topicname, "map": map, "restrictions": topicdata[str(topic.topicid)]["restrictions"], "bboxlegend": topicdata[str(topic.topicid)]["bboxlegend"], "completelegend": extract.topiclegenddir+str(topic.topicid)+'_topiclegend.pdf', "legalbases": topicdata[str(topic.topicid)]["legalbase"], "legalprovisions": topicdata[str(topic.topicid)]["legalprovision"], "references": topicdata[str(topic.topicid)]["reference"], "authority": [ topicdata[str(topic.topicid)]["authority"] ] }) d = { "attributes": { "reporttype": type, "directprint": directprint, "extractcreationdate": extract.creationdate, "filename": extract.filename, "extractid": extract.id, "map": basemap, "municipality": municipality, "cadastre": cadastre, "cadastrelabel": "Cadastre", "propertytype": propertytype, "propertynumber": propertynumber, "EGRIDnumber": featureinfo['egrid'], "municipalitylogopath": municipalitylogopath, "federalmunicipalitynumber": featureinfo['nufeco'], "competentauthority": extract.baseconfig['competentauthority'], "titlepage": [{ "title": report_title, "certificationinstance": "", "certificationtext": "", }], "concernedtopics": concernedtopics, "notconcernedtopics": ";".join(notconcernedtopics), "emptytopics": ";".join(emptytopics), "propertyarea": propertyarea, "datasource": data }, "layout": "report", "outputFilename": extract.filename, "outputFormat": "pdf" } # import json # pretty printed json data for the extract # jsonfile = open('C:/Temp/'+extract.filename+'.json', 'w') # jsondata = json.dumps(d, indent=4) # jsonfile.write(jsondata) # jsonfile.close() return d
def get_translations_list(request): """Loads the translations for all the multilingual labels """ try: limit = int(request.params['limit']) start = int(request.params['start']) except: limit = 25 start = 0 if request.params['sort'] == 'id': sort = 'Translations.id' else: sort = request.params['sort'] sort += ' ' + request.params['dir'] filter_params = {} try: filter_params = request.params['filter'] filter_params = loads(filter_params) except KeyError: filter_params = None if filter_params is None: totalCount = int(DBSession.query(Translations).count()) else: totalCount = '999' translationslist = DBSession.query(Translations).order_by( Translations.id).offset(start).limit(limit).first() if translationslist: translationslist = translationslist # just for flake8 to stop complaining # if filter_params is not None : # for filterparam in filter_params : # if filterparam['type'] == 'numeric': # if filterparam['field'] == 'id_user': # filterparam['field'] = '\"order\".id_user' # if filterparam['comparison'] == 'eq': # filter = str(filterparam['field'])+'='+str(filterparam['value']) # elif filterparam['comparison'] == 'lt': # filter = str(filterparam['field'])+'<'+str(filterparam['value']) # elif filterparam['comparison'] == 'gt' : # filter = str(filterparam['field'])+'>'+str(filterparam['value']) # orderlist = orderlist.filter(filter) # if filterparam['type'] == 'date': # if filterparam['comparison'] == 'eq': # filter = str(filterparam['field'])+'=\''+filterparam['value']+'\'' # elif filterparam['comparison'] == 'lt': # filter = str(filterparam['field'])+'<\''+str(filterparam['value'])+'\'' # elif filterparam['comparison'] == 'gt' : # filter = str(filterparam['field'])+'>\''+str(filterparam['value'])+'\'' # orderlist = orderlist.filter(filter) # elif filterparam['type'] == 'string': # orderlist = orderlist.filter(getattr(Order, filterparam['field']).like("%%%s%%" % filterparam['value'])) # elif filterparam['type'] == 'boolean': # filter = str(filterparam['field'])+'='+str(filterparam['value']) # orderlist = orderlist.filter(filter) # elif filterparam['type'] == 'list': # for option in filterparam['value']: # filter = str(filterparam['field']) + '=\'' + str(option) +'\'' # orderlist = orderlist.filter(filter) # orderlist = orderlist.order_by(sort).offset(start).limit(limit) # else : # orderlist =sessionDB.query(Order).order_by(sort).offset(start).limit(limit).all() results = DBSession.query(Translations).all() list = [] for result in results: list.append({ 'id': result.id, 'varstr': result.varstr, 'de': result.de, 'fr': result.fr, 'it': result.it, 'ro': result.ro, 'en': result.en }) translations = {'translations': list, 'totalCount': totalCount} return translations