title: Is there a way to run initialization code in each uwsgi worker (after forking)
body: <p>Is there a way (in uWSGI or Flask) to register a function to be run in each worker <em>after</em> spawning but as soon as possible?</p>
  
  <p>We have a flask app that benefits from preloading a bunch of stuff. The following only calls <code>preload</code> once for the 8 worker processes. The first request is fast, but the preloaded objects are shared in some fashion that causes errors.</p>
  
  <pre><code>app = Flask(__name__)
  preload()
  </code></pre>
  
  <p>If I use <a href="http://flask.pocoo.org/docs/1.0/api/#flask.Flask.before_first_request" rel="nofollow noreferrer">before_first_request</a>, then the objects are loaded in each worker process and there are no errors, but the first request is very slow.</p>
  
  <pre><code>app = Flask(__name__)
  
  @app.before_first_request
  def bfr():
      preload()
  </code></pre>
  
  <p>I also tried setting up a flask script. Running the command works, but obviously the objects are loaded in the command's process rather than the uwsgi workers.</p>
  
  <pre><code>app = Flask(__name__)
  manager = Manager(app)
  
  @manager.command
  def preload():
      ...
  </code></pre>
  
  <p>I guess if we use <code>before_first_request</code>, we could manually trigger a request after restarting uwsgi. Is that the only solution here?</p>
  
  <p><em>edit: Just found the uswgi <a href="https://uwsgi-docs.readthedocs.io/en/latest/Options.html#hook-post-fork" rel="nofollow noreferrer">hook-post-fork</a> option (and other hook options). I'm going to try that tomorrow. Maybe one of those is what I need.</em></p>