title: Python twisted web server caching and executing outdated code
body: <p><strong>Background:</strong> Working on a web application that allows users to upload python scripts to a server (Twisted web server). The UI provides full CRUD functionality on these python scripts. After uploading a script the user can then select the script and run it on the server and get results back on the UI. Everything works fine... </p>
  
  <p><strong>Problem:</strong> ...except when the user edits the python code inline (via the UI) or updates a script by uploading a new script overwriting one which already exists. It seems that twisted caches the code (both old and new) and runs new code sometimes and sometimes runs the old code.</p>
  
  <p><strong>Example:</strong> I upload a script <code>hello.py</code> on the server which has a function called <code>run()</code> which does: <code>print 'hello world'</code>. Someone else comes along and uploads another script named <code>hello.py</code> which does: <code>print 'goodbye world'</code>. Then, I go back and execute the <code>run()</code> function on the script 10 times. Half of the times it will say 'hello world' and half of the times it will say 'goodbye world'. </p>
  
  <p><strong>Tried so far:</strong> Several different ways to reload the script into memory before executing it, including: </p>
  
  <ul>
  <li><p>python's builtin reload(): </p>
  
  <pre><code>module = __import__('hello')
  reload(module)
  module.run()
  </code></pre></li>
  <li><p>imp module reload(): </p>
  
  <pre><code>import imp
  module = __import__('hello')
  imp.reload(module)
  module.run()
  </code></pre></li>
  <li><p>twisted.python.rebuild()</p>
  
  <pre><code>from twisted.python.rebuild import rebuild
  module = __import__('hello')
  rebuild(module)
  module.run()
  </code></pre></li>
  <li><p>figured that perhaps if we force python to not write bytecode, that would solve the issue: <code>sys.dont_write_bytecode = True</code></p></li>
  <li><p>restart twisted server</p></li>
  <li><p>a number of other things which I can't remember</p></li>
  </ul>
  
  <p>And the only way to make sure that the most up to date python code executes is to restart twisted server manually. I have been researching for quite some time and have not found any better way of doing it, which works 100% of the time. This leads me to believe that bouncing twisted is the only way.</p>
  
  <p><strong>Question:</strong> Is there a better way to accomplish this (i.e. always execute the most recent code) without having to bounce twisted? Perhaps by preventing twisted from caching scripts into memory, or by clearing twisted cache before importing/reloading modules.</p>
  
  <p>I'm fairly new to twisted web server, so it's possible that I may have overlooked obvious way to resolve this issue, or may have a completely wrong way of approaching this. Some insight into solving this issue would be greatly appreciated. </p>
  
  <p>Thanks</p>
  
  <p>T</p>