Home PC Games Linux Windows Database Network Programming Server Mobile  
           
  Home \ Programming \ Django how to generate content in non-HTML formats     - How to use OpenVPN and PrivacyIDEA build two-factor authentication for remote access (Server)

- Android in the coordinate system and a method to obtain the coordinates (Programming)

- Ubuntu 10.10 install Oracle 10g Installation Guide (Database)

- C language sorting instance (select, bubble, insert, binary, fast) (Programming)

- installation of Piwik under Ubuntu (Programming)

- Linux Network Programming --TCP and UDP datagram type Explanation (Programming)

- PL / SQL data types (Database)

- Based on Google Cloud Storage Mirroring open Maven Central Repository (Server)

- Linux / BSD firewall M0n0wall Profile (Linux)

- Oracle GoldenGate encryption (Database)

- Spring Data study notes -Helloworld (Programming)

- Ubuntu 15.04 / 14.04 install Ubuntu After Install 2.6 (Linux)

- Linux Kernel 4.2.2 compiler installation tutorial (Linux)

- Ubuntu Control Panel to resolve network-manager icon display issue (Linux)

- Use mdadm tool to create software RAID 0 (Linux)

- The most simple drive to write and test procedures under linux (Programming)

- Workaround CentOS error message during compilation PHP5 common (Linux)

- CentOS yum install LNMP PHP5.4 version (Server)

- Docker + Nginx + Tomcat7 simple load balancing configuration (Server)

- Linux network security probing tools Hping2 (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:      
 
- Linux System Getting Started Learning: modify environment variables in Linux PATH (Linux)
- How to install Virtualbox 4.3.20 in Ubuntu 14.04 (Linux)
- Xshell configure SSH free password (Server)
- CentOS 7.1 install NTFS-3G (Linux)
- Programmers Do not neglect debugging techniques (Programming)
- Command line tool Tmux (Linux)
- How to protect the Apache website under Linux system (Linux)
- Installing Linux and Windows 10 dual system (Linux)
- CentOS yum install LAMP (Server)
- Ubuntu 14.10 installation SecureCRT 7.3 (Linux)
- Linux, modify the hostname (Linux)
- Linux see whether there is a hacker program (Linux)
- Figlet use (Linux)
- ctop: monitor container performance Linux command line artifact (Linux)
- Dockerfile use to build a mirror-based CentOS 7 (Linux)
- Manage SQL Server services login (start) account and password (Database)
- Source compiler install Nginx (Server)
- The AWK use Cygwin tools mysql binlog log viewer (Database)
- MariaDB 10.1 and MySQL 5.7 in general performance on commodity hardware (Database)
- The Oracle VM VirtualBox use U disk under ubuntu (Linux)
     
           
     
  CopyRight 2002-2020 newfreesoft.com, All Rights Reserved.