3
gl                 @   s  d Z ddlZddlmZmZ ddlmZ ddlm	Z	 ddl
mZmZmZmZmZmZ ddlmZmZmZmZmZmZmZ ddlmZmZ dd	lmZmZmZm Z  dd
l!m"Z" G dd de#Z$G dd de$Z%G dd de$Z&G dd de$Z'G dd de$Z(G dd dZ)dS )a  
 The LayerMapping class provides a way to map the contents of OGR
 vector files (e.g. SHP files) to Geographic-enabled Django models.

 For more information, please consult the GeoDjango documentation:
   https://docs.djangoproject.com/en/dev/ref/contrib/gis/layermapping/
    N)DecimalInvalidOperation)Path)GeometryField)CoordTransform
DataSourceGDALExceptionOGRGeometryOGRGeomTypeSpatialReference)OFTDateOFTDateTime
OFTIntegerOFTInteger64OFTReal	OFTStringOFTTime)FieldDoesNotExistObjectDoesNotExist)connectionsmodelsroutertransaction)	force_strc               @   s   e Zd ZdS )LayerMapErrorN)__name__
__module____qualname__ r   r   c/var/www/tester-filtro-web/env/lib/python3.6/site-packages/django/contrib/gis/utils/layermapping.pyr      s   r   c               @   s   e Zd ZdS )InvalidStringN)r   r   r   r   r   r   r   r        s   r    c               @   s   e Zd ZdS )InvalidDecimalN)r   r   r   r   r   r   r   r!   $   s   r!   c               @   s   e Zd ZdS )InvalidIntegerN)r   r   r   r   r   r   r   r"   (   s   r"   c               @   s   e Zd ZdS )MissingForeignKeyN)r   r   r   r   r   r   r   r#   ,   s   r#   c            ,   @   s  e Zd ZdZdeddeddededjed	ed
jededjediZeje	ej
eeje	eje	eefeje	eefeje	efejeejeejeejeeje	efejeejeejeejeejeeje	eefej e	eefej!e	eefej"e	eefej#e	eefiZ$d0ddZ%dd Z&dd Z'dd Z(dd Z)dd Z*dd  Z+d!d" Z,d#d$ Z-d%d& Z.d'd( Z/d)d* Z0d+d, Z1d-d-d-d-d-e2j3d-fd.d/Z4dS )1LayerMappingz1A class that maps OGR Layers to GeoDjango Models.   Z
MultiPoint   ZMultiLineString   ZMultiPolygonZPoint25DZMultiPoint25DZLineString25DZMultiLineString25DZ
Polygon25DZMultiPolygon25Dr   Nutf-8commit_on_successTc             C   s,  t |ttfrt||d| _n|| _| j| | _|
dk	r<|
ntj|| _t	| j j
| _|| _|| _| j  t	| j jjr| j | _nd}|r| j|| _| j | _n|| _|rddlm} || || _nd| _|	r| j|	 d}|	| _nd| _|| _|dkrd| _n |dkrtj| _nt d| dS )	a  
        A LayerMapping object is initialized using the given Model (not an instance),
        a DataSource (or string path to an OGR-supported data file), and a mapping
        dictionary.  See the module level docstring for more details and keyword
        argument usage.
        )encodingNFr   )lookupZ
autocommitr)   z!Unrecognized transaction mode: %s)!
isinstancestrr   r   Zdslayerr   Zdb_for_writeusingr   opsspatial_backendmappingmodelcheck_layerfeaturesZsupports_transformgeometry_field	geo_field	check_srs
source_srscoord_transform	transformcodecsr+   r*   check_uniqueuniquetransaction_modetransaction_decoratorr   Zatomicr   )selfr3   datar2   r.   r9   r*   r?   r;   r>   r/   r+   r   r   r   __init__V   s@    



zLayerMapping.__init__c             C   s6   |r.t |ttfrt| S t |tr(|S tndS dS )zCheck the `fid_range` keyword.N)r,   tuplelistslice	TypeError)rA   	fid_ranger   r   r   check_fid_range   s    
zLayerMapping.check_fid_rangec                s.  d| _ i | _| jj | jj} fdd}x| jj D ]\}}y| jjj|}W n  t	k
rr   t
d| Y nX |jj}t|tr8| j rt
d|j}y"|dkrt|d }nt|}W n  tk
r   t
d| Y nX | jj}	|	jj|jp| j|	|s&t
d	||dkrd
nd|	f || _ || _|}
nt|tjrt|tr|jj}xZ|j D ]N\}}||}y|jj| W n* t	k
r   t
d||jjf Y nX qdW |}
ntdnV|j| jkrt
d| ||}|| }t|| j|j st
d||j|f |}
|
| j|< q6W dS )z
        Check the Layer metadata and ensure that it's compatible with the
        mapping information and model. Unlike previous revisions, there is no
        need to increment through each feature in the Layer.
        Fc                s4   y j | }W n  tk
r.   td|  Y nX |S )Nz4Given mapping OGR field "%s" not found in OGR Layer.)index
ValueErrorr   )Zogr_map_fldidx)
ogr_fieldsr   r   check_ogr_fld   s
    z/LayerMapping.check_layer.<locals>.check_ogr_fldz3Given mapping field "%s" not in given Model fields.zDLayerMapping does not support more than one GeometryField per model.r'   Z25Dz'Invalid mapping for GeometryField "%s".zDInvalid mapping geometry; model has %s%s, layer geometry type is %s.z(dim=3) z/ForeignKey mapping field "%s" not in %s fields.z.ForeignKey mapping must be of dictionary type.z0Django field type "%s" has no OGR mapping (yet).z:OGR field "%s" (of type %s) cannot be mapped to Django %s.N)
geom_fieldfieldsr.   Zfield_typesr2   itemsr3   _meta	get_fieldr   r   	__class__r   r,   r   Zdimr
   r   	geom_typename
startswith
make_multi	coord_dimr   Z
ForeignKeydictZremote_fieldrG   FIELD_TYPES
issubclass)rA   Zogr_field_typesrN   
field_nameogr_namemodel_fieldZfld_namerZ   ZgtypeZltypeZ
fields_val	rel_modelZrel_name	ogr_fieldrL   r   )rM   r   r4      sb    		
zLayerMapping.check_layerc             C   s^   t |tr|}n8t || jj r(|j}n t |ttfr@t|}n| jj}|sVtdn|S dS )z>Check the compatibility of the given spatial reference object.z#No source reference system defined.N)	r,   r   r1   spatial_ref_syssrsintr-   r.   r   )rA   r9   srr   r   r   r8     s    


zLayerMapping.check_srsc             C   sR   t |ttfr,x>|D ]}|| jkrtqW n"t |trF|| jkrNtntddS )zDCheck the `unique` keyword parameter -- may be a sequence or string.zBUnique keyword argument must be set with a tuple, list, or string.N)r,   rE   rD   r2   rK   r-   rG   )rA   r>   attrr   r   r   r=     s    




zLayerMapping.check_uniquec             C   s   i }x| j j D ]\}}| j| }t|tr^y| j|j|}W q tk
rZ   tdY qX n.t|t	j
jr|| j|||}n| j|| |}|||< qW |S )z{
        Given an OGR Feature, return a dictionary of keyword arguments for
        constructing the mapped model.
        z)Could not retrieve geometry from feature.)r2   rR   rQ   r,   r   verify_geomgeomr   r   r   baseZ	ModelBase	verify_fkverify_ogr_field)rA   featkwargsr^   r_   r`   valr   r   r   feature_kwargs,  s    

zLayerMapping.feature_kwargsc                s4   t | jtr| j | j iS  fdd| jD S dS )z
        Given the feature keyword arguments (from `feature_kwargs`), construct
        and return the uniqueness keyword arguments -- a subset of the feature
        kwargs.
        c                s   i | ]} | |qS r   r   ).0Zfld)rn   r   r   
<dictcomp>V  s    z.LayerMapping.unique_kwargs.<locals>.<dictcomp>N)r,   r>   r-   )rA   rn   r   )rn   r   unique_kwargsM  s    zLayerMapping.unique_kwargsc       
      C   s  t |tr|t |tjtjfr|| jr<|jdk	r<t|j| j}n|j}|jrx|dk	rxt	||jkrxt
d|j|jt	|f nt |tot |tjr<ytt|j}W n" tk
r   td|j Y nX |j }|d }|d }|j|j }|dk r
t	|d| }	nt	|| }	|	|kr6td|j|j|f |}nZt |ttfrt |tjryt|j}W n$ tk
r   td|j Y nX n|j}|S )	z
        Verify if the OGR Field contents are acceptable to the model field. If
        they are, return the verified value, otherwise raise an exception.
        Nz@%s model field maximum string length is %s, given %s characters.z$Could not construct decimal from: %sr%   r&   r   zeA DecimalField with max_digits %d, decimal_places %d must round to an absolute value less than 10^%d.z$Could not construct integer from: %s)r,   r   r   	CharField	TextFieldr*   valuer   
max_lengthlenr    rW   r   DecimalFieldr   r-   DecimalInvalidOperationr!   as_tupleZ
max_digitsZdecimal_placesIntegerFieldre   rK   r"   )
rA   rb   r`   ro   dZdtupdigitsZd_idxZmax_precZn_precr   r   r   rl   Y  s@    


zLayerMapping.verify_ogr_fieldc             C   sx   i }x0|j  D ]$\}}| j|| |jj|||< qW y|jj| jjf |S  tk
rr   td|j	|f Y nX dS )z
        Given an OGR Feature, the related model and its dictionary mapping,
        retrieve the related model for the ForeignKey mapping.
        z7No ForeignKey %s model found with keyword arguments: %sN)
rR   rl   rS   rT   objectsr/   getr   r#   r   )rA   rm   ra   Zrel_mappingZ	fk_kwargsr^   r_   r   r   r   rk     s    
 zLayerMapping.verify_fkc             C   s`   | j |j kr| j |_ | j|j|rD| j|jj }t|}|j| n|}| jrZ|j| j |jS )z
        Verify the geometry -- construct and return a GeometryCollection
        if necessary (for example if the model field is MultiPolygonField while
        the mapped shapefile only contains Polygons).
        )	rZ   rY   rV   MULTI_TYPESnumr	   addr;   wkt)rA   ri   r`   Z
multi_typegr   r   r   rh     s    zLayerMapping.verify_geomc             C   sd   | j j }y(|jj| jj| jjdj}t| j	|S  t
k
r^ } ztd|W Y dd}~X nX dS )z,Return the coordinate transformation object.)sridz?Could not translate between the data source and model geometry.N)r1   rc   r   r/   r   r7   r   rd   r   r9   	Exceptionr   )rA   ZSpatialRefSysZ
target_srsexcr   r   r   r:     s    
zLayerMapping.coord_transformc             C   s   | j j}|j| jS )zHReturn the GeometryField instance associated with the geographic column.)r3   rS   rT   rP   )rA   optsr   r   r   r6     s    zLayerMapping.geometry_fieldc             C   s   |j | jko|jjd|j kS )z
        Given the OGRGeomType for a geometry and its associated GeometryField,
        determine whether the geometry should be turned into a GeometryCollection.
        zMulti%s)r   r   rU   r   Zdjango)rA   rV   r`   r   r   r   rY     s    zLayerMapping.make_multiFc                s6  j |} r, dks"t t r(dn |ddf fdd	}	jdk	r`j|	}	jj}
|o|t|to|||
k r,|rtdd\}}}t||
|}t|}xt	|D ]r\}}|d |krt
|d}n
t
||}y|	|||\}}|}W q tk
r$   jd	d
d |f   Y qX qW n|	  dS )a  
        Save the contents from the OGR DataSource Layer into the database
        according to the mapping dictionary given at initialization.

        Keyword Parameters:
         verbose:
           If set, information will be printed subsequent to each model save
           executed on the database.

         fid_range:
           May be set with a slice or tuple of (begin, end) feature ID's to map
           from the data source.  In other words, this keyword enables the user
           to selectively import a subset range of features in the geographic
           data source.

         step:
           If set with an integer, transactions will occur at every step
           interval. For example, if step=1000, a commit would occur after
           the 1,000th feature, the 2,000th feature etc.

         progress:
           When this keyword is set, status information will be printed giving
           the number of features processed and successfully saved.  By default,
           progress information will pe printed every 1000 features processed,
           however, this default may be overridden by setting this keyword with an
           integer for the desired interval.

         stream:
           Status information will be written to this file handle.  Defaults to
           using `sys.stdout`, but any object with a `write` method is supported.

         silent:
           By default, non-fatal error notifications are printed to stdout, but
           this keyword may be set to disable these notifications.

         strict:
           Execution of the model mapping will cease upon the first error
           encountered.  The default behavior is to attempt to continue.
        Ti  r   c          #      s  | rj |  }nj }x|D ]}|d7 }yj|}W nD tk
r~ } z&rT nsljd|j|f  W Y d d }~X nrX d}jr<yj|}jjj	j	j
f |}	d}t|	j}
|
d krt|j }n,|
j}t|j }x|D ]}|j| qW t|	j|j W n" tk
r8   jf |}	Y nX njf |}	y<|	jj	d |d7 }rjd|rvdnd|	f  W nj tk
r } zLrƈsjd	|j  jd
|   nsވjd||f  W Y d d }~X nX  r| dkrjd||f  qW ||fS )Nr%   z#Ignoring Feature ID %s because: %s
FT)r/   z%s: %s
ZUpdatedZSavedzOFailed to save the feature (id: %s) into the model with the keyword arguments:
z%s
z"Failed to save %s:
 %s
Continuing
r   z$Processed %d features, saved %d ...
)r.   rp   r   writeZfidr>   rs   r3   r   r/   r   getattrrP   r	   Zogrr   setattrr   r   saver   )Z
feat_rangenum_feat	num_savedZ
layer_iterrm   rn   msgZ	is_updateZu_kwargsmZ
geom_valueri   newr   )progressprogress_intervalrA   silentstreamstrictverboser   r   _save  s^    (

 
$z LayerMapping.save.<locals>._saveNzOThe `step` keyword may not be used in conjunction with the `fid_range` keyword.r%   z%s
Failed to save slice: %s
z=-   )r   r   r   )rI   r,   re   r@   r.   r   r   rangerx   	enumeraterF   r   r   )rA   r   rH   stepr   r   r   r   Zdefault_ranger   Znfeatbegr   r   indicesZn_iiendZ
step_slicer   )r   r   rA   r   r   r   r   r   r     s4    *
 L



zLayerMapping.save)r   Nr(   r)   TNN)5r   r   r   __doc__r
   r   r   r   Z	AutoFieldr   ZBigAutoFieldr   ZSmallAutoFieldZBooleanFieldr   r   r|   Z
FloatFieldZ	DateFieldr   ZDateTimeFieldr   Z
EmailFieldZ	TimeFieldr   ry   rt   Z	SlugFieldru   ZURLFieldZ	UUIDFieldZBigIntegerFieldZSmallIntegerFieldZPositiveBigIntegerFieldZPositiveIntegerFieldZPositiveSmallIntegerFieldr\   rC   rI   r4   r8   r=   rp   rs   rl   rk   rh   r:   r6   rY   sysstdoutr   r   r   r   r   r$   0   s\   

   
Ea!9r$   )*r   r   decimalr   r   rz   pathlibr   Zdjango.contrib.gis.db.modelsr   Zdjango.contrib.gis.gdalr   r   r   r	   r
   r   Zdjango.contrib.gis.gdal.fieldr   r   r   r   r   r   r   Zdjango.core.exceptionsr   r   Z	django.dbr   r   r   r   Zdjango.utils.encodingr   r   r   r    r!   r"   r#   r$   r   r   r   r   <module>   s    $