在视图函数中,有没有一种方法可以将字符串与响应对象一起返回?

2024-06-16 10:48:30 发布

您现在位置:Python中文网/ 问答频道 /正文

以下代码段将文件发送到浏览器。你知道吗

# 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+response,比如:

return pdata + send_from_directory( filepath, filename )

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


Tags: 文件fromformsendforreturnrequestdownload
2条回答

如果要同时返回字符串和响应对象,请尝试以下操作:

return (pdata, send_from_directory(filepath, filename))

这将返回一个包含两种数据类型的元组。不能使用+符号,除非有两个兼容的对象,例如"string" + "string"(tuple,) + (tuple,)

为什么不在你回来之前打印呢?你知道吗

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 )

相关问题 更多 >