Home >Web Front-end >HTML Tutorial >How to generate content in non-HTML format in Django. _html/css_WEB-ITnose

How to generate content in non-HTML format in Django. _html/css_WEB-ITnose

WBOY
WBOYOriginal
2016-06-24 11:48:181032browse

Sometimes there may be a need to click a link or a button on a web page to return a picture, a pdf document, a csv document, etc. instead of HTML. It's easy to do this in diango. Views in Django are used to receive http requests and return web responses. Normally, the content returned is HTML, but it can return more than just that, it can also be the above pictures, PDF files, etc. The key to returning non-HTML content lies in the HttpResponse class, especially the mimetype parameter. By setting this parameter to different values, you can prompt the browser view to return content in different formats. For example, if you want to return the image content, you only need to read an image, then specify the mimetype of the image in the HttpResponse and respond to the image content as another parameter to the browser, and the browser can automatically and correctly display the image content.

from django.http import HttpResponsedef my_image(request):    image_data = open("/path/to/my/image.png", "rb").read()    return HttpResponse(image_data, mimetype="image/png")
Another thing that needs special attention is that the HttpResponse object implements Python's standard "file-like-object" API, that is, you can use HttpResponse as a file.
Example:
Generate content in CSV format

import csvfrom 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
A few points to note:
1. The mimetype specified in HttpResponse is 'text/csv' The document returned by the browser is a CSV file.
2.HttpResponse sets another parameter Content-Disposition, where attachment tells the browser to save the returned document instead of displaying its content. filename specifies the name of the returned document. The name can be specified arbitrarily.
3. Because the writer method of csv expects a file type object as a parameter, and the HttpResponse instance can be used as a file, you can directly use HttpResponse as a parameter in the writer method of the csv module.
4. The writer.writerow method is responsible for writing a line of content to the file.

The above method is a general pattern for returning content in non-HTML format, that is, creating an HttpResponse of a specific MIME Type, passing it to a method that takes a file as a parameter to generate a document in a specific format, and then returning the response.

Generate content in PDF format

from reportlab.pdfgen import canvasfrom django.http import HttpResponsedef 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 process is basically the same as above, with a few points to note:
1. The application/pdf MIME type is used here Tell the browser that the returned PDF file is not HTML, otherwise the browser will treat it as ordinary HTML content.
2. The canvas.Canvas method expects a file-like object as a parameter, passing HttpResponse to the method.
3. Use the method of the Canvas instance to draw the PDF document and call the showPage() method and save() method (otherwise a damaged PDF document will be generated).
4. Finally return the HttpResponse instance

to generate a more complex PDF document. The cStringIO library is used here to temporarily store the PDF file

from cStringIO import StringIOfrom reportlab.pdfgen import canvasfrom django.http import HttpResponsedef 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
Others Possible formats
Essentially, any Python library that can write files can be combined with Django's HttpResponse to return content in a specific format, such as ZIP files, dynamic images, charts, XLS files, etc.

Finally, let’s look at an example of returning an xls file

from django.http import HttpResponseimport xlwtdef 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
The process is the same as above, without comments.

In addition, it is important to note that the request here must be submitted through a form to correctly return content in a specific format. If the request is initiated through Ajax, the returned content will be treated as a text string. Cannot be interpreted by the browser as specific content.
For example:
$.ajax({                url:"{% url 'mycitsm.views.viewXls' %}",                data:postData,                type:"POST",                success:function(result){                },       });//是不可以的,而要使用如下的表单提交才可以:var form = $("#xlsForm");form.attr({	action:"{% url 'mycitsm.views.returnXls' %}",	method:"POST"        });form.submit();
Speaking of which, it is necessary to record a problem encountered during the development process, which is the problem of serializing form content into strings.
Sometimes it is necessary to serialize all the content in the form into a string of key-value pairs and pass the URL parameters as a whole, and the special characters contained in the value need to be encoded. For example, there is 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;});#可以输出a=1&c=3&d=4&e=5
Why are the values ​​of the second text type input, the checkbox type input value and the submit type input not serialized? This is because if a form element's value is to be included in a sequence string, the element must use a name attribute. The second text type input has no name attribute. One of the checkbox type inputs is not checked, so... serialize() will only serialize "successful controls" into strings. If you do not use a button to submit the form, the value of the submit button is not serialized, so the submit type input is not serialized.
Of course, in addition to directly serializing the entire form, you can also serialize jQuery objects of selected individual form elements, such as ,