【发布时间】:2021-02-09 11:33:38
【问题描述】:
我创建了一个简单的 Django 应用程序并在本地服务器中进行了测试,它运行良好。该应用程序应该像这样工作,每当收到相应视图的发布请求时,响应应该是一个音频文件。在本地服务器中,它按预期工作,响应头显示“'Content-Type':'audio/mpeg'”,但从谷歌云我没有得到音频文件,响应头显示内容类型为“文本/html”。
Django 视图
if request.method == 'POST':
data = request.FILES['file']
tmp = os.path.join(settings.MEDIA_ROOT, "Image", data.name)
path = default_storage.save(tmp, ContentFile(data.read()))
tmp_file = os.path.join(settings.MEDIA_ROOT, path)
# ================ DATA PROCESSING =======================
# Image can be acced in :: tmp_file
# ================ DATA PROCESSING - END =======================
fhandle = open("piZero/from_file.mp3", 'rb') # audio output file name
tmp = os.path.join(settings.MEDIA_ROOT, "Audio", "output.mp3")
path = default_storage.save(tmp, ContentFile(fhandle.read()))
audioFile = os.path.join(settings.MEDIA_ROOT, path)
# Response build
file_handle = open(audioFile, "rb")
file = file_handle.read()
file_handle.close()
response = HttpResponse(file, content_type="audio/mpeg")
response['Content-Disposition'] = 'attachment; filename=filename.mp3'
return response
else:
return HttpResponse("GET")
app.yaml
:因为我没有任何静态文件,所以我没有运行收集静态文件。在实际程序中,此音频文件将由程序创建。所以我不知道是否将其设为静态。
# [START django_app]
runtime: python38
handlers:
# This configures Google App Engine to serve the files in the app's
# static directory.
- url: /static
static_dir: static/
# This handler routes all requests not caught above to the main app.
# It is required when static routes are defined, but can be omitted
# (along with the entire handlers section) when there are no static
# files defined.
- url: /.*
script: auto
# [END django_app]
settings.py :: 最后一部分
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
STATIC_URL = '/static/'
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'Media')
程序连接到 Django :: post 到 Django 服务器
myfiles = {'file': open(file_name, 'rb')}
myobj = {'somekey': 'somevalue'}
x = requests.post(url, data=myobj, files=myfiles)
print(x.headers)
print(x.content)
with open("dummy1.mp3", 'wb') as filehandle:
for chunk in x.iter_content(chunk_size=128):
filehandle.write(chunk)
在谷歌云平台中是否需要进行任何其他配置才能正常提供服务。我没有在我的视图中使用数据库/模型。
- 请解释为什么它在本地服务器中按预期工作,但在谷歌云平台中却没有
- 如何在谷歌云平台上按预期工作。
回复可以查看here。
【问题讨论】:
-
您确定您部署了正确的代码吗?在我看来,这应该可以按预期工作。您能否对照此处发布的代码检查您的 appengine 源代码?此外,在您看来,您创建了一个
response变量,设置了内容处置标头,但随后您返回了一个新的响应对象。我不认为这就是你的本意吗? -
谢谢,我已将回复更正为
# Response build file_handle = open(audioFile, "rb") file = file_handle.read() file_handle.close() response = HttpResponse(file, content_type="audio/mpeg") response['Content-Disposition'] = 'attachment; filename=filename.mp3' return response但结果仍然相同。@NicoGriffioen -
如果响应类型是
text/html,响应正文中的内容是什么?你能显示curl-ing 端点的输出吗?
标签: python django google-cloud-platform python-requests response