Populating Python3 with uWSGI

I spent a lot of time but could not find a solution.
If I use streams in my application deployed with uwsgi, they are not synchronized.

Here is a simple example code (wsgi.py):

from time import sleep import threading i = 0 def daemon(): global i while True: i += 1 print(i) sleep(3) th = threading.Thread(target=daemon, args=()) th.start() def application(environ, start_response): start_response('200 OK', [('Content-Type','text/html')]) return [str(i).encode()] 

And when I run this application, i increases in the log, but I always get 1 when I request make from the browser. (Or get 0 if I move sleep(3) to i in the first increment)
I tried uwsgi.thread decorator but got the same result.

uwsgi config:

 [uwsgi] socket = 127.0.0.1:3034 plugins-dir = /srv/uwsgi plugin = python34 uid = py3utils gid = py3utils chdir = /srv/python/3/py3utils/tht/app/ wsgi-file = wsgi.py enable-threads = true daemonize = %(chdir)/../uwsgi.log master = true die-on-term = true touch-reload = ../uwsgi_restart.txt 

* sorry for my English

+5
source share
2 answers

This is because, after importing the application, the plug-in master process is working:

 spawned uWSGI master process (pid: 7167) spawned uWSGI worker 1 (pid: 7169, cores: 1) spawned uWSGI http 1 (pid: 7170) 

So, your thread, which prints i , starts in the main process, and your requests are processed by the worker. The worker sees i equal to 1 during a fork. If you move sleep before increment i , the process processes fork before the first increment.

You should use something like uwsgidecorators.thread :

 from time import sleep import threading import uwsgidecorators i = 0 @uwsgidecorators.postfork @uwsgidecorators.thread def daemon(): global i while True: i += 1 print(i) sleep(3) def application(environ, start_response): start_response('200 OK', [('Content-Type','text/html')]) return [str(i).encode()] 

Threads, except the main one, are not copied during the fork.

Or use:

 [uwsgi] master = false 
+5
source

Python threads are disabled by default in uwsgi, you can enable it by adding the --enable-threads option:

 uwsgi --http :8090 --wsgi-file uwsgi_test.py --enable-threads 

It works in my test environment.

+1
source

All Articles