Home PC Games Linux Windows Database Network Programming Server Mobile  
           
  Home \ Programming \ Django how to generate content in non-HTML formats     - Linux Workstation Security Checklist - from the Linux Foundation Internal (Linux)

- An Analysis of the C Algorithm for Calculating the Number of Days Between Date (Programming)

- CentOS6.0 successful installation and configuration OpenCV (Linux)

- Linux System Getting Started Tutorial: How to Force Change your password at next logon Linux (Linux)

- Linux Telnet access Windows 7 configuration procedure (Linux)

- Eclipse remove all comments and code spaces (Linux)

- Detailed reference Oracle 11g Partition (Database)

- Linux Command - ps: a snapshot of the current process (Linux)

- Linux how to view the graphics models notebook (Linux)

- Linux System Getting Started Learning: Join cron job in Linux (Linux)

- ORA-14400: inserted partition key does not map to any partition (Database)

- To use slay kill user processes (Linux)

- Alternative methods of intrusion bundled executable file new thinking (Linux)

- Oracle LONG RAW BLOB CLOB type of presentation (Database)

- Memcached and Redis (Linux)

- Programmers Do not neglect debugging techniques (Programming)

- Linux hard drive failure Case Studies (Linux)

- Spring AOP custom annotation way to achieve log management (Programming)

- How to choose the correct HTTP status code (Server)

- Ubuntu 14.10 Install Ubuntu Touch Music App 2.0 (Linux)

 
         
  Django how to generate content in non-HTML formats
     
  Add Date : 2018-11-21      
         
         
         
  Sometime you may have such needs, click on a link in a Web page or a picture of a button want to return, a pdf file, a csv file and so on, rather than HTML. In diango very easy to do that. The Django view for receiving http request and returns the web response. Typically, the returned content is HTML, but it is not able to return to that, but may be the above images, pdf files, etc. The key return non-HTML content in the form of this is that HttpResponse class, especially mimetype this parameter, different values ​​may prompt the browser to view the contents of different formats returned by this parameter setting. For example, want to return to the picture content simply read as a picture, and then specify the mimetype in HttpResponse pictures and image content as another parameter response to the browser, the browser can automatically display the correct image content.

from django.http import HttpResponse

def my_image (request):
    image_data = open ( "/ path / to / my / image.png", "rb"). read ()
    return HttpResponse (image_data, mimetype = "image / png")

Another particular note is the HttpResponse objects implement Python's standard "file-like-object" API, which can also be HttpResponse as files.

example:
Generated content CSV format

import csv
from django.http import HttpResponse

# Number of unruly passengers each year 1995 - 2005. In a real application
# This would likely come from a database or some other back-end data store.
UNRULY_PASSENGERS = [146,184,235,200,226,251,299,273,281,304,203]

def unruly_passengers_csv (request):
    # Create the HttpResponse object with the appropriate CSV header.
    response = HttpResponse (mimetype = 'text / csv')
    response [ 'Content-Disposition'] = 'attachment; filename = unruly.csv'

    # Create the CSV writer using the HttpResponse as the "file."
    writer = csv.writer (response)
    writer.writerow ([ 'Year', 'Unruly Airline Passengers'])
    for (year, num) in zip (range (1995, 2006), UNRULY_PASSENGERS):
        writer.writerow ([year, num])

    return response

Points to note:
1.HttpResponse mimetype specified in order to 'text / csv' tells the browser the document is a CSV file.
2.HttpResponse set another parameter Content-Disposition attachment which tell the browser to save the documents returned instead to display its contents, filename indicates the return of the document name, change the name can be specified.
3. Because the writer csv file type method expects an object as a parameter, and HttpResponse instance can use as a file, so it can be directly in the writer method csv module HttpResponse as a parameter.
4.writer.writerow method is responsible for writing a line to the file.

The above method is to return non-HTML content in a format common mode, namely: to create a specific MIME Type of HttpResponse, it is passed as a parameter file is given a specific method of producing the document format, and then returns the response.

Generated content in PDF format

from reportlab.pdfgen import canvas
from django.http import HttpResponse

def hello_pdf (request):
    # Create the HttpResponse object with the appropriate PDF headers.
    response = HttpResponse (mimetype = 'application / pdf')
    response [ 'Content-Disposition'] = 'attachment; filename = hello.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 ()
    return response

The basic process above, points to note:
1. As used herein, the application / pdf MIME type tells the browser returns a PDF file, rather than HTML, or the browser treats it as ordinary HTML content processing.
2.canvas.Canvas method expects a file-like object as a parameter passed to the method of the HttpResponse.
3. Use the Canvas instance method to draw a PDF document, call showPage () method and the save () method (or will cause damage to the pdf document).
4. Finally, the return HttpResponse instance

Generate more complex PDF documents, used here cStringIO library to temporarily store the PDF file

from cStringIO import StringIO
from reportlab.pdfgen import canvas
from django.http import HttpResponse

def hello_pdf (request):
    # Create the HttpResponse object with the appropriate PDF headers.
    response = HttpResponse (mimetype = 'application / pdf')
    response [ 'Content-Disposition'] = 'attachment; filename = hello.pdf'

    temp = StringIO ()

    # Create the PDF object, using the StringIO object as its "file."
    p = canvas.Canvas (temp)

    # 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.
    response.write (temp.getvalue ())
    return response

Other possible formats
In essence, any file can write Python library can be combined to return a specific format and content of Django's HttpResponse, such as ZIP files, dynamic images, graphics, XLS files, etc.

Finally, looking at a return xls files example

from django.http import HttpResponse
import xlwt
def viewXls (request):
    response = HttpResponse (mimetype = 'application / vnd.ms-excel')
    response [ 'Content-Disposition'] = 'attachment; filename = request.xls'
    book = xlwt.Workbook (encoding = 'utf8')
    sheet = book.add_sheet ( 'untitled')
    for row, column, value in ((0,0,1), (0,1,2), (1,0,3), (1,1,4))
    sheet.write (int (row), int (column), value)
    book.save (response)
    return response

Ibid process, not the comments.

In addition, special attention is required, where the request must be submitted to a specific format to return the correct content over form, to be initiated by way of ajax request is returned as a text string content will be processed, which can not be interpreted as a browser specific content.
such as:

$ .ajax ({
                url: "{% url 'mycitsm.views.viewXls'%}",
                data: postData,
                type: "POST",
                success: function (result) {

                },
      });
// Is not possible, and to use the following form to submit it to:
var form = $ ( "# xlsForm");
form.attr ({
 action: "{% url 'mycitsm.views.returnXls'%}",
 method: "POST"
});
form.submit ();

Here it is necessary to record about a problem encountered in the development process, will soon form the content sequence into a string of problems.
Sometimes you need to form all of the content sequence into a string of key-value pairs constructed as a whole URL parameter passing, but also contains a special character values ​​are encoded. For example, we have the following form:

< Form>

  < Div> < input type = "text" name = "a" value = "1" id = "a" /> < / div>

  < Div> < input type = "text" value = "2" id = "b" /> < / div>

  < Div> < input type = "hidden" name = "c" value = "3" id = "c" /> < / div>

  < Div>

    < Textarea name = "d" rows = "8" cols = "40"> 4 < / textarea>

  < / Div>

  < Div> < select name = "e">

    < Option value = "5" selected = "selected"> 5 < / option>

    < Option value = "6"> 6 < / option>

    < Option value = "7"> 7 < / option>

  < / Select> < / div>

  < Div>

    < Input type = "checkbox" name = "f" value = "8" id = "f" />

  < / Div>

  < Div>

    < Input type = "submit" name = "g" value = "Submit" id = "g" />

  < / Div>

< / Form>

$ ( 'Form'). Submit (function () {

  alert ($ (this) .serialize ());

  return false;

});
# Can be output
a = 1 & c = 3 & d = 4 & e = 5

Why there is value and submit value type input checkbox type of input of the second type of input text has not been serialized yet? This is because if the value of the form element contains the sequence string, the element must use the name attribute. While the second type of input text no name attribute. there is a checkbox input type has not been checked so ....... serialize () will only "success control" serialized as a string. If you do not use the button to submit the form, not the value of the submit button for serialization, so submit input type is not serialized.
Of course, in addition to directly form the entire sequence Outsider also on the jQuery object selected individual form elements serialization, such as < input>, < textarea>, and so on.
     
         
         
         
  More:      
 
- OpenStack image production in the CentOS 6.2 (Linux)
- The Linux-based security settings Ipchains Firewall (Linux)
- Ubuntu 14.10 splash screen brightness settings (Linux)
- Four levels to deal with Linux server attacks (Linux)
- libreadline.so.6: can not open shared object file problem solution (Linux)
- Java object serialization (Programming)
- Through the source code to install MySQL 5.6.26 under CentOS6 (Database)
- How to back up Debian system backupninja (Linux)
- ActiveMQ memory settings and flow control (Linux)
- Getting Started with Linux system to learn: how to check the version of SSH on Linux (Linux)
- CentOS7 install NTFS-3G driver (Linux)
- To configure parameter configuration and software installation and uninstallation under Linux (Linux)
- Use C program in JavaScript (Programming)
- Linux System shutdown procedures (Linux)
- Linux System Getting Started Learning: On Linux how to convert text files to PDF (Linux)
- Linux tmux tcpdump summary (Linux)
- Oracle 11g RAC installation considerations Miscellany (Database)
- Piostat - Monitoring and Statistics Linux process (Linux)
- Configuring Sublime Text Python runtime environment 2 (Linux)
- 2016, the new Node project Precautions (Programming)
     
           
     
  CopyRight 2002-2022 newfreesoft.com, All Rights Reserved.