zoukankan      html  css  js  c++  java
  • django中怎样生成非HTML格式的内容。

    某些时候可能有这种需求。在网页中点击一个链接或者一个button希望返回一张图片、一个pdf文档、一个csv文档等而非HTML。

    在diango中非常easy做到这些。django中的view用来接收http request并返回web response。

    通常情况下,返回的内容为HTML,但其可以返回的不只如此。还可以是上述图片、pdf文件等等。返回非HTML形式的内容的关键在于HttpResponse这个类,尤其是mimetype这个參数,通过将此參数设置为不同的值可以提示浏览器view返回了不同格式的内容。

    比方,想要返回图片内容,只需读如一张图片,然后在HttpResponse中指明图片的mimetype并将图片内容作为还有一參数response给浏览器,浏览器可以自己主动正确的显示图片内容。

    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")
    另外一个须要特别注意的的是HttpResponse对象实现了Python的标准“file-like-object”API。也即能够将HttpResponse当做文件使用。
    样例:
    生成CSV格式的内容

    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
    须要注意的几点:
    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 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
    流程基本同上,须要注意的几点:
    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 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
    其它可能的格式
    实质上。不论什么能够写文件的Python库都可与Django的HttpResponse结合用以返回特定格式的内容,如ZIP文件、动态图片、图表、XLS文件等等。

    最后在看一个返回xls文件的样例

    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
    流程同上,不在凝视。

    另外。须要特别注意的是,这里的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>
    
      <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
    为什么第二个text类型的input的值还有checkbox类型的input的值以及submit类型的input没有被序列化呢?这是由于假设要表单元素的值包括到序列字符串中,元素必须使用 name 属性。

    而第二个text类型的input无name属性。checkbox类型的input有一个并没有被checked所以……。

    serialize()仅仅会将”成功的控件“序列化为字符串。

    假设不使用button来提交表单。则不正确提交button的值序列化,所以submit类型的input没有被序列化。


    当然除了直接对整个form序列化外还可对已选取的个别表单元素的jQuery对象序列化。如<input>,<textarea>等等。





  • 相关阅读:
    Red Hat Enterprise Linux 4 下安装 Oracle 10g [转]
    C# 轻松实现对窗体(Form)换肤[转]
    广州.NET俱乐部第一次活动安排暨动员书
    庆祝广州.net俱乐部成立暨迎接新成员暨讨论社区活动
    有感于广州.NET俱乐部的成立暨全体动员书
    如何在列表模板中增加一个计算列
    BI有感续
    BI有感
    列表属性查看器WebPart
    广州.NET第一次活动内容及演讲安排(本贴持续更新中)
  • 原文地址:https://www.cnblogs.com/zfyouxi/p/5205273.html
Copyright © 2011-2022 走看看