django中如何生成非HTML格式的内容。_html/css_WEB-ITnose
某些时候可能有这样的需求,在网页中点击一个链接或者一个按钮希望返回一张图片、一个pdf文档、一个csv文档等而非HTML。在diango中很容易做到这些。django中的view用来接收http request并返回web response。通常情况下,返回的内容为HTML,但其能够返回的不仅仅如此,还可以是上述图片、pdf文件等等。返回非HTML形式的内容的关键在于HttpResponse这个类,尤其是mimetype这个参数,通过将此参数设置为不同的值可以提示浏览器view返回了不同格式的内容。比如,想要返回图片内容,只需读如一张图片,然后在HttpResponse中指明图片的mimetype并将图片内容作为另一参数response给浏览器,浏览器能够自动正确的显示图片内容。
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")
例子:
生成CSV格式的内容
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
1.HttpResponse中mimetype指定为了'text/csv'告知浏览器返回的文档是CSV文件。
2.HttpResponse设置了另外一个参数Content-Disposition其中attachment告知浏览器保存返回的文档而非显示其内容,filename指明了返回文档的名字,改名字可任意指定。
3.因为csv的writer方法期望一个文件类型的对象作为参数,而HttpResponse实例可以当做文件使用,所以可以直接在csv模块的writer方法中将HttpResponse作为参数。
4.writer.writerow方法负责往文件中写入一行内容。
上述方法是返回非HTML格式内容的通用模式,也即:创建一个特定MIME Type的HttpResponse,将其传递给以文件为参数产生特定格式的文档的方法,之后返回该response。
生成PDF格式的内容
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
1.此处使用了 application/pdf MIME type告知浏览器返回的是PDF文件,而非HTML,否则浏览器会将其作为普通HTML内容处理。
2.canvas.Canvas方法期望一个file-like的对象作为参数,将HttpResponse传递给该方法。
3.使用Canvas实例的方法绘制PDF文档,调用showPage()方法和save()方法(否则会产生损坏的pdf文档)。
4.最后返回该HttpResponse实例
生成更为复杂的PDF文档,这里使用了cStringIO库来临时存放PDF文件
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
实质上,任何可以写文件的Python库都可与Django的HttpResponse结合用以返回特定格式的内容,如ZIP文件、动态图片、图表、XLS文件等等。
最后在看一个返回xls文件的例子
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
另外,需要特别注意的是,这里的request必须是通过表单提交才能正确返回特定格式的内容,若要是通过ajax方式发起的request则返回的内容会被当做文本串处理,而不能被浏览器解释为特定内容。
比如:
$.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();
有时需将表单中的所有内容序列化为键值对构成的串做为一个整体进行URL参数传递,而且需要对值中包含的特殊字符进行编码。比如有如下表单:
当然除了直接对整个form序列化外还可对已选取的个别表单元素的jQuery对象序列化,如,

熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

Video Face Swap
使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

記事本++7.3.1
好用且免費的程式碼編輯器

SublimeText3漢化版
中文版,非常好用

禪工作室 13.0.1
強大的PHP整合開發環境

Dreamweaver CS6
視覺化網頁開發工具

SublimeText3 Mac版
神級程式碼編輯軟體(SublimeText3)

HTML適合初學者學習,因為它簡單易學且能快速看到成果。 1)HTML的學習曲線平緩,易於上手。 2)只需掌握基本標籤即可開始創建網頁。 3)靈活性高,可與CSS和JavaScript結合使用。 4)豐富的學習資源和現代工具支持學習過程。

HTML定義網頁結構,CSS負責樣式和佈局,JavaScript賦予動態交互。三者在網頁開發中各司其職,共同構建豐富多彩的網站。

WebDevelovermentReliesonHtml,CSS和JavaScript:1)HTMLStructuresContent,2)CSSStyleSIT和3)JavaScriptAddSstractivity,形成thebasisofmodernWebemodernWebExexperiences。

GiteePages靜態網站部署失敗:404錯誤排查與解決在使用Gitee...

AnexampleOfAstartingTaginHtmlis,beginSaparagraph.startingTagSareEssentialInhtmlastheyInitiateEllements,defiteTheeTheErtypes,andarecrucialforsstructuringwebpages wepages webpages andConstructingthedom。

實現圖片點擊後周圍圖片散開並放大效果許多網頁設計中,需要實現一種交互效果:點擊某張圖片,使其周圍的...

HTML、CSS和JavaScript是Web開發的三大支柱。 1.HTML定義網頁結構,使用標籤如、等。 2.CSS控製網頁樣式,使用選擇器和屬性如color、font-size等。 3.JavaScript實現動態效果和交互,通過事件監聽和DOM操作。

網頁批註功能的Y軸位置自適應算法本文將探討如何實現類似Word文檔的批註功能,特別是如何處理批註之間的間�...
