Django使用HttpResponse返回图片并显示的方法

yipeiwu_com6年前Python基础

做了一个关于Django的小案例,想要在网页中显示图片,直接在img标签的src属性写图片的路径是不能显示的,查询资料发现在Django中使用图片这类的资源相当繁琐需要进行一定D的配置,摸索了一会没有整明白,想到了写Java时使用文件流返回图片,于是想到使用该种方式来显示图片。

使用实例如下:

views.py

def my_image(request,news_id): 
  d = path.dirname(__file__) 
  #parent_path = path.dirname(d) 
  print("d="+str(d)) 
  imagepath = path.join(d,"static/show/wordimage/"+str(news_id)+".png") 
  print("imagepath="+str(imagepath)) 
  image_data = open(imagepath,"rb").read() 
  return HttpResponse(image_data,content_type="image/png") #注意旧版的资料使用mimetype,现在已经改为content_type 

urls.py

urlpatterns = [ 
  url(r'^index/$', views.index,name="index"), 
  url(r'^search/$', views.search,name="search"), 
  url(r'^science/(?P<news_id>.+)/$', views.science,name="science"), 
  <strong>url(r'^image/(?P<news_id>.+)/$',views.my_image,name="image"),</strong> 
] 

temlate:

<img src="{% url 'show:image' param.id %}" alt="{{param.id}}"/> 

以上这篇Django使用HttpResponse返回图片并显示的方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

python BeautifulSoup使用方法详解

直接看例子:复制代码 代码如下:#!/usr/bin/python# -*- coding: utf-8 -*-from bs4 import BeautifulSouphtml_doc...

Python标准库os.path包、glob包使用实例

os.path包 os.path包主要用于处理字符串路径,比如'/home/zikong/doc/file.doc',提取出有用的信息。 复制代码 代码如下: import os.pat...

解决Python3中的中文字符编码的问题

解决Python3中的中文字符编码的问题

python3中str默认为Unicode的编码格式 Unicode是一32位编码格式,不适合用来传输和存储,所以必须转换成utf-8,gbk等等 所以在Python3中必须将str类型...

python使用suds调用webservice接口的方法

最近做接口对接,遇到了.net开发的webservice接口,因为python第一次与webservice对接,连问带查,最后使用suds库来实现了 1.安装suds   mac: su...

Python3 requests文件下载 期间显示文件信息和下载进度代码实例

这篇文章主要介绍了Python3 requests文件下载 期间显示文件信息和下载进度代码实例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以...