S
S
sandrosklyarov2017-07-26 10:28:45
Python
sandrosklyarov, 2017-07-26 10:28:45

How to download a generated file in Python?

I programmatically generate xml and save it to my disk

s = etree.ElementTree(root)
s.write( "keywordgroups.xml", encoding='utf8')

You need to do the same, only so that the jump (from the browser) of the xml that will be generated takes place.
I know how to download a file that is on the server, but how to download the generated file?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
sandrosklyarov, 2017-07-26
@sandrosklyarov

s = etree.ElementTree(root)
response = HttpResponse(etree.tostring(s, encoding="utf8", method='xml'), 'application/xml; charset=UTF-8')
response['Content-Disposition'] = 'attachment; filename=keywords.xml'
return response

A
Alexey Cheremisin, 2017-07-26
@leahch

Take any interpretation of a python web server and serve the generated file through it.
For example, via aiohttp (checked, working)

from aiohttp import web
from concurrent.futures import ThreadPoolExecutor
import xml.etree.ElementTree as ElementTree

def get_xml():
    root = ElementTree.Element('root')
    b = ElementTree.SubElement(root, 'b')
    c = ElementTree.SubElement(root, 'c')
    d = ElementTree.SubElement(root, 'd')

    xmlstr = ElementTree.tostring(root, encoding='utf8', method='xml')
    return xmlstr

async def handle(request):
    with ThreadPoolExecutor() as executor:
        xmlstr = await request.app.loop.run_in_executor(executor, get_xml)
    return web.Response(body=xmlstr, content_type="text/xml")

app = web.Application()
app.router.add_get('/', handle)

web.run_app(app, port=8080)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question