在发送文件给用户之前先打印一些东西

时间:2018-09-23 14:27:18

标签: python bottle

现在,以下代码无法返回具有2个元素的元组,第一个元素是astring,然后是响应方法。

@app.route( '/file', methods=['POST'] )
def file():

    pdata = ''
    pdata = pdata + '''<img src="/static/img/arrow.gif" align="left">'''
    return pdata, send_from_directory( filepath, filename, as_attachment=True )

在我将文件返回给用户之前,让pdata打印一些行的最简单方法是什么?

我不想创建额外的html模板只是为了打印一些行。

3 个答案:

答案 0 :(得分:1)

使用产量。

@app.route( '/file', methods=['POST'] )
def file():

    pdata = ''
    pdata = pdata + '''<img src="/static/img/arrow.gif" align="left">'''
    yield pdata
    for f in send_from_directory( filepath, filename, as_attachment=True ):
        yield f

完整的工作示例:

from bottle import app, get, post, template, route, run

@get('/file')
@post('/file')
def file():

    pdata = '<h3>Hello<h3>'
    pdata = pdata + '''<img src="/static/img/arrow.gif" align="left">'''
    yield pdata
    yield '<br><br>HELLO WORLD'

run(host='localhost', port=8080, debug=True)

答案 1 :(得分:0)

如果您的打印件无法输出某些内容,则可能会与您的框架挂钩。

您可以尝试通过以下方式打印内容:

  • 使用std.err
import sys
print(pdata, file=sys.stderr)
  • 记录模块
import logging
logging.error(pdata)

答案 2 :(得分:0)

filename = request.form.get('filename')         # value comes from posted html form

# Prepare selected file for download...
if request.args:
    filename = request.args.get('filename')         # value comes from template link
    filepath = '/home/nikos/wsgi/static/files/'

    return send_from_directory( filepath, filename, as_attachment=True )

return render_template( 'files.html', authuser=auth.username, filename=filename )

我通过将使用情况发送到'files.html'模板,如上所述进行了尝试,这样他就可以看到html数据输出,然后从那里开始使用:

<meta http-equiv="REFRESH" content="5; URL=http://superhost.gr/files/download?filename={{ filename }}">

因此它可以返回相同的回调函数来获取文件。 这就是我能想到的。

如果有人有更明确的解决方案,请告诉我。