Created
July 19, 2016 03:38
-
-
Save chew-z/8e4c39fad4b5e895a1670c26e39319fc to your computer and use it in GitHub Desktop.
Small but smart script for serving files in Pythonista iOS
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#coding: utf-8 | |
# python 3 | |
# This script is an editor action, called "Serve Files." It has three improvements over existing implementations: | |
# Serve every file from the directory of your script at its filename | |
# Serve a zip of the entire directory in which your script is contained at /. This is useful for copying a lot of files to a computer at once | |
# Printing your local IP to the console, to make it easier to see where you should go on your computer | |
# It will also clean up the zip it creates after you stop the server. | |
import os | |
import shutil | |
import socket | |
import urllib.parse | |
import dialogs | |
import editor | |
import flask | |
# SETUP | |
# Resolve local IP by connecting to Google's DNS server | |
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) | |
s.connect(("8.8.8.8", 80)) | |
localip = s.getsockname()[0] | |
s.close() | |
# Initialize Flask | |
app = flask.Flask(__name__) | |
# Calculate path details | |
directory, filename = os.path.split(editor.get_path()) | |
dirpath, dirname = os.path.split(directory.rstrip("/")) | |
zippath = os.path.abspath("./{}.zip".format(dirname)) | |
# Make an archive | |
shutil.make_archive(dirname, "zip", dirpath, dirname) | |
# Configure server routings | |
@app.route("/") | |
def index(): | |
"""Serve a zip of it all from the root""" | |
return flask.send_file(zippath) | |
@app.route("/<path:path>") | |
def serve_file(path): | |
"""Serve individual files from elsewhere""" | |
return flask.send_from_directory(directory, path) | |
# Run the app | |
print("Running at {}".format(localip)) | |
app.run(host="0.0.0.0", port=80) | |
# After it finishes | |
os.remove(zippath) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment