[Answer]-Python: Create and return an SQLite DB as a web request result

1👍

I’m not sure you can get at the contents of a :memory: database to treat it as a file; a quick look through the SQLite documentation suggests that its API doesn’t expose the :memory: database to you as a binary string, or a memory-mapped file, or any other way you could access it as a series of bytes. The only way to access a :memory: database is through the SQLite API.

What I would do in your shoes is to set up your server to have a directory mounted with ramfs, then create an SQLite3 database as a “file” in that directory. When you’re done populating the database, return that “file”, then delete it. This will be the simplest solution by far: you’ll avoid having to write anything to disk and you’ll gain the same speed benefits as using a :memory: database, but your code will be much easier to write.

👤rmunn

0👍

With web content you can easily serve files as raw binary with a content type specified in the response.

Django makes this fairly easy – here’s a snippet I use on one of my sites for generating a barcode for a user.

def barcode(request):
    from core import ugbarcode
    bar = ugbarcode.UGBar("0001")
    binStream = bar.asString('gif')
    return HttpResponse(binStream, 'image/gif')

See also this post for more details in specifying it is an attachment to trigger download: Generating file to download with Django

Leave a comment