Tuesday, August 14, 2012

Python's CSV library, and the output



def report_all(request, *args, **kwargs):
    """ Queries for all customers for an operator_name.

        Returns the list of all ***cust.active*** customers as CSV data.
    """
    # 1. Prepare the output type
    response = HttpResponse(mimetype='text/csv')
    response['Content-Disposition'] = 'attachment; filename=report_all.csv'
    writer = csv.writer(response)


    # 2. Query the db
    view_kwargs = kwargs
    operator_name = view_kwargs['operator_name']
    operator = Operator.objects.get(name=operator_name)

    customer_set = Customer.objects.filter(operator_id=operator.id)
    dct_customer_info = lambda cust : dict(id=cust.id, extref=cust.extref, license_size=cust.license_size, first_login_date=cust.first_login_date, last_login_date=cust.last_login_date)
    # cust_csv is a list of lists
    first_row = [["%12s" % "[Customer]", "%12s" % "[Lic Size]"]]
    cust_csv = first_row + [["%12s" % cust.extref, "%12s" % cust.license_size] for cust in customer_set]

##    customer_csv = ["%(id)10s, %(extref)10s, %(license_size)10s, " % dct_customer_info(customer) for customer in customer_set]

    # 3. Write and return the CSV
    for row in cust_csv:
        writer.writerow(row)

    writer.writerow(['First row', 'F,oo', 'Ba,r', 'Baz', ",,,"])
    writer.writerow(['Second row', 'A', 'B', 'C', '"Testing"', 'Her","e\'s a quote'])
    return response


######################################


  [Customer],  [Lic Size]
       john1,          12
      sawtec,          11
     willa01,           5
      chewbo,          10
      lamsio,          10
    siang666,          10
       john2,          11
First row,"F,oo","Ba,r",Baz,",,,"
Second row,A,B,C,"""Testing""","Her"",""e's a quote"


#################################################################


https://docs.djangoproject.com/en/dev/howto/outputting-csv/


If:

    writer.writerow(['First row', 'Foo', 'Bar', 'Baz'])
    writer.writerow(['Second row', 'A', 'B', 'C', '"Testing"', "Here's a quote"])


First row,Foo,Bar,Baz
Second row,A,B,C,"""Testing""",Here's a quote

No comments:

Post a Comment