Skip to content

Commit

Permalink
Merge 9655a2d into f324205
Browse files Browse the repository at this point in the history
  • Loading branch information
Spenser Solys committed May 21, 2017
2 parents f324205 + 9655a2d commit 6c37c6f
Show file tree
Hide file tree
Showing 3 changed files with 69 additions and 0 deletions.
44 changes: 44 additions & 0 deletions cyclone/autoreload.py
@@ -0,0 +1,44 @@
import os, sys, subprocess, threading, time
from apscheduler.schedulers.background import BackgroundScheduler

from twisted.internet import reactor

sched = BackgroundScheduler()
sched.start()

_reload_attempted = False
modify_times = {}

def start():
sched.add_job(_reload_on_update, 'interval', seconds=.5, id="poll")

def _reload_on_update():
for module, m in sys.modules.items():
if m is None:
continue
if getattr(m, '__file__', None) is None:
continue

result = _check_file(m.__file__.lower())
if result != None:
print("Detected a change in " + str(result) + "\nRestarting " + str(sys.argv[0]))
_reload()

def _check_file(path):
try:
modified = os.stat(path).st_mtime
except Exception:
return None

if path not in modify_times:
modify_times[path] = modified
return None

if modify_times[path] != modified:
return path

def _reload():
sched.remove_job("poll")
reactor.callWhenRunning(reactor.stop)
time.sleep(1)
subprocess.Popen([sys.executable] + sys.argv, shell=True)
6 changes: 6 additions & 0 deletions cyclone/web.py
Expand Up @@ -1399,6 +1399,12 @@ def __init__(self, handlers=None, default_host="",
if handlers:
self.add_handlers(".*$", handlers)

if self.settings.get('autoreload'):
print ""
print "Auto Reloader Enabled"
from cyclone import autoreload
autoreload.start()

def add_handlers(self, host_pattern, host_handlers):
"""Appends the given handlers to our handler list.
Expand Down
19 changes: 19 additions & 0 deletions demos/autoreload/autoreload.py
@@ -0,0 +1,19 @@
import cyclone.web
import sys

from twisted.internet import reactor
from twisted.python import log


class MainHandler(cyclone.web.RequestHandler):
def get(self):
self.write("Try modifying the server file!")

if __name__ == "__main__":
application = cyclone.web.Application([
(r"/", MainHandler)
], autoreload=True)

log.startLogging(sys.stdout)
reactor.listenTCP(8888, application)
reactor.run()

0 comments on commit 6c37c6f

Please sign in to comment.