如何修改GET请求以触发文件附件响应(合法)



我有一个Django项目,它使用python象棋模块在主视图中显示棋盘。默认为空白板:

views.py

import chess, chess.pgn
def index(request, pgn_slug=None):
board = chess.Board()
game = chess.pgn.Game.from_board(board)
game.headers["DrawOffered"] = "False"

主索引函数捕获AJAX请求并提供响应:

from django.http import JsonResponse
if request.headers.get('x-requested-with') == 'XMLHttpRequest':
...
return JsonResponse(response_obj)

或者它将呈现页面:

from django.http import HttpResponse
else:
html = get_html(game, board)
return HttpResponse(html)

我想要一个elif返回一个基于python象棋游戏编写函数的.txt附件。我如何通过格式良好的请求和响应来实现这一点?Django似乎有一个专门的响应对象来处理这种事情,但我不能完全把二和二放在一起。也许是这样的?:

from django.http import FileResponse
elif request._____ == 'download': # what could mark the request?
file_name = 'foo.txt'
file = open(filename, 'wt')
file.write(str(game))
return FileResponse(file, as_attachment=True,
filename=file_name)

该请求由同一页面上的一个按钮和一个JavaScript函数触发,它会调用窗口的URL,或者从AJAX动态传递给函数的URL:

<script>
function downloadPGN(URL) { 
if (URL === undefined) { 
URL = window.location.href 
}
// ... GET request with modified headers? 
</script>
<button type="button" id="downloadButton" 
onClick="downloadPGN()">↓</button>

我意识到我的问题与其他几个问题相似,但解决方案似乎已有十年历史,对于我印象中相当简单的问题来说,非常复杂。我觉得我好像错过了一些重要的小细节。有人能帮忙吗?

我发现使用html下载属性会产生不同的GET头。不确定可移植性,但这在我的本地系统上通过下载请求将GET与GET分离。

fetch = request.headers.get('Sec-Fetch-Site')
dest = request.headers.get('Sec-Fetch-Dest')
if fetch == 'same-origin' and dest == 'empty':
disp = 'attachment; filename="foo.txt"'
return HttpResponse(get_download(game), headers={
'Content-Disposition': disp })
else: 
html = get_html(request.path, game, board)
return HttpResponse(html)

相关内容

最新更新