在金字塔视图中生成二维码,return 无需写入磁盘

generate a qr code in pyramid view, return it without writing to disk

我有一个金字塔视图,需要生成二维码并 return 将其作为图像提供给用户。我想避免存储图像,我只想生成它,发送它然后忘记它。

我尝试的第一件事是这样的:

oRet = StringIO.StringIO()
oQR  = pyqrcode.create('yo mamma')
oQR.svg(oRet, scale=8)
return Response(body = oRet.read(), content_type="image/svg")

但这会生成一个无法打开的svg文件。

仔细看:

oRet = StringIO.StringIO()
oQR  = pyqrcode.create('yo mamma')

oQR.eps(oRet, scale=8)  
with open('test.eps','w') as f: # cant display image in file
    f.write(oRet.read())

with open('test2.eps','w') as f:  # image file works fine
    oQR.eps(f, scale=8)

oQR.svg(oRet, scale=8) 
with open('test.svg','w') as f:  # cant display image in file
    f.write(oRet.read())

with open('test2.svg','w') as f:  # image file works fine
    oQR.svg(f, scale=8)

oQR.png(oRet) 
with open('test.png','w') as f:  # cant display image
    f.write(oRet.read())

with open('test2.png','w') as f:  #works
    oQR.png(f)   # works

with open('test3.png','w') as f:
    f.write(oQR.png_as_base64_str()) #doesn't work

所以我的问题是:如何 return 将新生成的二维码作为金字塔响应而不存储在磁盘上?我不太介意图片是什么格式

我们有一个赢家:

oRet = StringIO.StringIO()
oQR  = pyqrcode.create('yo mamma')
oQR.png(oRet, scale=8)

oResp =  Response(body = oRet.getvalue(), content_type="image/png",content_disposition='attachment; filename="yummy.png"')
return oResp

诀窍是使用 oRet.getvalue()oRet.read()

这是我的代码:

from pyramid.config import Configurator
from pyramid.response import Response
from pyramid.response import FileResponse
from pyramid.view import view_config
from io import StringIO
from io import BytesIO
import matplotlib.pyplot as plt
import numpy as np
import pyqrcode

 @view_config(route_name='qrcview')
def qrc_test2(request):
    oRet = BytesIO()
    oQR  = pyqrcode.create('bla bla bla bla bla ')
    oQR.png(oRet, scale=10)
    print(type(oRet.getvalue()))
    response =  Response(body = oRet.getvalue(), 
    content_type="image/png")
    return response

 if __name__ == '__main__':
      with Configurator() as config:
          config.add_route('qrcview', '/qrc2')
          config.scan('__main__')
          app = config.make_wsgi_app()
server = make_server('0.0.0.0', 6543, app)
server.serve_forever()