Django "How To" Series 9: Triad: Leverage Legacy databases, output CSV, and output PDFs

Source: Internet
Author: User

How to integrate a legacy database

Django can integrate a previously legacy database while it is suitable for developing new applications, and the following is how to integrate an existing database process.

Given the parameters of your database

You need to tell Django your database connection parameters and the database name, and you can give your database parameters by modifying the default connection in the databases of the Django configuration file.

    • NAME
    • ENGINE
    • USER
    • PASSWORD
    • HOST
    • PORT
automatically generate models

Django comes with a tool inspectdb, which can create a model by deserializing a database that already exists.

Python manage.py Inspectdb

You can use redirect output directly to a file

Python manage.py inspectdb > models.py

Generate additional Core tables

INSPECTDB Specifies to reverse-create an existing database table, we still need to create other core tables, such as admin permissions and so on

Python manage.py syncdb

Testing and Tuning

Test and adjust these models in a variety of ways to meet your requirements. It is recommended to access the data through the Django database API, edit the data through the Django Admin site, and adjust your model files as needed.

using the Django output CSV

Here's how to use the Django view function dynamically to output a CSV file. You can use a Python CSV library or a Django template system

use Python's CSV library

Python comes with a CSV library CSV. The key to using this library in Django is that the CSV module's CSV creation capability acts on the class file object, and the Django HttpResponse object is the class file object. Here is an example:

ImportCSV fromDjango.httpImportHttpResponsedefSome_view (Request):#Create the HttpResponse object with the appropriate CSV header.Response = HttpResponse (mimetype='Text/csv') response['content-disposition'] ='attachment; filename= "Somefilename.csv"'writer=Csv.writer (response) Writer.writerow (['First Row','Foo','Bar','Baz']) Writer.writerow (['Second Row','A','B','C','"Testing"',"Here ' s a quote"])    returnResponse

The code and comments are straightforward, but there are some things worth mentioning:

    • Response to get a special MIME type ' text/csv ', if not, the browser may interpret the output as an HTML, which is an ugly and scary official website article.
    • The response gets an extra Content-disposition header that contains the file name of the CSV file, which is used in the Save As window
    • Hooked into the CSV Generator API is very simple, Csv.writer accepts a class file object, and the HttpResponse object exactly matches
    • Writer.writerow accept an object that can be iterated (list or tuple)
    • CSV module for you to pay attention to the quotation marks, you need to put the original string in the good.
processing Unicode

Python's CSV module does not support Unicode input because Django uses Unicode only internally, which means that strings from some sources (such as httpreuqest) are potentially problematic. Here are some ways to handle this:

    • Manually encode all Unicode objects into a compatible
    • Using the Unicodewriter class
    • Using the Python-unicode module
output CSV using the template system

Idea: Pass a list of objects to your template, and then use the for loop to output commas in the template.

This is an example:

 fromDjango.httpImportHttpResponse fromDjango.templateImportLoader, ContextdefSome_view (Request):#Create the HttpResponse object with the appropriate CSV header.Response = HttpResponse (mimetype='Text/csv') response['content-disposition'] ='attachment; filename= "Somefilename.csv"'    #The data is hard-coded here, but you could load it from a database or    #some other source.Csv_data = (        ('First Row','Foo','Bar','Baz'),        ('Second Row','A','B','C','"Testing"',"Here ' s a quote"),) T= Loader.get_template ('My_template_name.txt') C=Context ({'Data': Csv_data,}) Response.Write (T.render (c))returnResponse
 for  in data%}"{{row.0|addslashes}}" "{{row.1|addslashes}}"  "{{row.2|addslashes}}" "{{row.3|addslashes}}"  "{{row.4|addslashes}}"{% endfor%}
Using Django output PDF

Django uses an excellent open source Python library, Reportlab, to output PDF files

Installing Reportlab

Can be directly to the online search download or directly with the command line installation can be

http://www.reportlab.com/software/opensource/rl-toolkit/download/

After the installation is complete, the direct import is ready to use

Reportlab
Using in a view function

Like the CSV module, Reportlab's API also acts on the class file object, and the Django HttpResponse object is also the class file object, here is a simple example:

 fromReportlab.pdfgenImportCanvas fromDjango.httpImportHttpResponsedefSome_view (Request):#Create the HttpResponse object with the appropriate PDF headers.Response = HttpResponse (mimetype='application/pdf') response['content-disposition'] ='attachment; filename= "Somefilename.pdf"'    #Create The PDF object, using the response object as its "file."p =Canvas. Canvas (response)#Draw things on the PDF. Here's where the PDF generation happens.    #See the Reportlab documentation for the full list of functionality.P.drawstring (100, 100,"Hello World.")    #Close The PDF object cleanly, and we ' re done.p.showpage () p.save ( )returnResponse

The final showpage () and save () are important for PDF files, and other considerations are similar to the output CSV file, which can be referenced by looking at

A complex PDF

If you want to create a complex PDF, consider using Cstringio to temporarily store your PDF file

#Fall back to Stringio in environments where Cstringio are not availableTry:     fromCstringioImportStringioexceptImporterror: fromStringioImportStringio fromReportlab.pdfgenImportCanvas fromDjango.httpImportHttpResponsedefSome_view (Request):#Create the HttpResponse object with the appropriate PDF headers.Response = HttpResponse (mimetype='application/pdf') response['content-disposition'] ='attachment; filename= "Somefilename.pdf"'Buffer=Stringio ()#Create The PDF object, using the Stringio object as its "file."p =Canvas. Canvas (buffer)#Draw things on the PDF. Here's where the PDF generation happens.    #See the Reportlab documentation for the full list of functionality.P.drawstring (100, 100,"Hello World.")    #Close the PDF object cleanly.p.showpage () p.save ( )#Get The value of the Stringio buffer and write it to the response.PDF =Buffer.getvalue () Buffer.close () Response.Write (pdf)returnResponse

Django "How To" Series 9: Triad: Leverage Legacy databases, output CSV, and output PDFs

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.