"""csv export views:organization: Logilab:copyright: 2001-2009 LOGILAB S.A. (Paris, FRANCE), license is LGPL v2.:contact: http://www.logilab.fr/ -- mailto:contact@logilab.fr:license: GNU Lesser General Public License, v2.1 - http://www.gnu.org/licenses"""__docformat__="restructuredtext en"fromcubicweb.schemaimportdisplay_namefromcubicweb.common.uilibimportUnicodeCSVWriterfromcubicweb.viewimportEntityView,AnyRsetViewclassCSVMixIn(object):"""mixin class for CSV views"""templatable=Falsecontent_type="text/comma-separated-values"binary=True# avoid unicode assertioncsv_params={'dialect':'excel','quotechar':'"','delimiter':';','lineterminator':'\n'}defset_request_content_type(self):"""overriden to set a .csv filename"""self.req.set_content_type(self.content_type,filename='cubicwebexport.csv')defcsvwriter(self,**kwargs):params=self.csv_params.copy()params.update(kwargs)returnUnicodeCSVWriter(self.w,self.req.encoding,**params)classCSVRsetView(CSVMixIn,AnyRsetView):"""dumps raw result set in CSV"""id='csvexport'title=_('csv export')defcall(self):writer=self.csvwriter()writer.writerow(self.columns_labels())rset,descr=self.rset,self.rset.descriptioneschema=self.schema.eschemaforrowindex,rowinenumerate(rset):csvrow=[]forcolindex,valinenumerate(row):etype=descr[rowindex][colindex]ifvalisnotNoneandnoteschema(etype).is_final():# csvrow.append(val) # val is eid in that casecontent=self.view('textincontext',rset,row=rowindex,col=colindex)else:content=self.view('final',rset,displaytime=True,format='text/plain',row=rowindex,col=colindex)csvrow.append(content)writer.writerow(csvrow)classCSVEntityView(CSVMixIn,EntityView):"""dumps rset's entities (with full set of attributes) in CSV the generated CSV file will have a table per entity type found in the resultset. ('table' here only means empty lines separation between table contents) """id='ecsvexport'title=_('csv entities export')defcall(self):req=self.reqrows_by_type={}writer=self.csvwriter()rowdef_by_type={}forindexinxrange(len(self.rset)):entity=self.complete_entity(index)ifentity.e_schemanotinrows_by_type:rowdef_by_type[entity.e_schema]=[rsforrs,atinentity.e_schema.attribute_definitions()ifat!='Bytes']rows_by_type[entity.e_schema]=[[display_name(req,rschema.type)forrschemainrowdef_by_type[entity.e_schema]]]rows=rows_by_type[entity.e_schema]rows.append([entity.printable_value(rs.type,format='text/plain')forrsinrowdef_by_type[entity.e_schema]])forrowsinrows_by_type.itervalues():writer.writerows(rows)# use two empty lines as separatorwriter.writerows([[],[]])