Viewing File: /opt/alt/python35/lib64/python3.5/site-packages/playhouse/__pycache__/csv_utils.cpython-35.pyc



R6WX-@skdZddlZddlZddlZddlZddlmZyddlmZWn"ek
r~ddl	mZYnXddl
Tddl
mZddl
mZddl
m
Z
e
reZd	Znd
ZGdddeZd
dZGdddeZGdddeZddd
dddd	ddZeje_d
d
d
dddZdS)a
Peewee helper for loading CSV data into a database.

Load the users CSV file into the database and return a Model for accessing
the data:

    from playhouse.csv_loader import load_csv
    db = SqliteDatabase(':memory:')
    User = load_csv(db, 'users.csv')

Provide explicit field types and/or field names:

    fields = [IntegerField(), IntegerField(), DateTimeField(), DecimalField()]
    field_names = ['from_acct', 'to_acct', 'timestamp', 'amount']
    Payments = load_csv(db, 'payments.csv', fields, field_names)
N)contextmanager)StringIO)*)Database)Func)PY3FTc@s"eZdZeddZdS)
_CSVReadercksd}t|tr't|d}n>t|trL|}|jdn|}|jdd}tj||}|V|r|jdS)NFrrT)
isinstance
basestringopenrseekcsvreaderclose)selffile_or_name
reader_kwargsis_filefhrr
/csv_utils.py
get_reader's
z_CSVReader.get_readerN)__name__
__module____qualname__rrrrrrr&srcsfdd}|S)Ncsfdd|_|S)Ncs
S)Nrr)field_classfield_kwargsrr<lambda>:sz2convert_field.<locals>.decorator.<locals>.<lambda>)field)fn)rrrr	decorator9sz convert_field.<locals>.decoratorr)rrr!r)rrr
convert_field8sr"c@seZdZdZddgZddgZdddd	Zd
dZee	dd
ddZ
eedd
ddZee
ddddZeeddddZeeddddZddZddZddZd S)!RowConvertera
    Simple introspection utility to convert a CSV file into a list of headers
    and column types.

    :param database: a peewee Database object.
    :param bool has_header: whether the first row of CSV is a header row.
    :param int sample_size: number of rows to introspect
    z%Y-%m-%dz%m/%d/%Yz%Y-%m-%d %H:%M:%Sz%Y-%m-%d %H:%M:%S.%fT
cCs||_||_||_dS)N)database
has_headersample_size)rr%r&r'rrr__init__Os		zRowConverter.__init__cCsEx>|D]6}ytjj||Wntk
r8YqXdSqWdS)NT)datetimestrptime
ValueError)rvalueformatsfmtrrrmatches_dateTs

zRowConverter.matches_datedefaultrcCs
|jS)N)isdigit)rr,rrr
is_integer]szRowConverter.is_integercCs1yt|Wnttfk
r(YnXdSdS)NT)floatr+	TypeError)rr,rrris_floatas
zRowConverter.is_floatZnullcCs|j||jS)N)r/datetime_formats)rr,rrris_datetimejszRowConverter.is_datetimecCs|j||jS)N)r/date_formats)rr,rrris_datenszRowConverter.is_datecCsdS)NTr)rr,rrrr0rszRowConverter.defaultc	Ksg}|j}|j||T}|jr7|d7}x7t|D])\}}|j|||jkrDPqDWWdQRX|jr|d|dd}}n#ddtt|dD}||fS)aq
        Extract `self.sample_size` rows from the CSV file and analyze their
        data-types.

        :param str file_or_name: A string filename or a file handle.
        :param reader_kwargs: Arbitrary parameters to pass to the CSV reader.
        :returns: A 2-tuple containing a list of headers and list of rows
                  read from the CSV file.
        NrcSsg|]}d|qS)zfield_%dr).0irrr
<listcomp>s	z-RowConverter.extract_rows.<locals>.<listcomp>)r'rr&	enumerateappendrangelen)	rrrrowsZrows_to_readrr=rowheaderrrrextract_rowsvs
		

	#zRowConverter.extract_rowscCs"|j|j|j|j|jgS)z6Return a list of functions to use when testing values.)r9r7r2r5r0)rrrr
get_checkss
zRowConverter.get_checksc	st|}|j}g}x}t|D]o\}}dd|D}xM|D]Etfdd|D}t|rQ|jjPqQWq+W|S)a
        Analyze the given rows and try to determine the type of value stored.

        :param list rows: A list-of-lists containing one or more rows from a
                          csv file.
        :returns: A list of peewee Field objects for each column in the CSV.
        cSs"g|]}|dkr|qS)r:r)r<valrrrr>s	z(RowConverter.analyze.<locals>.<listcomp>c3s|]}|VqdS)Nr)r<rH)checkrr	<genexpr>sz'RowConverter.analyze.<locals>.<genexpr>)ziprGr?setallr@r)	rrCZ
transposedZchecksZcolumn_typesr=columnZcol_valsresultsr)rIranalyzes
	zRowConverter.analyzeN)rrr__doc__r8r6r(r/r"IntegerFieldr2Z
FloatFieldr5Z
DateTimeFieldr7Z	DateFieldr9Z	BareFieldr0rFrGrPrrrrr#>s					r#c	@sseZdZdZdddddddddZdd	Zd
dZdd
ZddZddZ	dS)Loaderat
    Load the contents of a CSV file into a database and return a model class
    suitable for working with the CSV data.

    :param db_or_model: a peewee Database instance or a Model class.
    :param file_or_name: the filename of the CSV file *or* a file handle.
    :param list fields: A list of peewee Field() instances appropriate to
        the values in the CSV file.
    :param list field_names: A list of names to use for the fields.
    :param bool has_header: Whether the first row of the CSV file is a header.
    :param int sample_size: Number of rows to introspect if fields are not
        defined.
    :param converter: A RowConverter instance to use.
    :param str db_table: Name of table to store data in (if not specified, the
        table name will be derived from the CSV filename).
    :param reader_kwargs: Arbitrary arguments to pass to the CSV reader.
    NTr$Fc
Ksj||_||_||_||_||_||_|
|_t|trZ||_	n't|t
rud|_	n|j|_	t|tr||_
d|_|ptjjtjj|j	d|_n||_|jjj
|_
|jjj|_|jjj|_|jjj|_|jjjrf|	rf|jdd|_|jdd|_dS)Nzdata.csvrr;)rfieldsfield_namesr&r'	converterrr
rfilenamernamerr%modelospathsplitextbasenamedb_table_metaZ
sorted_fieldsZsorted_field_namesZauto_increment)rdb_or_modelrrTrUr&r'rVr^	pk_in_csvrrrrr(s2									+	zLoader.__init__cCstjdd|jS)Nz
[^a-z0-9]+_)resublower)rsrrrclean_field_nameszLoader.clean_field_namecCs(|jp't|jd|jd|jS)Nr&r')rVr#r%r&r')rrrr
get_converters		zLoader.get_convertercsjjjj\}}|rEj|_nfdd|D_jsfdd|D_dS)Ncsg|]}jjqSr)r0r)r<rb)rVrrr>s	z&Loader.analyze_csv.<locals>.<listcomp>csg|]}j|qSr)rg)r<col)rrrr>s	)rhrFrrrPrTrU)rrErCr)rVrranalyze_csvs	zLoader.analyze_csvcCs|jr|jStt||}d|krAt|d<n t|dtrat|d<t|jjt	f|}|j
|j_
|j|j_|S)NidZ_auto_pk)rYdictrKZPrimaryKeyFieldr
rRtyper^titleZModelr%r_)rrUrTZattrsklassrrrget_model_classs	
zLoader.get_model_classcssjsjjrLjrLddttjD_jjj}|}jst	|}fdd|D_njrt	|j
jj}jj|j
dxu|D]m}i}xEtj|D]1\}}|rtr6|jd}|||<qW|r|j|jqWWdQRXWdQRX|S)NcSsg|]}d|qS)zfield_%dr)r<r=rrrr>
s	zLoader.load.<locals>.<listcomp>csg|]}j|qSr)rg)r<ri)rrrr>s	Tzutf-8)rTrjrUr&rArBrrrnextrpr%ZtransactionZcreate_tablerKdecode_valuedecodeinsertZexecute)rZ
reader_objrrDZ
ModelClassrt
field_namer,r)rrloads0	
%			


%zLoader.load)
rrrrQr(rgrhrjrprvrrrrrSs	#
rSr$c	KsLtd|d|d|d|d|d|d|d|d	||		}
|
jS)
Nr`rrTrUr&r'rVr^ra)rSrv)r`rrTrUr&r'rVr^rarloaderrrrload_csv's	rxcCs?t|tr-t||r!dp$d}n|}|rI|jdd|pptj|ddddd	tj}|rg}xrt|jD]a\}	}
|
j	r|j
|
j	qt|
ttfr|j
|
j
q|j
d
|	qW|j|x'|jjD]}|j|qW|r;|j|S)z'
    Create a CSV dump of a query.
    awr	delimiter,Z	quotechar"Zquotingzcol_%s)r
rrr
rwriterZ
QUOTE_MINIMALr?_selectZ_aliasr@ZFieldrrXZwriterowZtuplesiteratorr)ZqueryrZinclude_headerZ
close_filer@Z
csv_writerrrrEidxZnoderDrrrdump_csv9s0	

r)rQrr)rZrc
contextlibrrImportErrorioZpeeweerrrstrrrrobjectrr"r#rSrxrrrrr<module>s6

	qx	
Back to Directory File Manager