当前位置: 首页 > 知识库问答 >
问题:

在视图函数中,有没有办法将字符串与响应对象一起返回?[重复]

熊锐进
2023-03-14

以下代码段将文件发送到浏览器。

# Prepare selected file for download...
filename = request.form.get('filename')
filepath = '/home/nikos/wsgi/static/files/'

return send_from_directory( filepath, filename )

如果我想在发送文件之前打印一些行,比如:

# Prepare selected file for download...
pdata = pdata + '''Your file will be ready for download'''
padata = pdata + '''it will just atake a moment'''

filename = request.form.get('filename')
filepath = '/home/nikos/wsgi/static/files/'

return send_from_directory( filepath, filename )

如果我尝试添加 pdata 回复,如:

return pdata + send_from_directory( filepath, filename )

我得到一个错误,return应该只返回字符串而不是字符串响应

共有2个答案

越信鸥
2023-03-14

为什么不在你回来之前打印出来呢?

def add(a, b):
    print(f"{a} is being added...")
    print(f"{b} is being added..")
    return a + b

c = add(1, 2)
print(c)
(xenial)vash@localhost:~/python/stack_overflow$ python3.7 strings.py
1 is being added...
2 is being added..
3

建议:

print(f'{pdata} "Your file will be ready for download..."')
print(f'{pdata} "it will just atake a moment..."')

filename = request.form.get('filename')
filepath = '/home/nikos/wsgi/static/files/'

return send_from_directory( filepath, filename )

较旧的Python:

print(f'{} "Your file will be ready for download..."'.format(pdata))
print(f'{} "it will just atake a moment..."'.format(pdata))

filename = request.form.get('filename')
filepath = '/home/nikos/wsgi/static/files/'

return send_from_directory( filepath, filename )
韩琛
2023-03-14

如果您想同时返回字符串和响应对象,请尝试以下方法:

return (pdata, send_from_directory(filepath, filename))

这将返回一个包含两种数据类型的元组。您不能使用符号,除非您有 2 个兼容的对象,例如,“字符串”“字符串”(元组,) (元组,)

 类似资料: