Reputation: 13485
I like the ease of use of Python's SimpleHTTPServer but...
I'd like to launch it from what I'm calling a "fake directory" - that is, a directory that only exists from the server's point of view (does not actually persist on the computer), and ceases to exist when the python process running the server stops. I could also do with a temporary directory, but I want to guarantee that this directory is deleted after (so I don't accumulate files every time I run this and have to think about manually erasing them).
Does anyone know what is the best way to do this?
Upvotes: 2
Views: 1047
Reputation: 193
You could inherit from SimpleHTTPServer and override the method list_directory and translate_path, but if you really don't mind dumping it to disc, you could make yourself a temporary directory context manager that handles directory deletion with shutil:
from tempfile import mkdtemp
import shutil
class TempDir(object):
def __init__(self, *args, **kwargs):
self.args = args
self.kwargs = kwargs
def __enter__(self):
self.tempdir = mkdtemp(*self.args, **self.kwargs)
return self.tempdir
def __exit__(self, *args):
return shutil.rmtree(self.tempdir)
And then serve it with SimpleHTTPServer.
from SimpleHTTPServer import test
import os
with TempDir(prefix="server") as dirname:
os.chdir(dirname)
try:
test()
except KeyboardInterrupt:
pass
Upvotes: 0
Reputation: 11220
Here is a snippet of what you could achieve using mkdtemp
. It does not remove files if the python process gets killed. Maybe a signal handler could do the job.
import SimpleHTTPServer
import tempfile
import os
import shutil
class CustomHTTPServer():
pass
if __name__ == '__main__':
tmpdir = tempfile.mkdtemp()
try:
print "Serving files under %s" % tmpdir
os.chdir(tmpdir)
SimpleHTTPServer.test()
except Exception:
pass
finally:
shutil.rmtree(tmpdir)
which you can just summon using python -m CustomHTTPServer
.
Upvotes: 1
Reputation: 8781
You could use TemporaryDirectory or mkdtemp and make the server serve from that directory. With the first approach, and if used as a context manager, you get automatic cleanup.
Alternatively you could try running everything inside a container system, such as Docker. That way you get isolation of all operations inside the container and it's view of the filesystem, and only allow the modifications you want. It's kind of a heavy weapon to use however.
Upvotes: 1
Reputation: 385970
I would do this by using an in-memory sqlite database. You get all of the benefits of a sql database (relations, searchability, etc), but it only exists for the life of the process.
You can use the package libsqlfs which emulates a complete POSIX filesystem, or you can create your own with a couple of simple tables to store directories and files. It depends on just how thoroughly you want to emulate an actual filesystem.
Upvotes: 1