Home PC Games Linux Windows Database Network Programming Server Mobile  
           
  Home \ Programming \ Django how to generate content in non-HTML formats     - How to enhance the Nagios server security (Linux)

- configuration ssh without password under Linux (Linux)

- Spark source code compiler package (Linux)

- PLSQL often lose resolution process automatically disconnect the connection (Database)

- Oracle 11g forget approach SYS and SYSTEM password (Database)

- MySQL master recovery from failure using binlog (Database)

- Java Concurrency - processes and threads (Programming)

- Flask installation environment (Linux)

- Vi editor Introduction (Linux)

- The best tools and techniques to find data on a Unix system (Linux)

- How to install Visual Studio Code on Ubuntu (Linux)

- RedHat virtual machine to install VMware Tools (Linux)

- File easier to compare tools under Linux (Linux)

- CentOS 6.4 installation and configuration LNMP build PHP server runtime environment (Server)

- CentOS terminal display Chinese (Linux)

- MySQL and MariaDB traditional master-slave cluster configuration (Database)

- Whisker Menu 1.4.3 Install menu Linux (Linux)

- MongoDB query timeout exception SocketTimeoutException (Database)

- Linux Network Security: nmap port scanning software (Linux)

- Python when automated operation and maintenance often used method (Programming)

 
         
  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:      
 
- Why you can have JavaScript string method (Programming)
- The minimum initial use of the Linux operating system RancherOS feelings (Linux)
- Sublime Text 3 using summary (Linux)
- Oracle database online redo logs are several methods of recovery of deleted (Database)
- Linux + Apache + PHP + Oracle based environment to build (Server)
- Use LKM change the default linux security level (Linux)
- MongoDB query timeout exception SocketTimeoutException (Database)
- Construction LVM-based raw device Oracle10g Database on Oracle Linux 5.11 (Database)
- Linux foundation tutorial: how to modify the host name on CentOS or RHEL 7 (Linux)
- To learn from scratch OpenWrt perfect tutorial (Linux)
- Ubuntu deploying Solr (4.4) to Tomcat (7.0.53) (Server)
- Linux uses shared memory communication process synchronization Withdrawal (Programming)
- Learning UNIX good habits (Linux)
- Getting Started with Linux system to learn: how to install the Shrew Soft IPsec VPN on Linux (Linux)
- Processor in protected mode of protection (Linux)
- Mac OS X systems create Ubuntu USB boot disk for the Mac (Linux)
- Oracle create a temporary table space group (Database)
- Hadoop safe hftp (Server)
- Nginx caching using the official guide (Server)
- Linux installed Cisco Packet Tracer (Linux)
     
           
     
  CopyRight 2002-2022 newfreesoft.com, All Rights Reserved.