Skip to content

Instantly share code, notes, and snippets.

@zombified
Last active September 11, 2023 15:05
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save zombified/38130dc5fe876944c5eb07f530a03319 to your computer and use it in GitHub Desktop.
Save zombified/38130dc5fe876944c5eb07f530a03319 to your computer and use it in GitHub Desktop.
Python File Saver HTTP Server for TiddlyWiki 5
#!/usr/bin/env python3
"""
TiddlyWiki 5 saver in the form of a Python 3 http.server.
Start script in directory with TiddlyWiki's, go to http://localhost:8181,
select the TiddlyWiki you want, and this server should handle saving via
TiddlyWiki 5 PUT save method.
Based on: https://gist.github.com/jimfoltz/ee791c1bdd30ce137bc23cce826096da
- why not just use the Ruby one? some environments don't have Ruby, some
people feel more comfortable with Python.
"""
from http.server import HTTPServer, SimpleHTTPRequestHandler
import os
import shutil
import time
class ReqHandler(SimpleHTTPRequestHandler):
def do_PUT(self):
backupsdir = os.path.join(self.directory, 'backups')
src = os.path.join(self.directory, self.path[1:])
dest = os.path.join(
backupsdir,
os.path.splitext(os.path.basename(self.path))[0] + "-" + str(time.time()) + ".html")
if not os.path.exists(backupsdir):
os.mkdir(backupsdir)
shutil.copyfile(src, dest)
clen = int(self.headers.get('Content-Length'))
self.send_response(200)
self.send_header("Content-Type", "text/html")
self.end_headers()
with open(src, 'wb') as fout:
fout.write(self.rfile.read(clen))
fout.close()
def do_OPTIONS(self):
self.send_response(200)
self.send_header("Allow", "GET,HEAD,POST,OPTIONS,CONNECT,PUT,DAV,dav")
self.send_header("x-api-access-type", "file")
self.send_header("dav", "tw5/put")
self.end_headers()
try:
server = HTTPServer(("127.0.0.1", 8181), ReqHandler)
print("ready")
server.serve_forever()
except KeyboardInterrupt:
print("bye")
server.socket.close()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment