From 057cfe761f24ae61520197de5cc4c80a442d4376 Mon Sep 17 00:00:00 2001 From: Curtis Date: Sat, 11 Apr 2015 22:50:11 +1000 Subject: [PATCH] Tidy with flake8 --- contrib/graphite_uwsgi.py | 1 + contrib/pypy/uwsgi_pypy_greenlets.py | 9 +- contrib/pyuwsgi.py | 2 +- contrib/runuwsgi.py | 5 +- contrib/spoolqueue/producer.py | 5 +- contrib/spoolqueue/tasks.py | 4 +- contrib/spoolqueue/tasksconsumer.py | 29 +- contrib/twuwsgi.py | 53 ++- contrib/uwsgi-cache-monitor.py | 70 ++-- examples/flaskpost.py | 2 + examples/heavytest.py | 8 +- examples/mjpeg_stream.py | 34 +- examples/multiapp.py | 22 +- examples/simple_app.py | 8 +- examples/simple_app_wsgi2.py | 6 +- examples/simple_logger.py | 3 +- examples/staticfilesnmp.py | 5 +- examples/taskqueue.py | 9 +- examples/uwsgirouter.py | 122 +++--- examples/uwsgirouter2.py | 6 +- examples/uwsgirouter3.py | 27 +- examples/uwsgirouter4.py | 17 +- examples/uwsgirouter5.py | 7 +- examples/uwsgistatus.py | 10 +- examples/welcome.py | 24 +- examples/welcome3.py | 10 +- plugins/airbrake/uwsgiplugin.py | 8 +- plugins/alarm_curl/uwsgiplugin.py | 2 +- plugins/alarm_speech/uwsgiplugin.py | 2 +- plugins/alarm_xmpp/uwsgiplugin.py | 2 +- plugins/asyncio/uwsgiplugin.py | 9 +- plugins/cache/uwsgiplugin.py | 2 +- plugins/carbon/uwsgiplugin.py | 3 +- plugins/cgi/uwsgiplugin.py | 3 +- plugins/cheaper_backlog2/uwsgiplugin.py | 2 +- plugins/cheaper_busyness/uwsgiplugin.py | 2 +- plugins/clock_monotonic/uwsgiplugin.py | 2 +- plugins/clock_realtime/uwsgiplugin.py | 2 +- plugins/corerouter/uwsgiplugin.py | 2 +- plugins/coroae/uwsgiplugin.py | 3 +- plugins/cplusplus/uwsgiplugin.py | 2 +- plugins/curl_cron/uwsgiplugin.py | 2 +- plugins/dumbloop/uwsgiplugin.py | 4 +- plugins/dummy/uwsgiplugin.py | 3 +- plugins/echo/uwsgiplugin.py | 2 +- plugins/emperor_amqp/uwsgiplugin.py | 4 +- plugins/emperor_mongodb/uwsgiplugin.py | 9 +- plugins/emperor_pg/uwsgiplugin.py | 8 +- plugins/emperor_zeromq/uwsgiplugin.py | 2 +- plugins/example/uwsgiplugin.py | 2 +- plugins/exception_log/uwsgiplugin.py | 2 +- plugins/fastrouter/uwsgiplugin.py | 2 +- plugins/fiber/uwsgiplugin.py | 2 +- plugins/forkptyrouter/uwsgiplugin.py | 3 +- plugins/gccgo/uwsgiplugin.py | 4 +- plugins/geoip/uwsgiplugin.py | 3 +- plugins/gevent/uwsgiplugin.py | 8 +- plugins/glusterfs/uwsgiplugin.py | 5 +- plugins/graylog2/uwsgiplugin.py | 2 +- plugins/greenlet/uwsgiplugin.py | 8 +- plugins/gridfs/uwsgiplugin.py | 9 +- plugins/http/uwsgiplugin.py | 2 +- plugins/jvm/uwsgiplugin.py | 22 +- plugins/jwsgi/uwsgiplugin.py | 3 +- plugins/ldap/uwsgiplugin.py | 2 +- plugins/legion_cache_fetch/uwsgiplugin.py | 3 +- plugins/libffi/uwsgiplugin.py | 11 +- plugins/libtcc/uwsgiplugin.py | 11 +- plugins/logcrypto/uwsgiplugin.py | 2 +- plugins/logfile/uwsgiplugin.py | 2 +- plugins/logpipe/uwsgiplugin.py | 2 +- plugins/logsocket/uwsgiplugin.py | 2 +- plugins/logzmq/uwsgiplugin.py | 2 +- plugins/lua/uwsgiplugin.py | 31 +- plugins/matheval/uwsgiplugin.py | 2 +- plugins/mongodb/uwsgiplugin.py | 13 +- plugins/mongodblog/uwsgiplugin.py | 2 +- plugins/mongrel2/uwsgiplugin.py | 2 +- plugins/mono/uwsgiplugin.py | 6 +- plugins/msgpack/uwsgiplugin.py | 8 +- plugins/nagios/uwsgiplugin.py | 2 +- plugins/notfound/uwsgiplugin.py | 2 +- plugins/objc_gc/uwsgiplugin.py | 10 +- plugins/pam/uwsgiplugin.py | 2 +- plugins/php/uwsgiplugin.py | 2 +- plugins/ping/uwsgiplugin.py | 3 +- plugins/psgi/uwsgiplugin.py | 4 +- plugins/pty/uwsgiplugin.py | 5 +- plugins/pypy/pypy_setup.py | 381 ++++++++++-------- plugins/pypy/uwsgiplugin.py | 9 +- plugins/python/uwsgiplugin.py | 36 +- plugins/pyuwsgi/uwsgiplugin.py | 8 +- plugins/rack/uwsgiplugin.py | 13 +- plugins/rados/uwsgiplugin.py | 3 +- plugins/rawrouter/uwsgiplugin.py | 2 +- plugins/rbthreads/uwsgiplugin.py | 2 +- plugins/redislog/uwsgiplugin.py | 2 +- plugins/ring/uwsgiplugin.py | 5 +- plugins/router_access/uwsgiplugin.py | 3 +- plugins/router_basicauth/uwsgiplugin.py | 3 +- plugins/router_cache/uwsgiplugin.py | 2 +- plugins/router_expires/uwsgiplugin.py | 2 +- plugins/router_hash/uwsgiplugin.py | 2 +- plugins/router_http/uwsgiplugin.py | 2 +- plugins/router_memcached/uwsgiplugin.py | 2 +- plugins/router_metrics/uwsgiplugin.py | 2 +- plugins/router_radius/uwsgiplugin.py | 2 +- plugins/router_redirect/uwsgiplugin.py | 2 +- plugins/router_redis/uwsgiplugin.py | 2 +- plugins/router_rewrite/uwsgiplugin.py | 2 +- plugins/router_spnego/uwsgiplugin.py | 3 +- plugins/router_static/uwsgiplugin.py | 2 +- plugins/router_uwsgi/uwsgiplugin.py | 2 +- plugins/router_xmldir/uwsgiplugin.py | 3 +- plugins/rpc/uwsgiplugin.py | 2 +- plugins/rrdtool/uwsgiplugin.py | 2 +- plugins/rsyslog/uwsgiplugin.py | 2 +- plugins/ruby19/uwsgiplugin.py | 13 +- plugins/servlet/uwsgiplugin.py | 4 +- plugins/signal/uwsgiplugin.py | 2 +- plugins/spooler/uwsgiplugin.py | 2 +- plugins/sqlite3/uwsgiplugin.py | 2 +- plugins/ssi/uwsgiplugin.py | 2 +- plugins/sslrouter/uwsgiplugin.py | 2 +- plugins/stackless/uwsgiplugin.py | 8 +- plugins/stats_pusher_file/uwsgiplugin.py | 2 +- plugins/stats_pusher_mongodb/uwsgiplugin.py | 9 +- plugins/stats_pusher_socket/uwsgiplugin.py | 2 +- plugins/stats_pusher_statsd/uwsgiplugin.py | 2 +- plugins/symcall/uwsgiplugin.py | 2 +- plugins/syslog/uwsgiplugin.py | 2 +- plugins/systemd_logger/uwsgiplugin.py | 5 +- plugins/tornado/uwsgiplugin.py | 8 +- plugins/transformation_chunked/uwsgiplugin.py | 2 +- plugins/transformation_gzip/uwsgiplugin.py | 2 +- plugins/transformation_offload/uwsgiplugin.py | 2 +- .../transformation_template/uwsgiplugin.py | 2 +- plugins/transformation_tofile/uwsgiplugin.py | 2 +- plugins/transformation_toupper/uwsgiplugin.py | 2 +- plugins/tuntap/uwsgiplugin.py | 11 +- plugins/ugreen/uwsgiplugin.py | 2 +- plugins/v8/uwsgiplugin.py | 3 +- plugins/webdav/uwsgiplugin.py | 3 +- plugins/xattr/uwsgiplugin.py | 9 +- plugins/xslt/uwsgiplugin.py | 3 +- plugins/zabbix/uwsgiplugin.py | 2 +- plugins/zergpool/uwsgiplugin.py | 2 +- setup.cpyext.py | 37 +- setup.py | 24 +- t/cachebitmap.py | 43 +- t/cachetest.py | 22 +- t/pypy/t_continulet1.py | 6 +- t/pypy/t_continulet2.py | 8 +- .../spooler_decorators/spooler_handlers.py | 2 +- t/python/spooler_handler.py | 26 +- .../spooler_priority_constants.py | 24 +- .../spooler_priority_handler.py | 24 +- .../spooler_priority/spooler_priority_test.py | 91 +++-- t/python/testba.py | 6 +- tests/badthread.py | 4 +- tests/badwrites.py | 2 +- tests/cpubound_async.py | 7 +- tests/cpubound_green.py | 23 +- tests/cpubound_stackless.py | 20 +- tests/decoratortest.py | 29 +- tests/fileserve_async.py | 16 +- tests/gevent_spool.py | 6 +- tests/grunter.py | 29 +- tests/iobound_async.py | 56 +-- tests/iobound_async_unix.py | 68 ++-- tests/iobound_green.py | 53 +-- tests/logger.py | 13 +- tests/mako_ugreen.py | 17 +- tests/mulefunc.py | 20 +- tests/myadmin.py | 13 +- tests/pgbound_async.py | 47 +-- tests/picazzo.py | 26 +- tests/psycogreen_green.py | 52 +-- tests/psycopg2_green.py | 67 ++- tests/pump.py | 17 +- tests/queue.py | 14 +- tests/refcount.py | 3 +- tests/runningthread.py | 1 + tests/sharedarea.py | 3 +- tests/signals.py | 23 +- tests/sigwait.py | 4 +- tests/sleeping_async.py | 3 +- tests/sleeping_green.py | 4 +- tests/sleepthreadasync.py | 10 +- tests/slow.py | 7 +- tests/spoolme.py | 12 +- tests/staticfile.py | 4 +- tests/testapp.py | 59 ++- tests/testgevent.py | 7 +- tests/testpy3.py | 6 +- tests/testsignals.py | 4 +- tests/threads.py | 40 +- tests/ugevent.py | 14 +- tests/websockets.py | 27 +- tests/websockets_chat.py | 31 +- tests/websockets_chat_async.py | 29 +- tests/websockets_chat_asyncio.py | 44 +- tests/websockets_echo.py | 13 +- tests/werkzeug.py | 2 +- uwsgiconfig.py | 261 ++++++------ uwsgidecorators.py | 2 +- vhosttest/flask001/app1.py | 1 + vhosttest/flask002/app2.py | 1 + vhosttest/flask003/app3.py | 1 + vhosttest/flask004/app4.py | 1 + vhosttest/flask005/app5.py | 1 + 211 files changed, 1622 insertions(+), 1311 deletions(-) diff --git a/contrib/graphite_uwsgi.py b/contrib/graphite_uwsgi.py index 3d2c8b2c..59f9ad87 100644 --- a/contrib/graphite_uwsgi.py +++ b/contrib/graphite_uwsgi.py @@ -15,6 +15,7 @@ os.environ['DJANGO_SETTINGS_MODULE'] = 'settings' CARBON_SERVER = "127.0.0.1:2003" + def update_carbon(signum): # connect to the carbon server carbon_fd = uwsgi.connect(CARBON_SERVER) diff --git a/contrib/pypy/uwsgi_pypy_greenlets.py b/contrib/pypy/uwsgi_pypy_greenlets.py index 7843f177..81d4c842 100644 --- a/contrib/pypy/uwsgi_pypy_greenlets.py +++ b/contrib/pypy/uwsgi_pypy_greenlets.py @@ -12,13 +12,15 @@ import greenlet uwsgi_pypy_greenlets = {} + def uwsgi_pypy_greenlet_wrapper(): lib.async_schedule_to_req_green() + @ffi.callback("void()") def uwsgi_pypy_greenlet_schedule(): id = lib.uwsgi.wsgi_req.async_id - modifier1 = lib.uwsgi.wsgi_req.uh.modifier1; + modifier1 = lib.uwsgi.wsgi_req.uh.modifier1 # generate a new greenlet if not lib.uwsgi.wsgi_req.suspended: @@ -36,10 +38,11 @@ def uwsgi_pypy_greenlet_schedule(): if lib.uwsgi.p[modifier1].resume: lib.uwsgi.p[modifier1].resume(ffi.NULL) + @ffi.callback("void(struct wsgi_request *)") def uwsgi_pypy_greenlet_switch(wsgi_req): - id = wsgi_req.async_id - modifier1 = wsgi_req.uh.modifier1; + wsgi_req.async_id + modifier1 = wsgi_req.uh.modifier1 # this is called in the current greenlet if lib.uwsgi.p[modifier1].suspend: diff --git a/contrib/pyuwsgi.py b/contrib/pyuwsgi.py index 482f5e24..a478ff97 100644 --- a/contrib/pyuwsgi.py +++ b/contrib/pyuwsgi.py @@ -11,7 +11,7 @@ uwsgi_args = [] for arg in sys.argv[2:]: uwsgi_args.append(arg) -#pyuwsgi.run('welcome.ini') +# pyuwsgi.run('welcome.ini') pyuwsgi.run(uwsgi_args) # if you are here uWSGI has been reloaded diff --git a/contrib/runuwsgi.py b/contrib/runuwsgi.py index f6164b0a..7b8b4956 100644 --- a/contrib/runuwsgi.py +++ b/contrib/runuwsgi.py @@ -4,6 +4,7 @@ from django.conf import settings import os import sys + class Command(BaseCommand): help = "Runs this project as a uWSGI application. Requires the uwsgi binary in system path." @@ -12,10 +13,10 @@ class Command(BaseCommand): def handle(self, *args, **options): for arg in args: - k,v = arg.split('=') + k, v = arg.split('=') if k == 'http': if self.http_port: - self.http_port = v + self.http_port = v elif k == 'socket': self.http_port = None self.socket_addr = v diff --git a/contrib/spoolqueue/producer.py b/contrib/spoolqueue/producer.py index ac6008a7..7edf4e54 100644 --- a/contrib/spoolqueue/producer.py +++ b/contrib/spoolqueue/producer.py @@ -1,11 +1,10 @@ from tasksconsumer import enqueue + def application(env, sr): - sr('200 OK', [('Content-Type','text/html')]) + sr('200 OK', [('Content-Type', 'text/html')]) enqueue(queue='fast', pippo='pluto') return "Task enqueued" - - diff --git a/contrib/spoolqueue/tasks.py b/contrib/spoolqueue/tasks.py index 5d6f55f0..e9048ee8 100644 --- a/contrib/spoolqueue/tasks.py +++ b/contrib/spoolqueue/tasks.py @@ -1,9 +1,11 @@ -from tasksconsumer import * +from tasksconsumer import queueconsumer + @queueconsumer('fast', 4) def fast_queue(arguments): print "fast", arguments + @queueconsumer('slow') def slow_queue(arguments): print "foobar", arguments diff --git a/contrib/spoolqueue/tasksconsumer.py b/contrib/spoolqueue/tasksconsumer.py index 3647670b..f2b6a779 100644 --- a/contrib/spoolqueue/tasksconsumer.py +++ b/contrib/spoolqueue/tasksconsumer.py @@ -1,35 +1,36 @@ -from uwsgidecorators import * +from uwsgidecorators import spool import Queue from threading import Thread queues = {} + class queueconsumer(object): def __init__(self, name, num=1, **kwargs): self.name = name - self.num = num + self.num = num self.queue = Queue.Queue() - self.threads = [] - self.func = None - queues[self.name] = self - + self.threads = [] + self.func = None + queues[self.name] = self @staticmethod def consumer(self): while True: - req = self.queue.get() + req = self.queue.get() print req - self.func(req) - self.queue.task_done() + self.func(req) + self.queue.task_done() def __call__(self, f): self.func = f - for i in range(self.num): - t = Thread(target=self.consumer,args=(self,)) - self.threads.append(t) - t.daemon = True - t.start() + for i in range(self.num): + t = Thread(target=self.consumer, args=(self,)) + self.threads.append(t) + t.daemon = True + t.start() + @spool def spooler_enqueuer(arguments): diff --git a/contrib/twuwsgi.py b/contrib/twuwsgi.py index e606c98f..86d3cdba 100644 --- a/contrib/twuwsgi.py +++ b/contrib/twuwsgi.py @@ -1,22 +1,22 @@ from twisted.internet import defer, protocol, reactor from twisted.protocols import basic -from twisted.web2 import server, http, resource, responsecode, stream, channel -from twisted.application import service, strports +from twisted.web2 import http, resource, responsecode, stream import struct class uWSGIClientResource(resource.LeafResource): - def __init__(self,app='', port=3030, host='localhost'): + def __init__(self, app='', port=3030, host='localhost'): resource.LeafResource.__init__(self) self.host = host self.port = port self.app = app - + def renderHTTP(self, request): return uWSGI(request, self.app, self.host, self.port) + def uWSGI(request, app, host, port): if request.stream.length is None: return http.Response(responsecode.LENGTH_REQUIRED) @@ -25,9 +25,10 @@ def uWSGI(request, app, host, port): factory = uWSGIClientProtocolFactory(request) reactor.connectTCP(host, port, factory) return factory.deferred - + + class uWSGIClientProtocol(basic.LineReceiver): - + def __init__(self, request, deferred): self.request = request self.deferred = deferred @@ -35,8 +36,8 @@ class uWSGIClientProtocol(basic.LineReceiver): self.response = http.Response(stream=self.stream) self.status_parsed = None - def build_uwsgi_var(self,key,value): - return struct.pack(' 0]) @@ -68,54 +69,75 @@ class Cache: self.samples += 1 block_sizes = sum([x[3] for x in data]) self.block_sizes += block_sizes - self.history.append({'full': full, 'empty': empty, 'data': data, \ - 'items': items, 'block_sizes': block_sizes}) + self.history.append({ + 'full': full, + 'empty': empty, + 'data': data, + 'items': items, + 'block_sizes': block_sizes + }) def dump(self): return { 'samples': self.samples, 'history': self.history, 'cache_slots': self.cache_slots, - 'sample_sleep': self.sample_sleep, + 'sample_sleep': self.sample_sleep, 'cache_empty': self.cache_empty, 'cache_full': self.cache_full, 'cache_items': self.cache_items, 'block_sizes': self.block_sizes, - } + } def show_dump(self): d = self.dump() print() - print("Recorded %d samples (%d second(s) sleep between samples)" % \ - (d['samples'], d['sample_sleep'])) - print("Cache empty %d times, full %d times, %.2f items on average" % \ - (d['cache_empty'], d['cache_full'], d['cache_items'] / d['samples'])) - print("Block size average size: %d bytes" % \ - (d['block_sizes'] / d['cache_items'] * 8)) - print("Data in cache average: %d bytes" % \ - (d['block_sizes'] / d['samples'] * 8)) + print("Recorded %d samples (%d second(s) sleep between samples)" % ( + d['samples'], + d['sample_sleep'] + )) + print("Cache empty %d times, full %d times, %.2f items on average" % ( + d['cache_empty'], + d['cache_full'], + d['cache_items'] / d['samples'] + )) + print("Block size average size: %d bytes" % ( + d['block_sizes'] / d['cache_items'] * 8 + )) + print("Data in cache average: %d bytes" % ( + d['block_sizes'] / d['samples'] * 8 + )) + def main(options): cache = Cache(options.cache_store, options.cache_slots, options.block_size, - options.sleep_time) + options.sleep_time) print("Recording...") while True: try: - data = cache.read() + cache.read() except KeyboardInterrupt: cache.show_dump() sys.exit(0) if __name__ == '__main__': parser = OptionParser() - parser.add_option("-s", "--cache-slots", dest="cache_slots", type="int", - help="Slots available in the cache, uwsgi cache option") - parser.add_option("-c", "--cache-store", dest="cache_store", default="uwsgi.cache", - help="The filename of the cache store, uwsgi cache-store option. Default: uwsgi.cache") - parser.add_option("-b", "--block-size", dest="block_size", default=65536, type="int", - help="The size of the cache block, uwsgi cache-blocksize option. Default: 65536") - parser.add_option("-t", "--sleep-time", dest="sleep_time", default=1, type="int", - help="The time to sleep between each sample. Default: 1") + parser.add_option( + "-s", "--cache-slots", dest="cache_slots", type="int", + help="Slots available in the cache, uwsgi cache option" + ) + parser.add_option( + "-c", "--cache-store", dest="cache_store", default="uwsgi.cache", + help="The filename of the cache store, uwsgi cache-store option. Default: uwsgi.cache" + ) + parser.add_option( + "-b", "--block-size", dest="block_size", default=65536, type="int", + help="The size of the cache block, uwsgi cache-blocksize option. Default: 65536" + ) + parser.add_option( + "-t", "--sleep-time", dest="sleep_time", default=1, type="int", + help="The time to sleep between each sample. Default: 1" + ) (options, args) = parser.parse_args() if not options.cache_slots: diff --git a/examples/flaskpost.py b/examples/flaskpost.py index 81206104..c36a0cf0 100644 --- a/examples/flaskpost.py +++ b/examples/flaskpost.py @@ -2,10 +2,12 @@ from flask import Flask, request app = Flask(__name__) app.debug = True + @app.route('/') def hello_world(): return "
" + @app.route('/upload', methods=['GET', 'POST']) def upload_file(): return str(len(request.form.get('pippo', 'boh'))) + request.form.get('pippo', 'boh') diff --git a/examples/heavytest.py b/examples/heavytest.py index bcef7b6f..26f582c1 100644 --- a/examples/heavytest.py +++ b/examples/heavytest.py @@ -3,12 +3,18 @@ import werkzeug.testapp uwsgi.cache_set("/cache/get", "HTTP 1.1 200 OK\r\nContent-Type: text/html\r\n\r\n

I am the uWSGI cache

") + def app001(env, start_response): start_response('200 OK', [('Content-Type', 'text/html')]) return "PATH_INFO=%s" % env['PATH_INFO'] + def app002(env, start_response): start_response('200 OK', [('Content-Type', 'text/html')]) return "requests: %d" % uwsgi.total_requests() -uwsgi.applications = { '':werkzeug.testapp.test_app, '/app001':app001, '/app002':app002 } +uwsgi.applications = { + '': werkzeug.testapp.test_app, + '/app001': app001, + '/app002': app002 +} diff --git a/examples/mjpeg_stream.py b/examples/mjpeg_stream.py index ae9e5474..9ed082c1 100644 --- a/examples/mjpeg_stream.py +++ b/examples/mjpeg_stream.py @@ -1,25 +1,23 @@ -import uwsgi import os + def application(env, start_response): - boundary = 'uwsgi_mjpeg_frame' + boundary = 'uwsgi_mjpeg_frame' - start_response('200 Ok', [ + start_response('200 Ok', [ + ('Cache-Control', 'no-cache'), + ('Cache-Control', 'private'), + ('Pragma', 'no-cache'), + ('Content-Type', 'multipart/x-mixed-replace; boundary=' + boundary), + ]) - ('Cache-Control', 'no-cache'), - ('Cache-Control', 'private'), - ('Pragma', 'no-cache'), - ('Content-Type', 'multipart/x-mixed-replace; boundary=' + boundary), - ] - ) + yield "--%s\r\n" % boundary - yield "--%s\r\n" % boundary - - while 1: - yield "Content-Type: image/jpeg\r\n\r\n" - print os.system('screencapture -t jpg -m -T 1 screenshot.jpg') - f = open('screenshot.jpg') - yield env['wsgi.file_wrapper'](f) - yield "\r\n--%s\r\n" % boundary - #os.system('./isightcapture -w 640 -h 480 screenshot.jpg') + while 1: + yield "Content-Type: image/jpeg\r\n\r\n" + print os.system('screencapture -t jpg -m -T 1 screenshot.jpg') + f = open('screenshot.jpg') + yield env['wsgi.file_wrapper'](f) + yield "\r\n--%s\r\n" % boundary + # os.system('./isightcapture -w 640 -h 480 screenshot.jpg') diff --git a/examples/multiapp.py b/examples/multiapp.py index 5b2f1125..80b06621 100644 --- a/examples/multiapp.py +++ b/examples/multiapp.py @@ -1,22 +1,30 @@ import werkzeug import uwsgi -def zero_app(e,s): - s('200 OK', [ ('Content-Type', 'text/plain') ]) + +def zero_app(e, s): + s('200 OK', [('Content-Type', 'text/plain')]) return "0" -def not_found(e,s): - s('404 Not Found', [ ('Content-Type', 'text/plain') ]) + +def not_found(e, s): + s('404 Not Found', [('Content-Type', 'text/plain')]) return "" def wsgi_app(e, s): - s('200 OK', [ ('Content-Type', 'text/plain') ]) + s('200 OK', [('Content-Type', 'text/plain')]) yield "I am a WSGI app\n" def internal_server_error(e, s): - s('500 Internal Server Error', [ ('Content-Type', 'text/plain') ]) + s('500 Internal Server Error', [('Content-Type', 'text/plain')]) return "" -uwsgi.applications = {'/wsgi':wsgi_app, '/test':werkzeug.test_app, '/zero':zero_app, '/notfound':not_found, '/ise':internal_server_error} +uwsgi.applications = { + '/wsgi': wsgi_app, + '/test': werkzeug.test_app, + '/zero': zero_app, + '/notfound': not_found, + '/ise': internal_server_error +} diff --git a/examples/simple_app.py b/examples/simple_app.py index d6ebb7cc..7a5afbb9 100644 --- a/examples/simple_app.py +++ b/examples/simple_app.py @@ -3,9 +3,11 @@ import os print("!!! uWSGI version:", uwsgi.version) + def ciao(): print("modifica su /tmp") + def ciao2(): print("nuovo uwsgi_server") print os.getpid() @@ -23,17 +25,15 @@ counter = 0 uwsgi.post_fork_hook = ciao2 -def application(env, start_response): +def application(env, start_response): global counter - - #print(env) start_response('200 Ok', [('Content-type', 'text/plain')]) yield "hello world" yield "hello world2" - for i in range(1,1000): + for i in range(1, 1000): yield str(i) yield "\n" diff --git a/examples/simple_app_wsgi2.py b/examples/simple_app_wsgi2.py index 0dffd9c5..ba176e43 100644 --- a/examples/simple_app_wsgi2.py +++ b/examples/simple_app_wsgi2.py @@ -1,9 +1,9 @@ def mygen(uri): - for i in xrange(1,100): + for i in xrange(1, 100): yield "ciao %s
" % uri -def application(env, start_response = None): +def application(env, start_response=None): return '200 OK', [('Content-Type', 'text/html')], "

This is the fastest homepage of the world !!!

" - #return '200 OK', [('Content-Type', 'text/html')], mygen(env['PATH_INFO']) + # return '200 OK', [('Content-Type', 'text/html')], mygen(env['PATH_INFO']) diff --git a/examples/simple_logger.py b/examples/simple_logger.py index 49bffc95..082aca99 100644 --- a/examples/simple_logger.py +++ b/examples/simple_logger.py @@ -1,6 +1,7 @@ import uwsgi + def print_logs(ip, port, message): - print(ip, port, message) + print(ip, port, message) uwsgi.udp_callable = print_logs diff --git a/examples/staticfilesnmp.py b/examples/staticfilesnmp.py index 315e85c9..0eb51872 100644 --- a/examples/staticfilesnmp.py +++ b/examples/staticfilesnmp.py @@ -4,10 +4,11 @@ from os import path uwsgi.snmp_set_counter64(1, 0) # Number of requests uwsgi.snmp_set_counter64(2, 0) # Number of bytes + def application(environ, start_response): size = path.getsize('logo_uWSGI.png') - start_response('200 OK', [('Content-Type', 'image/png'), ('Content-Length', str(size))] ) - fd = open('logo_uWSGI.png','r') + start_response('200 OK', [('Content-Type', 'image/png'), ('Content-Length', str(size))]) + fd = open('logo_uWSGI.png', 'r') uwsgi.snmp_incr_counter64(1) uwsgi.snmp_incr_counter64(2, size) return environ['wsgi.file_wrapper'](fd, 4096) diff --git a/examples/taskqueue.py b/examples/taskqueue.py index 121da38a..71131759 100644 --- a/examples/taskqueue.py +++ b/examples/taskqueue.py @@ -4,22 +4,24 @@ import uwsgi CONSUMERS = 4 + def consumer(q): while True: item = q.get() print(item) - #... DO A HEAVY TASK HERE ... + # ... DO A HEAVY TASK HERE ... q.task_done() + def spawn_consumers(): global q q = Queue.Queue() for i in range(CONSUMERS): - t = Thread(target=consumer,args=(q,)) + t = Thread(target=consumer, args=(q,)) t.daemon = True t.start() print("consumer %d on worker %d started" % (i, uwsgi.worker_id())) - + uwsgi.post_fork_hook = spawn_consumers @@ -33,4 +35,3 @@ def application(env, start_response): start_response('200 OK', [('Content-Type', 'text/html')]) yield "Task enqueued" - diff --git a/examples/uwsgirouter.py b/examples/uwsgirouter.py index a6225373..6da6cc38 100644 --- a/examples/uwsgirouter.py +++ b/examples/uwsgirouter.py @@ -1,78 +1,76 @@ import uwsgi + def application(env, start_response): - # open the socket - fd = uwsgi.async_connect("192.168.173.100:3032") + # open the socket + fd = uwsgi.async_connect("192.168.173.100:3032") - # wait for connection ready (3s timeout) - yield uwsgi.wait_fd_write(fd, 3) + # wait for connection ready (3s timeout) + yield uwsgi.wait_fd_write(fd, 3) - # has timed out ? - if env['x-wsgiorg.fdevent.timeout']: - print "connection timed out !!!" - uwsgi.close(fd) - raise StopIteration + # has timed out ? + if env['x-wsgiorg.fdevent.timeout']: + print "connection timed out !!!" + uwsgi.close(fd) + raise StopIteration - # connection refused ? - if not uwsgi.is_connected(fd): - print "unable to connect" - uwsgi.close(fd) - raise StopIteration - + # connection refused ? + if not uwsgi.is_connected(fd): + print "unable to connect" + uwsgi.close(fd) + raise StopIteration - # send request - # env can contains python objects, but send_message will discard them. - # In this way we will automagically have a congruent and valid uwsgi packet - uwsgi.async_send_message(fd, 0, 0, env) + # send request + # env can contains python objects, but send_message will discard them. + # In this way we will automagically have a congruent and valid uwsgi packet + uwsgi.async_send_message(fd, 0, 0, env) - # send the http body - # ready body in async mode and resend to fd - # uwsgi.recv will use always an internal buffer of 4096, but can be limited in the number of bytes to read + # send the http body + # ready body in async mode and resend to fd + # uwsgi.recv will use always an internal buffer of 4096, but can be limited in the number of bytes to read - # does this request has a body ? - cl = uwsgi.cl() + # does this request has a body ? + cl = uwsgi.cl() - if cl > 0: - # get the input fd - input = env['wsgi.input'].fileno() + if cl > 0: + # get the input fd + input = env['wsgi.input'].fileno() - # read (in async mode) upto 'cl' data and send to uwsgi peer - while cl > 0: - bufsize = min(cl, 4096) - yield uwsgi.wait_fd_read(input, 30) - if env['x-wsgiorg.fdevent.timeout']: - print "connection timed out !!!" - uwsgi.close(fd) - raise StopIteration - body = uwsgi.recv(input, bufsize) - if body: - uwsgi.send(fd, body) - cl = cl - len(body) - else: - break - + # read (in async mode) upto 'cl' data and send to uwsgi peer + while cl > 0: + bufsize = min(cl, 4096) + yield uwsgi.wait_fd_read(input, 30) + if env['x-wsgiorg.fdevent.timeout']: + print "connection timed out !!!" + uwsgi.close(fd) + raise StopIteration + body = uwsgi.recv(input, bufsize) + if body: + uwsgi.send(fd, body) + cl = cl - len(body) + else: + break - # wait for response (30s timeout) - yield uwsgi.wait_fd_read(fd, 30) + # wait for response (30s timeout) + yield uwsgi.wait_fd_read(fd, 30) - # has timed out ? - if env['x-wsgiorg.fdevent.timeout']: - print "connection timed out !!!" - uwsgi.close(fd) - raise StopIteration + # has timed out ? + if env['x-wsgiorg.fdevent.timeout']: + print "connection timed out !!!" + uwsgi.close(fd) + raise StopIteration - data = uwsgi.recv(fd) - # recv the data, if it returns None the callable will end - while data: - yield data - # wait for response - yield uwsgi.wait_fd_read(fd, 30) - if env['x-wsgiorg.fdevent.timeout']: - print "connection timed out !!!" - uwsgi.close(fd) - raise StopIteration - data = uwsgi.recv(fd) + data = uwsgi.recv(fd) + # recv the data, if it returns None the callable will end + while data: + yield data + # wait for response + yield uwsgi.wait_fd_read(fd, 30) + if env['x-wsgiorg.fdevent.timeout']: + print "connection timed out !!!" + uwsgi.close(fd) + raise StopIteration + data = uwsgi.recv(fd) - uwsgi.close(fd) - + uwsgi.close(fd) diff --git a/examples/uwsgirouter2.py b/examples/uwsgirouter2.py index 430336b7..37ff9bcb 100644 --- a/examples/uwsgirouter2.py +++ b/examples/uwsgirouter2.py @@ -2,7 +2,7 @@ import uwsgi -def application(e,s): +def application(e, s): - for part in uwsgi.send_message("192.168.173.100:3032", 0, 0, e, 0, e['wsgi.input'].fileno(), uwsgi.cl()): - yield part + for part in uwsgi.send_message("192.168.173.100:3032", 0, 0, e, 0, e['wsgi.input'].fileno(), uwsgi.cl()): + yield part diff --git a/examples/uwsgirouter3.py b/examples/uwsgirouter3.py index a1941c1c..37b4b894 100644 --- a/examples/uwsgirouter3.py +++ b/examples/uwsgirouter3.py @@ -3,23 +3,24 @@ import uwsgi current_node = 0 -def application(e,s): - global current_node +def application(e, s): - nodes = uwsgi.cluster_nodes() - print nodes + global current_node - if len(nodes) == 0: - print "no cluster node available" - raise StopIteration + nodes = uwsgi.cluster_nodes() + print nodes - if current_node >= len(nodes): - current_node = 0 + if len(nodes) == 0: + print "no cluster node available" + raise StopIteration - node = nodes[current_node] + if current_node >= len(nodes): + current_node = 0 - for part in uwsgi.send_message(node, 0, 0, e, 0, e['wsgi.input'].fileno(), uwsgi.cl()): - yield part + node = nodes[current_node] - current_node+=1 + for part in uwsgi.send_message(node, 0, 0, e, 0, e['wsgi.input'].fileno(), uwsgi.cl()): + yield part + + current_node += 1 diff --git a/examples/uwsgirouter4.py b/examples/uwsgirouter4.py index ce8e6fc4..7786ff6e 100644 --- a/examples/uwsgirouter4.py +++ b/examples/uwsgirouter4.py @@ -1,14 +1,15 @@ import uwsgi -def application(e,s): - node = uwsgi.cluster_best_node() - print node +def application(e, s): - if not node: - print "sorry node unavailable" - raise StopIteration + node = uwsgi.cluster_best_node() + print node - for part in uwsgi.send_message(node, 0, 0, e, 0, e['wsgi.input'].fileno(), uwsgi.cl()): - yield part + if not node: + print "sorry node unavailable" + raise StopIteration + + for part in uwsgi.send_message(node, 0, 0, e, 0, e['wsgi.input'].fileno(), uwsgi.cl()): + yield part diff --git a/examples/uwsgirouter5.py b/examples/uwsgirouter5.py index af27b6ba..85f4ed7f 100644 --- a/examples/uwsgirouter5.py +++ b/examples/uwsgirouter5.py @@ -3,7 +3,8 @@ import uwsgi fd = uwsgi.connect("127.0.0.1:3033") -def application(e,s): - for part in uwsgi.send_message(fd, 0, 4, e, 30, e['wsgi.input'].fileno(), uwsgi.cl()): - yield part +def application(e, s): + + for part in uwsgi.send_message(fd, 0, 4, e, 30, e['wsgi.input'].fileno(), uwsgi.cl()): + yield part diff --git a/examples/uwsgistatus.py b/examples/uwsgistatus.py index 3b3b0851..312ecc16 100644 --- a/examples/uwsgistatus.py +++ b/examples/uwsgistatus.py @@ -36,7 +36,7 @@ def application(env, start_response): yield "

Hooks

" - for h in range(0,255): + for h in range(0, 255): if uwsgi.has_hook(h): yield "%d
" % h @@ -45,15 +45,15 @@ def application(env, start_response): yield '' yield '' - workers = uwsgi.workers(); + workers = uwsgi.workers() yield '

workers

' for w in workers: - #print w - #print w['running_time'] + # print w + # print w['running_time'] if w is not None: - yield '' + yield '' print w yield '
worker idpidin requestrequestsrunning timeaddress spacerss
'+ str(w['id']) +'' + str(w['pid']) + '' + str(w['pid']) + '' + str(w['requests']) + '' + str(w['running_time']) + '' + str(w['vsz']) + '' + str(w['rss']) + '
' + str(w['id']) + '' + str(w['pid']) + '' + str(w['pid']) + '' + str(w['requests']) + '' + str(w['running_time']) + '' + str(w['vsz']) + '' + str(w['rss']) + '
' diff --git a/examples/welcome.py b/examples/welcome.py index 8db7af64..221d483a 100644 --- a/examples/welcome.py +++ b/examples/welcome.py @@ -2,7 +2,8 @@ import uwsgi import os import gc import sys -from uwsgidecorators import * +from uwsgidecorators import rpc, signal, postfork + print(sys.version) print(sys.version_info) if 'set_debug' in gc.__dict__: @@ -26,6 +27,7 @@ def after_request_hook(): uwsgi.after_req_hook = after_request_hook + @rpc('hello') def hello_rpc(one, two, three): arg0 = one[::-1] @@ -33,20 +35,24 @@ def hello_rpc(one, two, three): arg2 = three[::-1] return "!%s-%s-%s!" % (arg1, arg2, arg0) + @signal(17) def ciao_mondo(signum): print("Hello World") + def xsendfile(e, sr): sr('200 OK', [('Content-Type', 'image/png'), ('X-Sendfile', os.path.abspath('logo_uWSGI.png'))]) return '' + def serve_logo(e, sr): # use raw facilities (status will not be set...) uwsgi.send("%s 200 OK\r\nContent-Type: image/png\r\n\r\n" % e['SERVER_PROTOCOL']) uwsgi.sendfile('logo_uWSGI.png') return '' + def serve_config(e, sr): sr('200 OK', [('Content-Type', 'text/html')]) for opt in uwsgi.opt.keys(): @@ -57,11 +63,13 @@ routes['/xsendfile'] = xsendfile routes['/logo'] = serve_logo routes['/config'] = serve_config + @postfork def setprocname(): if uwsgi.worker_id() > 0: uwsgi.setprocname("i am the worker %d" % uwsgi.worker_id()) + def application(env, start_response): try: uwsgi.mule_msg(env['REQUEST_URI'], 1) @@ -82,7 +90,6 @@ def application(env, start_response): if env['PATH_INFO'] in routes: return routes[env['PATH_INFO']](env, start_response) - if DEBUG: print(env['wsgi.input'].fileno()) @@ -98,7 +105,7 @@ def application(env, start_response): for w in uwsgi.workers(): apps = '' for app in w['apps']: - apps += '' % (app['id'], app['mountpoint'], app['startup_time'], app['requests']) + apps += '' % (app['id'], app['mountpoint'], app['startup_time'], app['requests']) apps += '
idmountpointstartup timerequests
%d%s%d%d
%d%s%d%d
' workers += """ @@ -122,14 +129,9 @@ Workers and applications
%s - """ % (uwsgi.version, uwsgi.hostname, env.get('REMOTE_USER','None'), workers) + """ % (uwsgi.version, uwsgi.hostname, env.get('REMOTE_USER', 'None'), workers) - start_response('200 OK', [('Content-Type', 'text/html'), ('Content-Length', str(len(output)) )]) + start_response('200 OK', [('Content-Type', 'text/html'), ('Content-Length', str(len(output)))]) - #return bytes(output.encode('latin1')) + # return bytes(output.encode('latin1')) return output - - - - - diff --git a/examples/welcome3.py b/examples/welcome3.py index 6f5a9d13..4d308d17 100644 --- a/examples/welcome3.py +++ b/examples/welcome3.py @@ -1,14 +1,17 @@ import uwsgi import os + def xsendfile(e, sr): sr('200 OK', [('Content-Type', 'image/png'), ('X-Sendfile', os.path.abspath('logo_uWSGI.png'))]) return b'' + def serve_logo(e, sr): sr('200 OK', [('Content-Type', 'image/png')]) return uwsgi.sendfile('logo_uWSGI.png') + def serve_config(e, sr): sr('200 OK', [('Content-Type', 'text/html')]) for opt in uwsgi.opt.keys(): @@ -20,6 +23,7 @@ routes['/xsendfile'] = xsendfile routes['/logo'] = serve_logo routes['/config'] = serve_config + def application(env, start_response): if env['PATH_INFO'] in routes: @@ -39,9 +43,3 @@ Configuration
""".format(version=uwsgi.version.decode('ascii')) return bytes(body.encode('ascii')) - - - - - - diff --git a/plugins/airbrake/uwsgiplugin.py b/plugins/airbrake/uwsgiplugin.py index 10db6fc1..6d62304a 100644 --- a/plugins/airbrake/uwsgiplugin.py +++ b/plugins/airbrake/uwsgiplugin.py @@ -1,9 +1,11 @@ from uwsgiconfig import spcall -NAME='airbrake' +NAME = 'airbrake' CFLAGS = [spcall('xml2-config --cflags')] LDFLAGS = [] -LIBS = ['-lcurl', spcall('xml2-config --libs')] +LIBS = [ + '-lcurl', + spcall('xml2-config --libs') +] GCC_LIST = ['airbrake_plugin'] - diff --git a/plugins/alarm_curl/uwsgiplugin.py b/plugins/alarm_curl/uwsgiplugin.py index bd83e3ba..edc7ae38 100644 --- a/plugins/alarm_curl/uwsgiplugin.py +++ b/plugins/alarm_curl/uwsgiplugin.py @@ -1,4 +1,4 @@ -NAME='alarm_curl' +NAME = 'alarm_curl' CFLAGS = [] LDFLAGS = [] diff --git a/plugins/alarm_speech/uwsgiplugin.py b/plugins/alarm_speech/uwsgiplugin.py index dead5faa..e24ad537 100644 --- a/plugins/alarm_speech/uwsgiplugin.py +++ b/plugins/alarm_speech/uwsgiplugin.py @@ -1,6 +1,6 @@ import os -NAME='alarm_speech' +NAME = 'alarm_speech' uwsgi_os = os.uname()[0] diff --git a/plugins/alarm_xmpp/uwsgiplugin.py b/plugins/alarm_xmpp/uwsgiplugin.py index 16c93546..1ba20e61 100644 --- a/plugins/alarm_xmpp/uwsgiplugin.py +++ b/plugins/alarm_xmpp/uwsgiplugin.py @@ -1,4 +1,4 @@ -NAME='alarm_xmpp' +NAME = 'alarm_xmpp' CFLAGS = [] LDFLAGS = [] diff --git a/plugins/asyncio/uwsgiplugin.py b/plugins/asyncio/uwsgiplugin.py index 0441db41..7cb17f54 100644 --- a/plugins/asyncio/uwsgiplugin.py +++ b/plugins/asyncio/uwsgiplugin.py @@ -1,8 +1,11 @@ from distutils import sysconfig -NAME='asyncio' -CFLAGS = ['-I' + sysconfig.get_python_inc(), '-I' + sysconfig.get_python_inc(plat_specific=True)] +NAME = 'asyncio' + +CFLAGS = [ + '-I' + sysconfig.get_python_inc(), + '-I' + sysconfig.get_python_inc(plat_specific=True) +] LDFLAGS = [] LIBS = [] - GCC_LIST = ['asyncio'] diff --git a/plugins/cache/uwsgiplugin.py b/plugins/cache/uwsgiplugin.py index 560e7c3a..cb9a24d6 100644 --- a/plugins/cache/uwsgiplugin.py +++ b/plugins/cache/uwsgiplugin.py @@ -1,5 +1,5 @@ +NAME = 'cache' -NAME='cache' CFLAGS = [] LDFLAGS = [] LIBS = [] diff --git a/plugins/carbon/uwsgiplugin.py b/plugins/carbon/uwsgiplugin.py index 9aa41e00..8132311a 100644 --- a/plugins/carbon/uwsgiplugin.py +++ b/plugins/carbon/uwsgiplugin.py @@ -1,7 +1,6 @@ +NAME = 'carbon' -NAME='carbon' CFLAGS = [] LDFLAGS = [] LIBS = [] - GCC_LIST = ['carbon'] diff --git a/plugins/cgi/uwsgiplugin.py b/plugins/cgi/uwsgiplugin.py index 983040f3..2b5cf901 100644 --- a/plugins/cgi/uwsgiplugin.py +++ b/plugins/cgi/uwsgiplugin.py @@ -1,4 +1,5 @@ -NAME='cgi' +NAME = 'cgi' + CFLAGS = [] LDFLAGS = [] LIBS = [] diff --git a/plugins/cheaper_backlog2/uwsgiplugin.py b/plugins/cheaper_backlog2/uwsgiplugin.py index f63ee5e6..4f0cd6b1 100644 --- a/plugins/cheaper_backlog2/uwsgiplugin.py +++ b/plugins/cheaper_backlog2/uwsgiplugin.py @@ -1,4 +1,4 @@ -NAME='cheaper_backlog2' +NAME = 'cheaper_backlog2' CFLAGS = [] LDFLAGS = [] diff --git a/plugins/cheaper_busyness/uwsgiplugin.py b/plugins/cheaper_busyness/uwsgiplugin.py index e4e0743c..128d01b3 100644 --- a/plugins/cheaper_busyness/uwsgiplugin.py +++ b/plugins/cheaper_busyness/uwsgiplugin.py @@ -1,4 +1,4 @@ -NAME='cheaper_busyness' +NAME = 'cheaper_busyness' CFLAGS = [] LDFLAGS = [] diff --git a/plugins/clock_monotonic/uwsgiplugin.py b/plugins/clock_monotonic/uwsgiplugin.py index b3e98cc0..fa32c5a6 100644 --- a/plugins/clock_monotonic/uwsgiplugin.py +++ b/plugins/clock_monotonic/uwsgiplugin.py @@ -1,4 +1,4 @@ -NAME='clock_monotonic' +NAME = 'clock_monotonic' CFLAGS = [] LDFLAGS = [] diff --git a/plugins/clock_realtime/uwsgiplugin.py b/plugins/clock_realtime/uwsgiplugin.py index 9da5436c..198cf748 100644 --- a/plugins/clock_realtime/uwsgiplugin.py +++ b/plugins/clock_realtime/uwsgiplugin.py @@ -1,4 +1,4 @@ -NAME='clock_realtime' +NAME = 'clock_realtime' CFLAGS = [] LDFLAGS = [] diff --git a/plugins/corerouter/uwsgiplugin.py b/plugins/corerouter/uwsgiplugin.py index 7f55569e..37a42109 100644 --- a/plugins/corerouter/uwsgiplugin.py +++ b/plugins/corerouter/uwsgiplugin.py @@ -1,5 +1,5 @@ +NAME = 'corerouter' -NAME='corerouter' CFLAGS = [] LDFLAGS = [] LIBS = [] diff --git a/plugins/coroae/uwsgiplugin.py b/plugins/coroae/uwsgiplugin.py index 6d35564e..83c2b25e 100644 --- a/plugins/coroae/uwsgiplugin.py +++ b/plugins/coroae/uwsgiplugin.py @@ -1,6 +1,8 @@ import os import sys +NAME = 'coroae' + coroapi = None search_paths = os.popen('perl -MConfig -e \'print $Config{sitearch}.",".join(",", @INC);\'').read().rstrip().split(',') @@ -12,7 +14,6 @@ if not coroapi: print "unable to find the Coro perl module !!!" sys.exit(1) -NAME='coroae' CFLAGS = os.popen('perl -MExtUtils::Embed -e ccopts').read().rstrip().split() CFLAGS += ['-Wno-int-to-pointer-cast', '-Wno-error=format', '-Wno-error=int-to-pointer-cast', '-I%s/Coro' % coroapi] LDFLAGS = [] diff --git a/plugins/cplusplus/uwsgiplugin.py b/plugins/cplusplus/uwsgiplugin.py index 07548c63..7e1063d3 100644 --- a/plugins/cplusplus/uwsgiplugin.py +++ b/plugins/cplusplus/uwsgiplugin.py @@ -1,4 +1,4 @@ -NAME='cplusplus' +NAME = 'cplusplus' CFLAGS = [] LDFLAGS = [] diff --git a/plugins/curl_cron/uwsgiplugin.py b/plugins/curl_cron/uwsgiplugin.py index 4c8672f1..ad0eea74 100644 --- a/plugins/curl_cron/uwsgiplugin.py +++ b/plugins/curl_cron/uwsgiplugin.py @@ -1,4 +1,4 @@ -NAME='curl_cron' +NAME = 'curl_cron' CFLAGS = [] LDFLAGS = [] diff --git a/plugins/dumbloop/uwsgiplugin.py b/plugins/dumbloop/uwsgiplugin.py index 12bd06b3..72c81e4a 100644 --- a/plugins/dumbloop/uwsgiplugin.py +++ b/plugins/dumbloop/uwsgiplugin.py @@ -1,6 +1,6 @@ -NAME='dumbloop' +NAME = 'dumbloop' + CFLAGS = [] LDFLAGS = [] LIBS = [] - GCC_LIST = ['dumb'] diff --git a/plugins/dummy/uwsgiplugin.py b/plugins/dummy/uwsgiplugin.py index fb82e580..a00bfb75 100644 --- a/plugins/dummy/uwsgiplugin.py +++ b/plugins/dummy/uwsgiplugin.py @@ -1,7 +1,6 @@ +NAME = 'dummy' -NAME='dummy' CFLAGS = [] LDFLAGS = [] LIBS = [] - GCC_LIST = ['dummy'] diff --git a/plugins/echo/uwsgiplugin.py b/plugins/echo/uwsgiplugin.py index 9a65a439..8c967dba 100644 --- a/plugins/echo/uwsgiplugin.py +++ b/plugins/echo/uwsgiplugin.py @@ -1,4 +1,4 @@ -NAME='echo' +NAME = 'echo' CFLAGS = [] LDFLAGS = [] diff --git a/plugins/emperor_amqp/uwsgiplugin.py b/plugins/emperor_amqp/uwsgiplugin.py index f11cc69c..a79cf6fa 100644 --- a/plugins/emperor_amqp/uwsgiplugin.py +++ b/plugins/emperor_amqp/uwsgiplugin.py @@ -1,7 +1,7 @@ +NAME = 'emperor_amqp' -NAME='emperor_amqp' CFLAGS = [] LDFLAGS = [] LIBS = [] -GCC_LIST = ['amqp','emperor_amqp'] +GCC_LIST = ['amqp', 'emperor_amqp'] diff --git a/plugins/emperor_mongodb/uwsgiplugin.py b/plugins/emperor_mongodb/uwsgiplugin.py index 58b56757..2206fbc5 100644 --- a/plugins/emperor_mongodb/uwsgiplugin.py +++ b/plugins/emperor_mongodb/uwsgiplugin.py @@ -1,12 +1,15 @@ import os -NAME='emperor_mongodb' +NAME = 'emperor_mongodb' -CFLAGS = ['-I/usr/include/mongo','-I/usr/local/include/mongo'] +CFLAGS = [ + '-I/usr/include/mongo', + '-I/usr/local/include/mongo' +] LDFLAGS = [] LIBS = ['-lstdc++'] -if not 'UWSGI_MONGODB_NOLIB' in os.environ: +if 'UWSGI_MONGODB_NOLIB' not in os.environ: LIBS.append('-lmongoclient') LIBS.append('-lboost_thread') LIBS.append('-lboost_filesystem') diff --git a/plugins/emperor_pg/uwsgiplugin.py b/plugins/emperor_pg/uwsgiplugin.py index 6b8151bb..dd989e15 100644 --- a/plugins/emperor_pg/uwsgiplugin.py +++ b/plugins/emperor_pg/uwsgiplugin.py @@ -1,9 +1,13 @@ import os -NAME='emperor_pg' +NAME = 'emperor_pg' + CFLAGS = os.popen('pg_config --cflags').read().rstrip().split() CFLAGS.append('-I' + os.popen('pg_config --includedir').read().rstrip()) LDFLAGS = os.popen('pg_config --ldflags').read().rstrip().split() -LIBS = ['-L' + os.popen('pg_config --libdir').read().rstrip(), '-lpq'] +LIBS = [ + '-L' + os.popen('pg_config --libdir').read().rstrip(), + '-lpq' +] GCC_LIST = ['emperor_pg'] diff --git a/plugins/emperor_zeromq/uwsgiplugin.py b/plugins/emperor_zeromq/uwsgiplugin.py index f550d71d..6af2ce6d 100644 --- a/plugins/emperor_zeromq/uwsgiplugin.py +++ b/plugins/emperor_zeromq/uwsgiplugin.py @@ -1,5 +1,5 @@ +NAME = 'emperor_zeromq' -NAME='emperor_zeromq' CFLAGS = [] LDFLAGS = [] LIBS = ['-lzmq'] diff --git a/plugins/example/uwsgiplugin.py b/plugins/example/uwsgiplugin.py index 4074a00b..df46b7b4 100644 --- a/plugins/example/uwsgiplugin.py +++ b/plugins/example/uwsgiplugin.py @@ -1,4 +1,4 @@ -NAME='example' +NAME = 'example' CFLAGS = [] LDFLAGS = [] diff --git a/plugins/exception_log/uwsgiplugin.py b/plugins/exception_log/uwsgiplugin.py index 75e6c684..8dfc221e 100644 --- a/plugins/exception_log/uwsgiplugin.py +++ b/plugins/exception_log/uwsgiplugin.py @@ -1,4 +1,4 @@ -NAME='exception_log' +NAME = 'exception_log' CFLAGS = [] LDFLAGS = [] diff --git a/plugins/fastrouter/uwsgiplugin.py b/plugins/fastrouter/uwsgiplugin.py index 133452b2..ac254ae5 100644 --- a/plugins/fastrouter/uwsgiplugin.py +++ b/plugins/fastrouter/uwsgiplugin.py @@ -1,5 +1,5 @@ +NAME = 'fastrouter' -NAME='fastrouter' CFLAGS = [] LDFLAGS = [] LIBS = [] diff --git a/plugins/fiber/uwsgiplugin.py b/plugins/fiber/uwsgiplugin.py index ff0d4cb5..28c3a67e 100644 --- a/plugins/fiber/uwsgiplugin.py +++ b/plugins/fiber/uwsgiplugin.py @@ -1,6 +1,6 @@ import os -NAME='fiber' +NAME = 'fiber' try: RUBYPATH = os.environ['UWSGICONFIG_RUBYPATH'] diff --git a/plugins/forkptyrouter/uwsgiplugin.py b/plugins/forkptyrouter/uwsgiplugin.py index 0bc8af4b..cfe43235 100644 --- a/plugins/forkptyrouter/uwsgiplugin.py +++ b/plugins/forkptyrouter/uwsgiplugin.py @@ -1,7 +1,8 @@ import os uwsgi_os = os.uname()[0] -NAME='forkptyrouter' +NAME = 'forkptyrouter' + CFLAGS = [] LDFLAGS = [] if uwsgi_os in ('Linux', 'FreeBSD', 'GNU', 'NetBSD', 'DragonFly'): diff --git a/plugins/gccgo/uwsgiplugin.py b/plugins/gccgo/uwsgiplugin.py index 5b41b5dd..fee93647 100644 --- a/plugins/gccgo/uwsgiplugin.py +++ b/plugins/gccgo/uwsgiplugin.py @@ -1,11 +1,13 @@ import os -NAME='gccgo' + +NAME = 'gccgo' CFLAGS = ['-g'] LDFLAGS = [] LIBS = ['-lgo'] GCC_LIST = ['gccgo_plugin', 'uwsgi.go'] + def post_build(config): if os.path.exists('plugins/gccgo/uwsgi.go.o'): if os.system("objcopy -j .go_export plugins/gccgo/uwsgi.go.o plugins/gccgo/uwsgi.gox") != 0: diff --git a/plugins/geoip/uwsgiplugin.py b/plugins/geoip/uwsgiplugin.py index 8f5d4e9e..e74ca357 100644 --- a/plugins/geoip/uwsgiplugin.py +++ b/plugins/geoip/uwsgiplugin.py @@ -1,8 +1,7 @@ -NAME='geoip' +NAME = 'geoip' CFLAGS = [] LDFLAGS = [] LIBS = ['-lGeoIP'] GCC_LIST = ['geoip'] - diff --git a/plugins/gevent/uwsgiplugin.py b/plugins/gevent/uwsgiplugin.py index 155e2f23..4ff550a9 100644 --- a/plugins/gevent/uwsgiplugin.py +++ b/plugins/gevent/uwsgiplugin.py @@ -1,7 +1,11 @@ from distutils import sysconfig -NAME='gevent' -CFLAGS = ['-I' + sysconfig.get_python_inc(), '-I' + sysconfig.get_python_inc(plat_specific=True)] +NAME = 'gevent' + +CFLAGS = [ + '-I' + sysconfig.get_python_inc(), + '-I' + sysconfig.get_python_inc(plat_specific=True) +] LDFLAGS = [] LIBS = [] diff --git a/plugins/glusterfs/uwsgiplugin.py b/plugins/glusterfs/uwsgiplugin.py index b9fd924f..d5ea169d 100644 --- a/plugins/glusterfs/uwsgiplugin.py +++ b/plugins/glusterfs/uwsgiplugin.py @@ -1,7 +1,8 @@ import os -NAME='glusterfs' + +NAME = 'glusterfs' CFLAGS = os.popen('pkg-config --cflags glusterfs-api').read().rstrip().split() LDFLAGS = [] -LIBS = os.popen('pkg-config --libs glusterfs-api').read().rstrip().split() +LIBS = os.popen('pkg-config --libs glusterfs-api').read().rstrip().split() GCC_LIST = ['glusterfs'] diff --git a/plugins/graylog2/uwsgiplugin.py b/plugins/graylog2/uwsgiplugin.py index 4047a035..75512b80 100644 --- a/plugins/graylog2/uwsgiplugin.py +++ b/plugins/graylog2/uwsgiplugin.py @@ -1,4 +1,4 @@ -NAME='graylog2' +NAME = 'graylog2' CFLAGS = [] LDFLAGS = [] diff --git a/plugins/greenlet/uwsgiplugin.py b/plugins/greenlet/uwsgiplugin.py index 01fcefbc..27b1da12 100644 --- a/plugins/greenlet/uwsgiplugin.py +++ b/plugins/greenlet/uwsgiplugin.py @@ -1,7 +1,11 @@ from distutils import sysconfig -NAME='greenlet' -CFLAGS = ['-I' + sysconfig.get_python_inc(), '-I' + sysconfig.get_python_inc(plat_specific=True)] +NAME = 'greenlet' + +CFLAGS = [ + '-I' + sysconfig.get_python_inc(), + '-I' + sysconfig.get_python_inc(plat_specific=True) +] LDFLAGS = [] LIBS = [] diff --git a/plugins/gridfs/uwsgiplugin.py b/plugins/gridfs/uwsgiplugin.py index a2163d7f..a6b7f37d 100644 --- a/plugins/gridfs/uwsgiplugin.py +++ b/plugins/gridfs/uwsgiplugin.py @@ -1,12 +1,15 @@ import os -NAME='gridfs' +NAME = 'gridfs' -CFLAGS = ['-I/usr/include/mongo','-I/usr/local/include/mongo'] +CFLAGS = [ + '-I/usr/include/mongo', + '-I/usr/local/include/mongo' +] LDFLAGS = [] LIBS = [] -if not 'UWSGI_MONGODB_NOLIB' in os.environ: +if 'UWSGI_MONGODB_NOLIB' not in os.environ: LIBS.append('-lmongoclient') LIBS.append('-lstdc++') LIBS.append('-lboost_thread') diff --git a/plugins/http/uwsgiplugin.py b/plugins/http/uwsgiplugin.py index 91d0effb..da944846 100644 --- a/plugins/http/uwsgiplugin.py +++ b/plugins/http/uwsgiplugin.py @@ -1,5 +1,5 @@ +NAME = 'http' -NAME='http' CFLAGS = [] LDFLAGS = [] LIBS = [] diff --git a/plugins/jvm/uwsgiplugin.py b/plugins/jvm/uwsgiplugin.py index f39ad63d..80cafd91 100644 --- a/plugins/jvm/uwsgiplugin.py +++ b/plugins/jvm/uwsgiplugin.py @@ -1,7 +1,7 @@ import os import shutil -NAME='jvm' +NAME = 'jvm' JVM_INCPATH = None JVM_LIBPATH = None @@ -33,15 +33,15 @@ elif operating_system.startswith('cygwin'): else: known_jvms = ('/usr/lib/jvm/java-7-openjdk', '/usr/local/openjdk7', '/usr/lib/jvm/java-6-openjdk', '/usr/local/openjdk', '/usr/java', '/usr/lib/jvm/java/') for jvm in known_jvms: - if os.path.exists(jvm + '/include'): - JVM_INCPATH = ["-I%s/include/" % jvm, "-I%s/include/%s" % (jvm, operating_system)] - JVM_LIBPATH = ["-L%s/jre/lib/%s/server" % (jvm, arch)] - break - if os.path.exists("%s-%s/include" % (jvm, arch)): - jvm = "%s-%s" % (jvm, arch) - JVM_INCPATH = ["-I%s/include/" % jvm, "-I%s/include/%s" % (jvm, operating_system)] - JVM_LIBPATH = ["-L%s/jre/lib/%s/server" % (jvm, arch)] - break + if os.path.exists(jvm + '/include'): + JVM_INCPATH = ["-I%s/include/" % jvm, "-I%s/include/%s" % (jvm, operating_system)] + JVM_LIBPATH = ["-L%s/jre/lib/%s/server" % (jvm, arch)] + break + if os.path.exists("%s-%s/include" % (jvm, arch)): + jvm = "%s-%s" % (jvm, arch) + JVM_INCPATH = ["-I%s/include/" % jvm, "-I%s/include/%s" % (jvm, operating_system)] + JVM_LIBPATH = ["-L%s/jre/lib/%s/server" % (jvm, arch)] + break try: JVM_INCPATH = ['-I"' + os.environ['UWSGICONFIG_JVM_INCPATH'] + '"'] @@ -70,6 +70,7 @@ if 'LD_RUN_PATH' in os.environ: else: os.environ['LD_RUN_PATH'] = JVM_LIBPATH[0][2:] + def post_build(config): if os.system("javac %s/plugins/jvm/uwsgi.java" % os.getcwd()) != 0: os._exit(1) @@ -89,4 +90,3 @@ def post_build(config): tgt = "%s/bin/jvm_plugin.so" % env shutil.copyfile(plugin, tgt) print("*** jvm_plugin.so had been copied to %s" % tgt) - diff --git a/plugins/jwsgi/uwsgiplugin.py b/plugins/jwsgi/uwsgiplugin.py index af2aac6e..cbb29117 100644 --- a/plugins/jwsgi/uwsgiplugin.py +++ b/plugins/jwsgi/uwsgiplugin.py @@ -1,3 +1,5 @@ +NAME = 'jwsgi' + jvm_path = 'plugins/jvm' up = {} @@ -8,7 +10,6 @@ except: exec(f.read(), up) f.close() -NAME='jwsgi' CFLAGS = up['CFLAGS'] CFLAGS.append('-I%s' % jvm_path) LDFLAGS = [] diff --git a/plugins/ldap/uwsgiplugin.py b/plugins/ldap/uwsgiplugin.py index b44e6ad1..0f8b7ec5 100644 --- a/plugins/ldap/uwsgiplugin.py +++ b/plugins/ldap/uwsgiplugin.py @@ -1,5 +1,5 @@ +NAME = 'ldap' -NAME='ldap' CFLAGS = [] LDFLAGS = [] LIBS = ['-lldap'] diff --git a/plugins/legion_cache_fetch/uwsgiplugin.py b/plugins/legion_cache_fetch/uwsgiplugin.py index 27c53add..0983e430 100644 --- a/plugins/legion_cache_fetch/uwsgiplugin.py +++ b/plugins/legion_cache_fetch/uwsgiplugin.py @@ -1,8 +1,7 @@ - NAME = 'legion_cache_fetch' + CFLAGS = [] LDFLAGS = [] LIBS = [] GCC_LIST = ['legion_cache_fetch'] - diff --git a/plugins/libffi/uwsgiplugin.py b/plugins/libffi/uwsgiplugin.py index 32ae650b..f83e3905 100644 --- a/plugins/libffi/uwsgiplugin.py +++ b/plugins/libffi/uwsgiplugin.py @@ -1,5 +1,6 @@ -NAME='libffi' -CFLAGS=[] -LDFLAGS=[] -LIBS=['-lffi'] -GCC_LIST=['libffi'] +NAME = 'libffi' + +CFLAGS = [] +LDFLAGS = [] +LIBS = ['-lffi'] +GCC_LIST = ['libffi'] diff --git a/plugins/libtcc/uwsgiplugin.py b/plugins/libtcc/uwsgiplugin.py index d89627b4..1f6ec332 100644 --- a/plugins/libtcc/uwsgiplugin.py +++ b/plugins/libtcc/uwsgiplugin.py @@ -1,5 +1,6 @@ -NAME='libtcc' -CFLAGS=[] -LDFLAGS=[] -LIBS=['-ltcc'] -GCC_LIST=['libtcc'] +NAME = 'libtcc' + +CFLAGS = [] +LDFLAGS = [] +LIBS = ['-ltcc'] +GCC_LIST = ['libtcc'] diff --git a/plugins/logcrypto/uwsgiplugin.py b/plugins/logcrypto/uwsgiplugin.py index 601c43f8..26cbbadb 100644 --- a/plugins/logcrypto/uwsgiplugin.py +++ b/plugins/logcrypto/uwsgiplugin.py @@ -1,4 +1,4 @@ -NAME='logcrypto' +NAME = 'logcrypto' CFLAGS = [] LDFLAGS = [] diff --git a/plugins/logfile/uwsgiplugin.py b/plugins/logfile/uwsgiplugin.py index dd504017..63480601 100644 --- a/plugins/logfile/uwsgiplugin.py +++ b/plugins/logfile/uwsgiplugin.py @@ -1,4 +1,4 @@ -NAME='logfile' +NAME = 'logfile' CFLAGS = [] LDFLAGS = [] diff --git a/plugins/logpipe/uwsgiplugin.py b/plugins/logpipe/uwsgiplugin.py index b87f3f76..40c2c464 100644 --- a/plugins/logpipe/uwsgiplugin.py +++ b/plugins/logpipe/uwsgiplugin.py @@ -1,4 +1,4 @@ -NAME='logpipe' +NAME = 'logpipe' CFLAGS = [] LDFLAGS = [] diff --git a/plugins/logsocket/uwsgiplugin.py b/plugins/logsocket/uwsgiplugin.py index d2e3337d..9a5a6797 100644 --- a/plugins/logsocket/uwsgiplugin.py +++ b/plugins/logsocket/uwsgiplugin.py @@ -1,4 +1,4 @@ -NAME='logsocket' +NAME = 'logsocket' CFLAGS = [] LDFLAGS = [] diff --git a/plugins/logzmq/uwsgiplugin.py b/plugins/logzmq/uwsgiplugin.py index 0799e325..949cf286 100644 --- a/plugins/logzmq/uwsgiplugin.py +++ b/plugins/logzmq/uwsgiplugin.py @@ -1,5 +1,5 @@ +NAME = 'logzmq' -NAME='logzmq' CFLAGS = [] LDFLAGS = [] LIBS = ['-lzmq'] diff --git a/plugins/lua/uwsgiplugin.py b/plugins/lua/uwsgiplugin.py index 8aaa95b6..f9074d80 100644 --- a/plugins/lua/uwsgiplugin.py +++ b/plugins/lua/uwsgiplugin.py @@ -1,4 +1,6 @@ -import os,sys +import os + +NAME = 'lua' LUAINC = os.environ.get('UWSGICONFIG_LUAINC') LUALIB = os.environ.get('UWSGICONFIG_LUALIB') @@ -7,27 +9,24 @@ LUAPC = os.environ.get('UWSGICONFIG_LUAPC', 'lua5.1') # we LUAINC/LUALIB/LUALIBPATH override the LUAPC for backwards compat if LUAINC: - CFLAGS = ['-I%s' % LUAINC] + CFLAGS = ['-I%s' % LUAINC] else: - try: - CFLAGS = os.popen('pkg-config --cflags %s' % LUAPC).read().rstrip().split() - except: - CFLAGS = ['-I/usr/include/lua5.1'] + try: + CFLAGS = os.popen('pkg-config --cflags %s' % LUAPC).read().rstrip().split() + except: + CFLAGS = ['-I/usr/include/lua5.1'] if LUALIB: - LIBS = ['-l%s' % LUALIB] + LIBS = ['-l%s' % LUALIB] else: - try: - LIBS = os.popen('pkg-config --libs %s' % LUAPC).read().rstrip().split() - except: - LIBS = ['-llua5.1'] + try: + LIBS = os.popen('pkg-config --libs %s' % LUAPC).read().rstrip().split() + except: + LIBS = ['-llua5.1'] if LUALIBPATH: - LDFLAGS = ['-L%s' % LUALIBPATH] + LDFLAGS = ['-L%s' % LUALIBPATH] else: - LDFLAGS = [] + LDFLAGS = [] -NAME='lua' GCC_LIST = ['lua_plugin'] - - diff --git a/plugins/matheval/uwsgiplugin.py b/plugins/matheval/uwsgiplugin.py index f5c66adf..12539a31 100644 --- a/plugins/matheval/uwsgiplugin.py +++ b/plugins/matheval/uwsgiplugin.py @@ -1,4 +1,4 @@ -NAME='matheval' +NAME = 'matheval' CFLAGS = [] LDFLAGS = [] diff --git a/plugins/mongodb/uwsgiplugin.py b/plugins/mongodb/uwsgiplugin.py index 2a55f732..02ae00c1 100644 --- a/plugins/mongodb/uwsgiplugin.py +++ b/plugins/mongodb/uwsgiplugin.py @@ -1,8 +1,13 @@ -NAME='mongodb' +NAME = 'mongodb' CFLAGS = [] LDFLAGS = [] -LIBS = ['-Wl,-whole-archive', '-lmongoclient', '-Wl,-no-whole-archive', '-lboost_thread', '-lboost_system', '-lboost_filesystem'] - +LIBS = [ + '-Wl,-whole-archive', + '-lmongoclient', + '-Wl,-no-whole-archive', + '-lboost_thread', + '-lboost_system', + '-lboost_filesystem' +] GCC_LIST = ['plugin'] - diff --git a/plugins/mongodblog/uwsgiplugin.py b/plugins/mongodblog/uwsgiplugin.py index a3884bb9..b1f4328b 100644 --- a/plugins/mongodblog/uwsgiplugin.py +++ b/plugins/mongodblog/uwsgiplugin.py @@ -1,4 +1,4 @@ -NAME='mongodblog' +NAME = 'mongodblog' CFLAGS = [] LDFLAGS = [] diff --git a/plugins/mongrel2/uwsgiplugin.py b/plugins/mongrel2/uwsgiplugin.py index 723885cf..c9e7afc7 100644 --- a/plugins/mongrel2/uwsgiplugin.py +++ b/plugins/mongrel2/uwsgiplugin.py @@ -1,5 +1,5 @@ +NAME = 'mongrel2' -NAME='mongrel2' CFLAGS = [] LDFLAGS = [] LIBS = ['-lzmq'] diff --git a/plugins/mono/uwsgiplugin.py b/plugins/mono/uwsgiplugin.py index 4d17a48d..348abf06 100644 --- a/plugins/mono/uwsgiplugin.py +++ b/plugins/mono/uwsgiplugin.py @@ -1,14 +1,16 @@ import os -NAME='mono' + +NAME = 'mono' CFLAGS = os.popen('pkg-config --cflags mono-2').read().rstrip().split() LDFLAGS = [] -LIBS = os.popen('pkg-config --libs mono-2').read().rstrip().split() +LIBS = os.popen('pkg-config --libs mono-2').read().rstrip().split() GCC_LIST = ['mono_plugin'] if os.uname()[0] == 'Darwin': LIBS.append('-framework Foundation') + def post_build(config): if os.system("sn -k plugins/mono/uwsgi.key") != 0: os._exit(1) diff --git a/plugins/msgpack/uwsgiplugin.py b/plugins/msgpack/uwsgiplugin.py index 4473a4f9..0421f334 100644 --- a/plugins/msgpack/uwsgiplugin.py +++ b/plugins/msgpack/uwsgiplugin.py @@ -1,5 +1,5 @@ -NAME='msgpack' -CFLAGS=[] -LDFLAGS=[] -LIBS=[] +NAME = 'msgpack' +CFLAGS = [] +LDFLAGS = [] +LIBS = [] GCC_LIST = ['msgpack'] diff --git a/plugins/nagios/uwsgiplugin.py b/plugins/nagios/uwsgiplugin.py index 4afbc3fa..6c0806ad 100644 --- a/plugins/nagios/uwsgiplugin.py +++ b/plugins/nagios/uwsgiplugin.py @@ -1,5 +1,5 @@ +NAME = 'nagios' -NAME='nagios' CFLAGS = [] LDFLAGS = [] LIBS = [] diff --git a/plugins/notfound/uwsgiplugin.py b/plugins/notfound/uwsgiplugin.py index 31666edd..ecdb3b06 100644 --- a/plugins/notfound/uwsgiplugin.py +++ b/plugins/notfound/uwsgiplugin.py @@ -1,4 +1,4 @@ -NAME='notfound' +NAME = 'notfound' CFLAGS = [] LDFLAGS = [] diff --git a/plugins/objc_gc/uwsgiplugin.py b/plugins/objc_gc/uwsgiplugin.py index b2e57eb6..1a1b0c8c 100644 --- a/plugins/objc_gc/uwsgiplugin.py +++ b/plugins/objc_gc/uwsgiplugin.py @@ -1,5 +1,5 @@ -NAME="objc_gc" -CFLAGS=["-fobjc-gc"] -LDFLAGS=[] -LIBS=[] -GCC_LIST=['objc_gc.m'] +NAME = "objc_gc" +CFLAGS = ["-fobjc-gc"] +LDFLAGS = [] +LIBS = [] +GCC_LIST = ['objc_gc.m'] diff --git a/plugins/pam/uwsgiplugin.py b/plugins/pam/uwsgiplugin.py index cf1f7269..e03f6fc6 100644 --- a/plugins/pam/uwsgiplugin.py +++ b/plugins/pam/uwsgiplugin.py @@ -1,4 +1,4 @@ -NAME='pam' +NAME = 'pam' CFLAGS = [] LDFLAGS = [] diff --git a/plugins/php/uwsgiplugin.py b/plugins/php/uwsgiplugin.py index e7ce425f..2f2becdd 100644 --- a/plugins/php/uwsgiplugin.py +++ b/plugins/php/uwsgiplugin.py @@ -1,6 +1,6 @@ import os -NAME='php' +NAME = 'php' ld_run_path = None PHPPATH = 'php-config' diff --git a/plugins/ping/uwsgiplugin.py b/plugins/ping/uwsgiplugin.py index eb589c96..8332d624 100644 --- a/plugins/ping/uwsgiplugin.py +++ b/plugins/ping/uwsgiplugin.py @@ -1,4 +1,5 @@ -NAME='ping' +NAME = 'ping' + CFLAGS = [] LDFLAGS = [] LIBS = [] diff --git a/plugins/psgi/uwsgiplugin.py b/plugins/psgi/uwsgiplugin.py index ec7e3469..a400b246 100644 --- a/plugins/psgi/uwsgiplugin.py +++ b/plugins/psgi/uwsgiplugin.py @@ -1,6 +1,6 @@ -import os,sys +import os -NAME='psgi' +NAME = 'psgi' CFLAGS = os.popen('perl -MExtUtils::Embed -e ccopts').read().rstrip().split() LDFLAGS = os.popen('perl -MExtUtils::Embed -e ldopts').read().rstrip().split() LIBS = [] diff --git a/plugins/pty/uwsgiplugin.py b/plugins/pty/uwsgiplugin.py index dbc2b23f..9c150b27 100644 --- a/plugins/pty/uwsgiplugin.py +++ b/plugins/pty/uwsgiplugin.py @@ -1,6 +1,7 @@ -NAME='pty' - import os + +NAME = 'pty' + uwsgi_os = os.uname()[0] CFLAGS = [] diff --git a/plugins/pypy/pypy_setup.py b/plugins/pypy/pypy_setup.py index 67533ddc..ebb108b0 100644 --- a/plugins/pypy/pypy_setup.py +++ b/plugins/pypy/pypy_setup.py @@ -1,7 +1,7 @@ import sys import os sys.path.insert(0, '.') -sys.path.extend(os.environ.get('PYTHONPATH','').split(os.pathsep)) +sys.path.extend(os.environ.get('PYTHONPATH', '').split(os.pathsep)) import imp import traceback @@ -53,10 +53,10 @@ for cflag in uwsgi_cflags: if '=' in line: (key, value) = line.split('=', 1) uwsgi_cdef.append('#define %s ...' % key) - uwsgi_defines.append('#define %s %s' % (key, value.replace('\\"','"').replace('""','"'))) + uwsgi_defines.append('#define %s %s' % (key, value.replace('\\"', '"').replace('""', '"'))) else: uwsgi_cdef.append('#define %s ...' % line) - uwsgi_defines.append('#define %s 1' % line) + uwsgi_defines.append('#define %s 1' % line) uwsgi_dot_h = ffi.string(lib0.uwsgi_get_dot_h()) # uwsgi definitions @@ -64,107 +64,107 @@ cdefines = ''' %s struct iovec { - void *iov_base; - size_t iov_len; - ...; + void *iov_base; + size_t iov_len; + ...; }; struct uwsgi_header { - uint8_t modifier1; - ...; + uint8_t modifier1; + ...; }; struct wsgi_request { - int fd; - int async_id; - uint16_t var_cnt; - struct iovec *hvec; + int fd; + int async_id; + uint16_t var_cnt; + struct iovec *hvec; - int async_ready_fd; - int async_last_ready_fd; + int async_ready_fd; + int async_last_ready_fd; - int suspended; + int suspended; - struct uwsgi_header *uh; - ...; + struct uwsgi_header *uh; + ...; }; struct uwsgi_opt { - char *key; - char *value; - ...; + char *key; + char *value; + ...; }; struct uwsgi_worker { - int id; - int pid; - uint64_t requests; - uint64_t delta_requests; - uint64_t signals; + int id; + int pid; + uint64_t requests; + uint64_t delta_requests; + uint64_t signals; - int cheaped; - int suspended; - int sig; - uint8_t signum; + int cheaped; + int suspended; + int sig; + uint8_t signum; - uint64_t running_time; - uint64_t avg_response_time; - uint64_t tx; - ...; + uint64_t running_time; + uint64_t avg_response_time; + uint64_t tx; + ...; }; struct uwsgi_plugin { - uint8_t modifier1; + uint8_t modifier1; - void (*suspend) (struct wsgi_request *); + void (*suspend) (struct wsgi_request *); void (*resume) (struct wsgi_request *); - ...; + ...; }; struct uwsgi_buffer { - char *buf; - size_t pos; - ...; + char *buf; + size_t pos; + ...; }; struct uwsgi_lock_item { - ...; + ...; }; struct uwsgi_cache { - struct uwsgi_lock_item *lock; - ...; + struct uwsgi_lock_item *lock; + ...; }; struct uwsgi_cache_item { - uint64_t keysize; - ...; + uint64_t keysize; + ...; }; struct uwsgi_server { - char hostname[]; - int mywid; - int muleid; - int master_process; + char hostname[]; + int mywid; + int muleid; + int master_process; - struct uwsgi_opt **exported_opts; - int exported_opts_cnt; + struct uwsgi_opt **exported_opts; + int exported_opts_cnt; - struct uwsgi_worker *workers; + struct uwsgi_worker *workers; - int signal_socket; - int numproc; - int async; + int signal_socket; + int numproc; + int async; - void (*schedule_to_main) (struct wsgi_request *); + void (*schedule_to_main) (struct wsgi_request *); void (*schedule_to_req) (void); - struct wsgi_request *(*current_wsgi_req) (void); - - struct wsgi_request *wsgi_req; + struct wsgi_request *(*current_wsgi_req) (void); - struct uwsgi_plugin *p[]; - ...; + struct wsgi_request *wsgi_req; + + struct uwsgi_plugin *p[]; + ...; }; struct uwsgi_server uwsgi; @@ -267,7 +267,6 @@ lib = ffi.verify(cverify) libc = ffi.dlopen(None) - """ this is a global object point the the WSGI callable it sucks, i will fix it in the near future... @@ -278,20 +277,22 @@ wsgi_application = None if len(sys.argv) == 0: sys.argv.insert(0, ffi.string(lib.uwsgi_binary_path())) -""" -execute source, we expose it as cffi callback to avoid deadlocks -after GIL initialization -""" + @ffi.callback("void(char *)") def uwsgi_pypy_execute_source(s): + """ + execute source, we expose it as cffi callback to avoid deadlocks + after GIL initialization + """ source = ffi.string(s) exec(source) -""" -load a wsgi module -""" + @ffi.callback("void(char *)") def uwsgi_pypy_loader(module): + """ + load a wsgi module + """ global wsgi_application m = ffi.string(module) c = 'application' @@ -303,22 +304,24 @@ def uwsgi_pypy_loader(module): mod = __import__(m) wsgi_application = getattr(mod, c) -""" -load a mod_wsgi compliant .wsgi file -""" + @ffi.callback("void(char *)") def uwsgi_pypy_file_loader(filename): + """ + load a mod_wsgi compliant .wsgi file + """ global wsgi_application w = ffi.string(filename) c = 'application' mod = imp.load_source('uwsgi_file_wsgi', w) wsgi_application = getattr(mod, c) -""" -load a .ini paste app -""" + @ffi.callback("void(char *)") def uwsgi_pypy_paste_loader(config): + """ + load a .ini paste app + """ global wsgi_application c = ffi.string(config) if c.startswith('config:'): @@ -333,29 +336,31 @@ def uwsgi_pypy_paste_loader(config): from paste.deploy import loadapp wsgi_application = loadapp('config:%s' % c) -""" -.post_fork_hook -""" + @ffi.callback("void()") def uwsgi_pypy_post_fork_hook(): + """ + .post_fork_hook + """ import uwsgi if hasattr(uwsgi, 'post_fork_hook'): uwsgi.post_fork_hook() -""" -add an item to the pythonpath -""" + @ffi.callback("void(char *)") def uwsgi_pypy_pythonpath(item): + """ + add an item to the pythonpath + """ path = ffi.string(item) sys.path.append(path) print "added %s to pythonpath" % path -""" -class implementing wsgi.file_wrapper -""" class WSGIfilewrapper(object): + """ + class implementing wsgi.file_wrapper + """ def __init__(self, wsgi_req, f, chunksize=0): self.wsgi_req = wsgi_req self.f = f @@ -382,10 +387,10 @@ class WSGIfilewrapper(object): lib.uwsgi_response_write_body_do(self.wsgi_req, ffi.new("char[]", chunk), len(chunk)) -""" -class implementing wsgi.input -""" class WSGIinput(object): + """ + class implementing wsgi.input + """ def __init__(self, wsgi_req): self.wsgi_req = wsgi_req @@ -429,11 +434,11 @@ class WSGIinput(object): return chunk -""" -the WSGI request handler -""" @ffi.callback("void(struct wsgi_request *)") def uwsgi_pypy_wsgi_handler(wsgi_req): + """ + the WSGI request handler + """ import uwsgi global wsgi_application @@ -506,6 +511,7 @@ sys.modules['uwsgi'] = uwsgi uwsgi.version = ffi.string(lib.uwsgi_pypy_version) uwsgi.hostname = ffi.string(lib.uwsgi.hostname) + def uwsgi_pypy_uwsgi_register_signal(signum, kind, handler): cb = ffi.callback('void(int)', handler) uwsgi_gc.append(cb) @@ -538,6 +544,7 @@ def uwsgi_pypy_uwsgi_register_rpc(name, func, argc=0): raise Exception("unable to register rpc func %s" % name) uwsgi.register_rpc = uwsgi_pypy_uwsgi_register_rpc + def uwsgi_pypy_rpc(node, func, *args): argc = 0 argv = ffi.new('char*[256]') @@ -558,7 +565,7 @@ def uwsgi_pypy_rpc(node, func, *args): else: c_node = ffi.NULL - response = lib.uwsgi_do_rpc(c_node, ffi.new("char[]",func), argc, argv, argvs, rsize) + response = lib.uwsgi_do_rpc(c_node, ffi.new("char[]", func), argc, argv, argvs, rsize) if response: ret = ffi.string(response, rsize[0]) lib.free(response) @@ -566,13 +573,14 @@ def uwsgi_pypy_rpc(node, func, *args): return None uwsgi.rpc = uwsgi_pypy_rpc + def uwsgi_pypy_call(func, *args): node = None if '@' in func: (func, node) = func.split('@') return uwsgi_pypy_rpc(node, func, *args) uwsgi.call = uwsgi_pypy_call - + uwsgi.signal = lambda x: lib.uwsgi_signal_send(lib.uwsgi.signal_socket, x) uwsgi.metric_get = lambda x: lib.uwsgi_metric_get(x, ffi.NULL) @@ -582,6 +590,7 @@ uwsgi.metric_dec = lambda x, y=1: lib.uwsgi_metric_dec(x, ffi.NULL, y) uwsgi.metric_mul = lambda x, y=1: lib.uwsgi_metric_mul(x, ffi.NULL, y) uwsgi.metric_div = lambda x, y=1: lib.uwsgi_metric_div(x, ffi.NULL, y) + def uwsgi_pypy_uwsgi_cache_get(key, cache=ffi.NULL): vallen = ffi.new('uint64_t*') value = lib.uwsgi_cache_magic_get(key, len(key), vallen, ffi.NULL, cache) @@ -592,21 +601,25 @@ def uwsgi_pypy_uwsgi_cache_get(key, cache=ffi.NULL): return ret uwsgi.cache_get = uwsgi_pypy_uwsgi_cache_get + def uwsgi_pypy_uwsgi_cache_set(key, value, expires=0, cache=ffi.NULL): if lib.uwsgi_cache_magic_set(key, len(key), value, len(value), expires, 0, cache) < 0: raise Exception('unable to store item in the cache') uwsgi.cache_set = uwsgi_pypy_uwsgi_cache_set + def uwsgi_pypy_uwsgi_cache_update(key, value, expires=0, cache=ffi.NULL): if lib.uwsgi_cache_magic_set(key, len(key), value, len(value), expires, 1 << 1, cache) < 0: raise Exception('unable to store item in the cache') uwsgi.cache_update = uwsgi_pypy_uwsgi_cache_update + def uwsgi_pypy_uwsgi_cache_del(key, cache=ffi.NULL): if lib.uwsgi_cache_magic_del(key, len(key), cache) < 0: raise Exception('unable to delete item from the cache') uwsgi.cache_del = uwsgi_pypy_uwsgi_cache_del + def uwsgi_pypy_uwsgi_cache_keys(cache=ffi.NULL): uc = lib.uwsgi_cache_by_name(cache) if uc == ffi.NULL: @@ -617,17 +630,20 @@ def uwsgi_pypy_uwsgi_cache_keys(cache=ffi.NULL): uci = ffi.new('struct uwsgi_cache_item **') while True: uci[0] = lib.uwsgi_cache_keys(uc, pos, uci) - if uci[0] == ffi.NULL: break + if uci[0] == ffi.NULL: + break l.append(ffi.string(lib.uwsgi_cache_item_key(uci[0]), uci[0].keysize)) lib.uwsgi_cache_rwunlock(uc) return l uwsgi.cache_keys = uwsgi_pypy_uwsgi_cache_keys + def uwsgi_pypy_uwsgi_add_timer(signum, secs): if lib.uwsgi_add_timer(signum, secs) < 0: raise Exception("unable to register timer") uwsgi.add_timer = uwsgi_pypy_uwsgi_add_timer + def uwsgi_pypy_uwsgi_add_rb_timer(signum, secs): if lib.uwsgi_signal_add_rb_timer(signum, secs, 0) < 0: raise Exception("unable to register redblack timer") @@ -639,16 +655,19 @@ def uwsgi_pypy_uwsgi_add_file_monitor(signum, filename): raise Exception("unable to register file monitor") uwsgi.add_file_monitor = uwsgi_pypy_uwsgi_add_file_monitor + def uwsgi_pypy_lock(num=0): if lib.uwsgi_user_lock(num) < 0: raise Exception("invalid lock") uwsgi.lock = uwsgi_pypy_lock + def uwsgi_pypy_unlock(num=0): if lib.uwsgi_user_unlock(num) < 0: raise Exception("invalid lock") uwsgi.unlock = uwsgi_pypy_unlock + def uwsgi_pypy_masterpid(): if lib.uwsgi.master_process: return lib.uwsgi.workers[0].pid @@ -659,18 +678,21 @@ uwsgi.worker_id = lambda: lib.uwsgi.mywid uwsgi.mule_id = lambda: lib.uwsgi.muleid + def uwsgi_pypy_signal_registered(signum): if lib.uwsgi_signal_registered(signum) > 0: return True return False uwsgi.signal_registered = uwsgi_pypy_signal_registered + def uwsgi_pypy_alarm(alarm, msg): lib.uwsgi_alarm_trigger(ffi.new('char[]', alarm), ffi.new('char[]', msg), len(msg)) uwsgi.alarm = uwsgi_pypy_alarm uwsgi.setprocname = lambda name: lib.uwsgi_set_processname(ffi.new('char[]', name)) + def uwsgi_pypy_add_cron(signum, minute, hour, day, month, week): if lib.uwsgi_signal_add_cron(signum, minute, hour, day, month, week) < 0: raise Exception("unable to register cron") @@ -695,25 +717,28 @@ for i in range(0, lib.uwsgi.exported_opts_cnt): else: uwsgi.opt[k] = v + def uwsgi_pypy_current_wsgi_req(): wsgi_req = lib.uwsgi.current_wsgi_req() if wsgi_req == ffi.NULL: raise Exception("unable to get current wsgi_request, check your setup !!!") return wsgi_req -""" -uwsgi.suspend() -""" + def uwsgi_pypy_suspend(): + """ + uwsgi.suspend() + """ wsgi_req = uwsgi_pypy_current_wsgi_req() if lib.uwsgi.schedule_to_main: - lib.uwsgi.schedule_to_main(wsgi_req); + lib.uwsgi.schedule_to_main(wsgi_req) uwsgi.suspend = uwsgi_pypy_suspend -""" -uwsgi.workers() -""" + def uwsgi_pypy_workers(): + """ + uwsgi.workers() + """ workers = [] for i in range(1, lib.uwsgi.numproc+1): worker = {} @@ -722,7 +747,7 @@ def uwsgi_pypy_workers(): worker['requests'] = lib.uwsgi.workers[i].requests worker['delta_requests'] = lib.uwsgi.workers[i].delta_requests worker['signals'] = lib.uwsgi.workers[i].signals - worker['exceptions'] = lib.uwsgi_worker_exceptions(i); + worker['exceptions'] = lib.uwsgi_worker_exceptions(i) worker['apps'] = [] if lib.uwsgi.workers[i].cheaped: worker['status'] == 'cheap' @@ -732,31 +757,33 @@ def uwsgi_pypy_workers(): if lib.uwsgi.workers[i].sig: worker['status'] = 'sig%d' % lib.uwsgi.workers[i].signum elif lib.uwsgi_worker_is_busy(i): - worker['status'] = 'busy' + worker['status'] = 'busy' else: worker['status'] = 'idle' worker['running_time'] = lib.uwsgi.workers[i].running_time worker['avg_rt'] = lib.uwsgi.workers[i].avg_response_time worker['tx'] = lib.uwsgi.workers[i].tx - + workers.append(worker) return workers - + uwsgi.workers = uwsgi_pypy_workers -""" -uwsgi.async_sleep(timeout) -""" + def uwsgi_pypy_async_sleep(timeout): + """ + uwsgi.async_sleep(timeout) + """ if timeout > 0: - wsgi_req = uwsgi_pypy_current_wsgi_req(); - lib.async_add_timeout(wsgi_req, timeout); + wsgi_req = uwsgi_pypy_current_wsgi_req() + lib.async_add_timeout(wsgi_req, timeout) uwsgi.async_sleep = uwsgi_pypy_async_sleep -""" -uwsgi.async_connect(addr) -""" + def uwsgi_pypy_async_connect(addr): + """ + uwsgi.async_connect(addr) + """ fd = lib.uwsgi_connect(ffi.new('char[]', addr), 0, 1) if fd < 0: raise Exception("unable to connect to %s" % addr) @@ -765,41 +792,44 @@ uwsgi.async_connect = uwsgi_pypy_async_connect uwsgi.connection_fd = lambda: uwsgi_pypy_current_wsgi_req().fd -""" -uwsgi.wait_fd_read(fd, timeout=0) -""" + def uwsgi_pypy_wait_fd_read(fd, timeout=0): - wsgi_req = uwsgi_pypy_current_wsgi_req(); + """ + uwsgi.wait_fd_read(fd, timeout=0) + """ + wsgi_req = uwsgi_pypy_current_wsgi_req() if lib.async_add_fd_read(wsgi_req, fd, timeout) < 0: raise Exception("unable to add fd %d to the event queue" % fd) uwsgi.wait_fd_read = uwsgi_pypy_wait_fd_read -""" -uwsgi.wait_fd_write(fd, timeout=0) -""" + def uwsgi_pypy_wait_fd_write(fd, timeout=0): - wsgi_req = uwsgi_pypy_current_wsgi_req(); + """ + uwsgi.wait_fd_write(fd, timeout=0) + """ + wsgi_req = uwsgi_pypy_current_wsgi_req() if lib.async_add_fd_write(wsgi_req, fd, timeout) < 0: raise Exception("unable to add fd %d to the event queue" % fd) uwsgi.wait_fd_write = uwsgi_pypy_wait_fd_write -""" -uwsgi.ready_fd() -""" + def uwsgi_pypy_ready_fd(): - wsgi_req = uwsgi_pypy_current_wsgi_req(); + """ + uwsgi.ready_fd() + """ + wsgi_req = uwsgi_pypy_current_wsgi_req() return lib.uwsgi_ready_fd(wsgi_req) uwsgi.ready_fd = uwsgi_pypy_ready_fd - -""" -uwsgi.send(fd=None,data) -""" + def uwsgi_pypy_send(*args): + """ + uwsgi.send(fd=None,data) + """ if len(args) == 0: raise ValueError("uwsgi.send() takes at least 1 argument") elif len(args) == 1: - wsgi_req = uwsgi_pypy_current_wsgi_req(); + wsgi_req = uwsgi_pypy_current_wsgi_req() fd = wsgi_req.fd data = args[0] else: @@ -811,14 +841,15 @@ def uwsgi_pypy_send(*args): return rlen uwsgi.send = uwsgi_pypy_send -""" -uwsgi.recv(fd=None,len) -""" + def uwsgi_pypy_recv(*args): + """ + uwsgi.recv(fd=None,len) + """ if len(args) == 0: raise ValueError("uwsgi.recv() takes at least 1 argument") elif len(args) == 1: - wsgi_req = uwsgi_pypy_current_wsgi_req(); + wsgi_req = uwsgi_pypy_current_wsgi_req() fd = wsgi_req.fd l = args[0] else: @@ -830,7 +861,7 @@ def uwsgi_pypy_recv(*args): raise IOError("unable to receive data") return ffi.string(data[0:rlen]) uwsgi.recv = uwsgi_pypy_recv - + """ uwsgi.close(fd) """ @@ -841,12 +872,13 @@ uwsgi.disconnect() """ uwsgi.disconnect = lambda: lib.uwsgi_disconnect(uwsgi_pypy_current_wsgi_req()) -""" -uwsgi.websocket_recv() -""" + def uwsgi_pypy_websocket_recv(): - wsgi_req = uwsgi_pypy_current_wsgi_req(); - ub = lib.uwsgi_websocket_recv(wsgi_req); + """ + uwsgi.websocket_recv() + """ + wsgi_req = uwsgi_pypy_current_wsgi_req() + ub = lib.uwsgi_websocket_recv(wsgi_req) if ub == ffi.NULL: raise IOError("unable to receive websocket message") ret = ffi.string(ub.buf, ub.pos) @@ -854,12 +886,13 @@ def uwsgi_pypy_websocket_recv(): return ret uwsgi.websocket_recv = uwsgi_pypy_websocket_recv -""" -uwsgi.websocket_recv_nb() -""" + def uwsgi_pypy_websocket_recv_nb(): - wsgi_req = uwsgi_pypy_current_wsgi_req(); - ub = lib.uwsgi_websocket_recv_nb(wsgi_req); + """ + uwsgi.websocket_recv_nb() + """ + wsgi_req = uwsgi_pypy_current_wsgi_req() + ub = lib.uwsgi_websocket_recv_nb(wsgi_req) if ub == ffi.NULL: raise IOError("unable to receive websocket message") ret = ffi.string(ub.buf, ub.pos) @@ -867,11 +900,12 @@ def uwsgi_pypy_websocket_recv_nb(): return ret uwsgi.websocket_recv_nb = uwsgi_pypy_websocket_recv_nb -""" -uwsgi.websocket_handshake(key, origin) -""" + def uwsgi_pypy_websocket_handshake(key='', origin='', proto=''): - wsgi_req = uwsgi_pypy_current_wsgi_req(); + """ + uwsgi.websocket_handshake(key, origin) + """ + wsgi_req = uwsgi_pypy_current_wsgi_req() c_key = ffi.new('char[]', key) c_origin = ffi.new('char[]', origin) c_proto = ffi.new('char[]', proto) @@ -879,20 +913,22 @@ def uwsgi_pypy_websocket_handshake(key='', origin='', proto=''): raise IOError("unable to complete websocket handshake") uwsgi.websocket_handshake = uwsgi_pypy_websocket_handshake -""" -uwsgi.websocket_send(msg) -""" + def uwsgi_pypy_websocket_send(msg): - wsgi_req = uwsgi_pypy_current_wsgi_req(); + """ + uwsgi.websocket_send(msg) + """ + wsgi_req = uwsgi_pypy_current_wsgi_req() if lib.uwsgi_websocket_send(wsgi_req, ffi.new('char[]', msg), len(msg)) < 0: raise IOError("unable to send websocket message") uwsgi.websocket_send = uwsgi_pypy_websocket_send -""" -uwsgi.chunked_read(timeout=0) -""" + def uwsgi_pypy_chunked_read(timeout=0): - wsgi_req = uwsgi_pypy_current_wsgi_req(); + """ + uwsgi.chunked_read(timeout=0) + """ + wsgi_req = uwsgi_pypy_current_wsgi_req() rlen = ffi.new("size_t*") chunk = lib.uwsgi_chunked_read(wsgi_req, rlen, timeout, 0) if chunk == ffi.NULL: @@ -900,25 +936,27 @@ def uwsgi_pypy_chunked_read(timeout=0): return ffi.string(chunk, rlen[0]) uwsgi.chunked_read = uwsgi_pypy_chunked_read -""" -uwsgi.chunked_read_nb() -""" + def uwsgi_pypy_chunked_read_nb(): - wsgi_req = uwsgi_pypy_current_wsgi_req(); + """ + uwsgi.chunked_read_nb() + """ + wsgi_req = uwsgi_pypy_current_wsgi_req() rlen = ffi.new("size_t*") chunk = lib.uwsgi_chunked_read(wsgi_req, rlen, 0, 1) if chunk == ffi.NULL: if lib.uwsgi_is_again() > 0: return None raise IOError("unable to receive chunked part") - + return ffi.string(chunk, rlen[0]) uwsgi.chunked_read_nb = uwsgi_pypy_chunked_read_nb -""" -uwsgi.set_user_harakiri(sec) -""" + def uwsgi_pypy_set_user_harakiri(x): + """ + uwsgi.set_user_harakiri(sec) + """ wsgi_req = uwsgi_pypy_current_wsgi_req() lib.set_user_harakiri(wsgi_req, x) uwsgi.set_user_harakiri = uwsgi_pypy_set_user_harakiri @@ -939,10 +977,11 @@ uwsgi_pypy_continulets = {} def uwsgi_pypy_continulet_wrapper(cont): lib.async_schedule_to_req_green() + @ffi.callback("void()") def uwsgi_pypy_continulet_schedule(): id = lib.uwsgi.wsgi_req.async_id - modifier1 = lib.uwsgi.wsgi_req.uh.modifier1; + modifier1 = lib.uwsgi.wsgi_req.uh.modifier1 # generate a new continulet if not lib.uwsgi.wsgi_req.suspended: @@ -952,33 +991,35 @@ def uwsgi_pypy_continulet_schedule(): # this is called in the main stack if lib.uwsgi.p[modifier1].suspend: - lib.uwsgi.p[modifier1].suspend(ffi.NULL) + lib.uwsgi.p[modifier1].suspend(ffi.NULL) # let's switch uwsgi_pypy_continulets[id].switch() # back to the main stack if lib.uwsgi.p[modifier1].resume: - lib.uwsgi.p[modifier1].resume(ffi.NULL) + lib.uwsgi.p[modifier1].resume(ffi.NULL) + @ffi.callback("void(struct wsgi_request *)") def uwsgi_pypy_continulet_switch(wsgi_req): id = wsgi_req.async_id - modifier1 = wsgi_req.uh.modifier1; + modifier1 = wsgi_req.uh.modifier1 # this is called in the current continulet if lib.uwsgi.p[modifier1].suspend: - lib.uwsgi.p[modifier1].suspend(wsgi_req) + lib.uwsgi.p[modifier1].suspend(wsgi_req) uwsgi_pypy_continulets[id].switch() # back to the continulet if lib.uwsgi.p[modifier1].resume: - lib.uwsgi.p[modifier1].resume(wsgi_req) + lib.uwsgi.p[modifier1].resume(wsgi_req) # update current running continulet lib.uwsgi.wsgi_req = wsgi_req - + + def uwsgi_pypy_setup_continulets(): if lib.uwsgi.async < 1: raise Exception("pypy continulets require async mode !!!") diff --git a/plugins/pypy/uwsgiplugin.py b/plugins/pypy/uwsgiplugin.py index 66fca415..590c8208 100644 --- a/plugins/pypy/uwsgiplugin.py +++ b/plugins/pypy/uwsgiplugin.py @@ -1,11 +1,14 @@ -NAME='pypy' +NAME = 'pypy' + LDFLAGS = [] LIBS = [] GCC_LIST = ['pypy_plugin'] -BINARY_LIST = [ ('_uwsgi_pypy_setup','pypy_setup.py')] +BINARY_LIST = [ + ('_uwsgi_pypy_setup', 'pypy_setup.py'), +] CFLAGS = [] try: - import __pypy__ + import __pypy__ # NOQA import sys CFLAGS.append('-DUWSGI_PYPY_HOME="\\"%s\\""' % sys.prefix) except: diff --git a/plugins/python/uwsgiplugin.py b/plugins/python/uwsgiplugin.py index f9b4ddb3..499c2d5c 100644 --- a/plugins/python/uwsgiplugin.py +++ b/plugins/python/uwsgiplugin.py @@ -1,7 +1,9 @@ -import os,sys +import os +import sys from distutils import sysconfig + def get_python_version(): version = sysconfig.get_config_var('VERSION') try: @@ -10,13 +12,31 @@ def get_python_version(): pass return version -NAME='python' -GCC_LIST = ['python_plugin', 'pyutils', 'pyloader', 'wsgi_handlers', 'wsgi_headers', 'wsgi_subhandler', 'web3_subhandler', 'pump_subhandler', 'gil', 'uwsgi_pymodule', 'profiler', 'symimporter', 'tracebacker', 'raw'] +NAME = 'python' +GCC_LIST = [ + 'python_plugin', + 'pyutils', + 'pyloader', + 'wsgi_handlers', + 'wsgi_headers', + 'wsgi_subhandler', + 'web3_subhandler', + 'pump_subhandler', + 'gil', + 'uwsgi_pymodule', + 'profiler', + 'symimporter', + 'tracebacker', + 'raw' +] -CFLAGS = ['-I' + sysconfig.get_python_inc(), '-I' + sysconfig.get_python_inc(plat_specific=True) ] +CFLAGS = [ + '-I' + sysconfig.get_python_inc(), + '-I' + sysconfig.get_python_inc(plat_specific=True), +] LDFLAGS = [] -if not 'UWSGI_PYTHON_NOLIB' in os.environ: +if 'UWSGI_PYTHON_NOLIB' not in os.environ: LIBS = sysconfig.get_config_var('LIBS').split() + sysconfig.get_config_var('SYSLIBS').split() # check if it is a non-shared build (but please, add --enable-shared to your python's ./configure script) if not sysconfig.get_config_var('Py_ENABLE_SHARED'): @@ -37,13 +57,13 @@ if not 'UWSGI_PYTHON_NOLIB' in os.environ: uname = os.uname() if uname[4].startswith('arm'): libpath = '%s/%s' % (libdir, sysconfig.get_config_var('LIBRARY')) - if not os.path.exists(libpath): + if not os.path.exists(libpath): libpath = '%s/%s' % (libdir, sysconfig.get_config_var('LDLIBRARY')) else: libpath = '%s/%s' % (libdir, sysconfig.get_config_var('LDLIBRARY')) - if not os.path.exists(libpath): + if not os.path.exists(libpath): libpath = '%s/%s' % (libdir, sysconfig.get_config_var('LIBRARY')) - if not os.path.exists(libpath): + if not os.path.exists(libpath): libpath = '%s/libpython%s.a' % (libdir, version) LIBS.append(libpath) # hack for messy linkers/compilers diff --git a/plugins/pyuwsgi/uwsgiplugin.py b/plugins/pyuwsgi/uwsgiplugin.py index a74c5a22..6e828fac 100644 --- a/plugins/pyuwsgi/uwsgiplugin.py +++ b/plugins/pyuwsgi/uwsgiplugin.py @@ -3,8 +3,12 @@ import os os.environ['UWSGI_PYTHON_NOLIB'] = '1' -NAME='pyuwsgi' -CFLAGS = ['-I' + sysconfig.get_python_inc(), '-I' + sysconfig.get_python_inc(plat_specific=True)] +NAME = 'pyuwsgi' + +CFLAGS = [ + '-I' + sysconfig.get_python_inc(), + '-I' + sysconfig.get_python_inc(plat_specific=True), +] LDFLAGS = [] LIBS = [] diff --git a/plugins/rack/uwsgiplugin.py b/plugins/rack/uwsgiplugin.py index 210b28e9..7dfb322b 100644 --- a/plugins/rack/uwsgiplugin.py +++ b/plugins/rack/uwsgiplugin.py @@ -1,11 +1,11 @@ -import os,sys +import os -NAME='rack' +NAME = 'rack' try: - RUBYPATH = os.environ['UWSGICONFIG_RUBYPATH'] + RUBYPATH = os.environ['UWSGICONFIG_RUBYPATH'] except: - RUBYPATH = 'ruby' + RUBYPATH = 'ruby' rbconfig = 'Config' @@ -18,7 +18,7 @@ if (v[0] == '1' and v[1] == '9') or v[0] >= '2': CFLAGS = os.popen(RUBYPATH + " -e \"require 'rbconfig';print RbConfig::CONFIG['CFLAGS']\"").read().rstrip().split() CFLAGS.append('-DRUBY19') CFLAGS.append('-Wno-unused-parameter') - rbconfig = 'RbConfig' + rbconfig = 'RbConfig' else: CFLAGS = os.popen(RUBYPATH + " -e \"require 'rbconfig';print %s::CONFIG['CFLAGS']\"" % rbconfig).read().rstrip().split() @@ -45,7 +45,7 @@ has_shared = os.popen(RUBYPATH + " -e \"require 'rbconfig';print %s::CONFIG['ENA LIBS = os.popen(RUBYPATH + " -e \"require 'rbconfig';print %s::CONFIG['LIBS']\"" % rbconfig).read().rstrip().split() if has_shared == 'yes': - LDFLAGS.append('-L' + libpath ) + LDFLAGS.append('-L' + libpath) os.environ['LD_RUN_PATH'] = libpath LIBS.append(os.popen(RUBYPATH + " -e \"require 'rbconfig';print '-l' + %s::CONFIG['RUBY_SO_NAME']\"" % rbconfig).read().rstrip()) else: @@ -64,4 +64,3 @@ else: CFLAGS.append('-DUWSGI_RUBY_LIBDIR="\\"%s\\""' % rubylibdir) CFLAGS.append('-DUWSGI_RUBY_ARCHDIR="\\"%s\\""' % rubyarchdir) GCC_LIST.append("%s/%s" % (libpath, os.popen(RUBYPATH + " -e \"require 'rbconfig';print %s::CONFIG['LIBRUBY_A']\"" % rbconfig).read().rstrip())) - diff --git a/plugins/rados/uwsgiplugin.py b/plugins/rados/uwsgiplugin.py index d2365a3a..2189b0e5 100644 --- a/plugins/rados/uwsgiplugin.py +++ b/plugins/rados/uwsgiplugin.py @@ -1,5 +1,4 @@ -import os -NAME='rados' +NAME = 'rados' CFLAGS = [] LDFLAGS = [] diff --git a/plugins/rawrouter/uwsgiplugin.py b/plugins/rawrouter/uwsgiplugin.py index 57158877..32c0d555 100644 --- a/plugins/rawrouter/uwsgiplugin.py +++ b/plugins/rawrouter/uwsgiplugin.py @@ -1,5 +1,5 @@ +NAME = 'rawrouter' -NAME='rawrouter' CFLAGS = [] LDFLAGS = [] LIBS = [] diff --git a/plugins/rbthreads/uwsgiplugin.py b/plugins/rbthreads/uwsgiplugin.py index 79dfd240..fda647b2 100644 --- a/plugins/rbthreads/uwsgiplugin.py +++ b/plugins/rbthreads/uwsgiplugin.py @@ -1,6 +1,6 @@ import os -NAME='rbthreads' +NAME = 'rbthreads' try: RUBYPATH = os.environ['UWSGICONFIG_RUBYPATH'] diff --git a/plugins/redislog/uwsgiplugin.py b/plugins/redislog/uwsgiplugin.py index ef7f2f7e..052ddcc4 100644 --- a/plugins/redislog/uwsgiplugin.py +++ b/plugins/redislog/uwsgiplugin.py @@ -1,4 +1,4 @@ -NAME='redislog' +NAME = 'redislog' CFLAGS = [] LDFLAGS = [] diff --git a/plugins/ring/uwsgiplugin.py b/plugins/ring/uwsgiplugin.py index aa699b2c..9dbab0e5 100644 --- a/plugins/ring/uwsgiplugin.py +++ b/plugins/ring/uwsgiplugin.py @@ -1,6 +1,8 @@ import os import shutil +NAME = 'ring' + jvm_path = 'plugins/jvm' up = {} @@ -11,13 +13,13 @@ except: exec(f.read(), up) f.close() -NAME='ring' CFLAGS = up['CFLAGS'] CFLAGS.append('-I%s' % jvm_path) LDFLAGS = [] LIBS = [] GCC_LIST = ['ring_plugin'] + def post_build(config): env = os.environ.get('VIRTUAL_ENV') if env: @@ -26,4 +28,3 @@ def post_build(config): tgt = "%s/bin/ring_plugin.so" % env shutil.copyfile(plugin, tgt) print("*** ring_plugin.so had been copied to %s" % tgt) - diff --git a/plugins/router_access/uwsgiplugin.py b/plugins/router_access/uwsgiplugin.py index 031f5c0e..35caa2aa 100644 --- a/plugins/router_access/uwsgiplugin.py +++ b/plugins/router_access/uwsgiplugin.py @@ -1,4 +1,5 @@ -NAME='router_access' +NAME = 'router_access' + CFLAGS = [] LDFLAGS = [] LIBS = ['-lwrap'] diff --git a/plugins/router_basicauth/uwsgiplugin.py b/plugins/router_basicauth/uwsgiplugin.py index 8f346369..1987cacd 100644 --- a/plugins/router_basicauth/uwsgiplugin.py +++ b/plugins/router_basicauth/uwsgiplugin.py @@ -1,5 +1,6 @@ import os -NAME='router_basicauth' + +NAME = 'router_basicauth' CFLAGS = [] LDFLAGS = [] diff --git a/plugins/router_cache/uwsgiplugin.py b/plugins/router_cache/uwsgiplugin.py index 4bad3f5f..ee9c90b5 100644 --- a/plugins/router_cache/uwsgiplugin.py +++ b/plugins/router_cache/uwsgiplugin.py @@ -1,4 +1,4 @@ -NAME='router_cache' +NAME = 'router_cache' CFLAGS = [] LDFLAGS = [] diff --git a/plugins/router_expires/uwsgiplugin.py b/plugins/router_expires/uwsgiplugin.py index aecefd71..f1e68c47 100644 --- a/plugins/router_expires/uwsgiplugin.py +++ b/plugins/router_expires/uwsgiplugin.py @@ -1,4 +1,4 @@ -NAME='router_expires' +NAME = 'router_expires' CFLAGS = [] LDFLAGS = [] diff --git a/plugins/router_hash/uwsgiplugin.py b/plugins/router_hash/uwsgiplugin.py index e2d0cbb9..31100d37 100644 --- a/plugins/router_hash/uwsgiplugin.py +++ b/plugins/router_hash/uwsgiplugin.py @@ -1,4 +1,4 @@ -NAME='router_hash' +NAME = 'router_hash' CFLAGS = [] LDFLAGS = [] diff --git a/plugins/router_http/uwsgiplugin.py b/plugins/router_http/uwsgiplugin.py index da4f9629..adc818ba 100644 --- a/plugins/router_http/uwsgiplugin.py +++ b/plugins/router_http/uwsgiplugin.py @@ -1,4 +1,4 @@ -NAME='router_http' +NAME = 'router_http' CFLAGS = [] LDFLAGS = [] diff --git a/plugins/router_memcached/uwsgiplugin.py b/plugins/router_memcached/uwsgiplugin.py index b72e6ad8..cee4010d 100644 --- a/plugins/router_memcached/uwsgiplugin.py +++ b/plugins/router_memcached/uwsgiplugin.py @@ -1,4 +1,4 @@ -NAME='router_memcached' +NAME = 'router_memcached' CFLAGS = [] LDFLAGS = [] diff --git a/plugins/router_metrics/uwsgiplugin.py b/plugins/router_metrics/uwsgiplugin.py index 27c7bef8..b5a04761 100644 --- a/plugins/router_metrics/uwsgiplugin.py +++ b/plugins/router_metrics/uwsgiplugin.py @@ -1,4 +1,4 @@ -NAME='router_metrics' +NAME = 'router_metrics' CFLAGS = [] LDFLAGS = [] diff --git a/plugins/router_radius/uwsgiplugin.py b/plugins/router_radius/uwsgiplugin.py index abf4bba2..50a3837f 100644 --- a/plugins/router_radius/uwsgiplugin.py +++ b/plugins/router_radius/uwsgiplugin.py @@ -1,4 +1,4 @@ -NAME='router_radius' +NAME = 'router_radius' CFLAGS = [] LDFLAGS = [] diff --git a/plugins/router_redirect/uwsgiplugin.py b/plugins/router_redirect/uwsgiplugin.py index 5abf365f..cfc4af43 100644 --- a/plugins/router_redirect/uwsgiplugin.py +++ b/plugins/router_redirect/uwsgiplugin.py @@ -1,4 +1,4 @@ -NAME='router_redirect' +NAME = 'router_redirect' CFLAGS = [] LDFLAGS = [] diff --git a/plugins/router_redis/uwsgiplugin.py b/plugins/router_redis/uwsgiplugin.py index 4b445725..47984b7f 100644 --- a/plugins/router_redis/uwsgiplugin.py +++ b/plugins/router_redis/uwsgiplugin.py @@ -1,4 +1,4 @@ -NAME='router_redis' +NAME = 'router_redis' CFLAGS = [] LDFLAGS = [] diff --git a/plugins/router_rewrite/uwsgiplugin.py b/plugins/router_rewrite/uwsgiplugin.py index 34fc8148..a13782ea 100644 --- a/plugins/router_rewrite/uwsgiplugin.py +++ b/plugins/router_rewrite/uwsgiplugin.py @@ -1,4 +1,4 @@ -NAME='router_rewrite' +NAME = 'router_rewrite' CFLAGS = [] LDFLAGS = [] diff --git a/plugins/router_spnego/uwsgiplugin.py b/plugins/router_spnego/uwsgiplugin.py index b9fc1ae9..3ae32d9f 100644 --- a/plugins/router_spnego/uwsgiplugin.py +++ b/plugins/router_spnego/uwsgiplugin.py @@ -1,5 +1,6 @@ import os -NAME='router_spnego' + +NAME = 'router_spnego' CFLAGS = os.popen('krb5-config --cflags gssapi').read().rstrip().split() LDFLAGS = [] diff --git a/plugins/router_static/uwsgiplugin.py b/plugins/router_static/uwsgiplugin.py index e17f907e..af35f30d 100644 --- a/plugins/router_static/uwsgiplugin.py +++ b/plugins/router_static/uwsgiplugin.py @@ -1,4 +1,4 @@ -NAME='router_static' +NAME = 'router_static' CFLAGS = [] LDFLAGS = [] diff --git a/plugins/router_uwsgi/uwsgiplugin.py b/plugins/router_uwsgi/uwsgiplugin.py index 8d754ceb..4b5b4bc2 100644 --- a/plugins/router_uwsgi/uwsgiplugin.py +++ b/plugins/router_uwsgi/uwsgiplugin.py @@ -1,4 +1,4 @@ -NAME='router_uwsgi' +NAME = 'router_uwsgi' CFLAGS = [] LDFLAGS = [] diff --git a/plugins/router_xmldir/uwsgiplugin.py b/plugins/router_xmldir/uwsgiplugin.py index 04635c85..6800b4cf 100644 --- a/plugins/router_xmldir/uwsgiplugin.py +++ b/plugins/router_xmldir/uwsgiplugin.py @@ -1,4 +1,5 @@ -NAME='router_xmldir' +NAME = 'router_xmldir' + CFLAGS = [] LDFLAGS = [] LIBS = [] diff --git a/plugins/rpc/uwsgiplugin.py b/plugins/rpc/uwsgiplugin.py index 93e3fa7a..75f7554f 100644 --- a/plugins/rpc/uwsgiplugin.py +++ b/plugins/rpc/uwsgiplugin.py @@ -1,4 +1,4 @@ -NAME='rpc' +NAME = 'rpc' CFLAGS = [] LDFLAGS = [] diff --git a/plugins/rrdtool/uwsgiplugin.py b/plugins/rrdtool/uwsgiplugin.py index de73f6ff..6317b4b8 100644 --- a/plugins/rrdtool/uwsgiplugin.py +++ b/plugins/rrdtool/uwsgiplugin.py @@ -1,5 +1,5 @@ +NAME = 'rrdtool' -NAME='rrdtool' CFLAGS = [] LDFLAGS = [] LIBS = [] diff --git a/plugins/rsyslog/uwsgiplugin.py b/plugins/rsyslog/uwsgiplugin.py index 3af77cb5..6030db0d 100644 --- a/plugins/rsyslog/uwsgiplugin.py +++ b/plugins/rsyslog/uwsgiplugin.py @@ -1,4 +1,4 @@ -NAME='rsyslog' +NAME = 'rsyslog' CFLAGS = [] LDFLAGS = [] diff --git a/plugins/ruby19/uwsgiplugin.py b/plugins/ruby19/uwsgiplugin.py index ecea48d0..eb5aecda 100644 --- a/plugins/ruby19/uwsgiplugin.py +++ b/plugins/ruby19/uwsgiplugin.py @@ -1,11 +1,11 @@ -import os,sys +import os -NAME='ruby19' +NAME = 'ruby19' try: - RUBYPATH = os.environ['UWSGICONFIG_RUBYPATH'] + RUBYPATH = os.environ['UWSGICONFIG_RUBYPATH'] except: - RUBYPATH = 'ruby' + RUBYPATH = 'ruby' rbconfig = 'Config' @@ -18,7 +18,7 @@ if v[0] == '1' and v[1] == '9': CFLAGS = os.popen(RUBYPATH + " -e \"require 'rbconfig';print RbConfig::CONFIG['CFLAGS']\"").read().rstrip().split() CFLAGS.append('-DRUBY19') CFLAGS.append('-Wno-unused-parameter') - rbconfig = 'RbConfig' + rbconfig = 'RbConfig' else: CFLAGS = os.popen(RUBYPATH + " -e \"require 'rbconfig';print %s::CONFIG['CFLAGS']\"" % rbconfig).read().rstrip().split() @@ -39,7 +39,6 @@ CFLAGS.append('-Drack_plugin=ruby19_plugin') LDFLAGS = os.popen(RUBYPATH + " -e \"require 'rbconfig';print %s::CONFIG['LDFLAGS']\"" % rbconfig).read().rstrip().split() libpath = os.popen(RUBYPATH + " -e \"require 'rbconfig';print %s::CONFIG['libdir']\"" % rbconfig).read().rstrip() -LDFLAGS.append('-L' + libpath ) +LDFLAGS.append('-L' + libpath) os.environ['LD_RUN_PATH'] = libpath LIBS = os.popen(RUBYPATH + " -e \"require 'rbconfig';print '-l' + %s::CONFIG['RUBY_SO_NAME']\"" % rbconfig).read().rstrip().split() - diff --git a/plugins/servlet/uwsgiplugin.py b/plugins/servlet/uwsgiplugin.py index 7b08e9e4..5c2dcb78 100644 --- a/plugins/servlet/uwsgiplugin.py +++ b/plugins/servlet/uwsgiplugin.py @@ -1,5 +1,4 @@ -import os -import shutil +NAME = 'servlet' jvm_path = 'plugins/jvm' @@ -11,7 +10,6 @@ except: exec(f.read(), up) f.close() -NAME='servlet' CFLAGS = up['CFLAGS'] CFLAGS.append('-I%s' % jvm_path) LDFLAGS = [] diff --git a/plugins/signal/uwsgiplugin.py b/plugins/signal/uwsgiplugin.py index 4af6764d..85cac898 100644 --- a/plugins/signal/uwsgiplugin.py +++ b/plugins/signal/uwsgiplugin.py @@ -1,5 +1,5 @@ +NAME = 'signal' -NAME='signal' CFLAGS = [] LDFLAGS = [] LIBS = [] diff --git a/plugins/spooler/uwsgiplugin.py b/plugins/spooler/uwsgiplugin.py index 5b3bc3ff..2b5a0716 100644 --- a/plugins/spooler/uwsgiplugin.py +++ b/plugins/spooler/uwsgiplugin.py @@ -1,4 +1,4 @@ -NAME='spooler' +NAME = 'spooler' CFLAGS = [] LDFLAGS = [] diff --git a/plugins/sqlite3/uwsgiplugin.py b/plugins/sqlite3/uwsgiplugin.py index 5b4649b9..8e1e8b9f 100644 --- a/plugins/sqlite3/uwsgiplugin.py +++ b/plugins/sqlite3/uwsgiplugin.py @@ -1,5 +1,5 @@ +NAME = 'sqlite3' -NAME='sqlite3' CFLAGS = [] LDFLAGS = [] LIBS = ['-lsqlite3'] diff --git a/plugins/ssi/uwsgiplugin.py b/plugins/ssi/uwsgiplugin.py index 7377fe26..86bf6d3c 100644 --- a/plugins/ssi/uwsgiplugin.py +++ b/plugins/ssi/uwsgiplugin.py @@ -1,4 +1,4 @@ -NAME='ssi' +NAME = 'ssi' CFLAGS = [] LDFLAGS = [] diff --git a/plugins/sslrouter/uwsgiplugin.py b/plugins/sslrouter/uwsgiplugin.py index 171fb5a3..01013776 100644 --- a/plugins/sslrouter/uwsgiplugin.py +++ b/plugins/sslrouter/uwsgiplugin.py @@ -1,5 +1,5 @@ +NAME = 'sslrouter' -NAME='sslrouter' CFLAGS = [] LDFLAGS = [] LIBS = [] diff --git a/plugins/stackless/uwsgiplugin.py b/plugins/stackless/uwsgiplugin.py index 4c3924a0..d720e2b9 100644 --- a/plugins/stackless/uwsgiplugin.py +++ b/plugins/stackless/uwsgiplugin.py @@ -1,7 +1,11 @@ from distutils import sysconfig -NAME='stackless' -CFLAGS = ['-I' + sysconfig.get_python_inc(), '-I' + sysconfig.get_python_inc(plat_specific=True)] +NAME = 'stackless' + +CFLAGS = [ + '-I' + sysconfig.get_python_inc(), + '-I' + sysconfig.get_python_inc(plat_specific=True), +] LDFLAGS = [] LIBS = [] diff --git a/plugins/stats_pusher_file/uwsgiplugin.py b/plugins/stats_pusher_file/uwsgiplugin.py index 643f13a1..6377407d 100644 --- a/plugins/stats_pusher_file/uwsgiplugin.py +++ b/plugins/stats_pusher_file/uwsgiplugin.py @@ -1,4 +1,4 @@ -NAME='stats_pusher_file' +NAME = 'stats_pusher_file' CFLAGS = [] LDFLAGS = [] diff --git a/plugins/stats_pusher_mongodb/uwsgiplugin.py b/plugins/stats_pusher_mongodb/uwsgiplugin.py index f3b28600..cc4dd0bb 100644 --- a/plugins/stats_pusher_mongodb/uwsgiplugin.py +++ b/plugins/stats_pusher_mongodb/uwsgiplugin.py @@ -1,12 +1,15 @@ import os -NAME='stats_pusher_mongodb' +NAME = 'stats_pusher_mongodb' -CFLAGS = ['-I/usr/include/mongo','-I/usr/local/include/mongo'] +CFLAGS = [ + '-I/usr/include/mongo', + '-I/usr/local/include/mongo', +] LDFLAGS = [] LIBS = [] -if not 'UWSGI_MONGODB_NOLIB' in os.environ: +if 'UWSGI_MONGODB_NOLIB' not in os.environ: LIBS.append('-lmongoclient') LIBS.append('-lboost_thread') LIBS.append('-lboost_filesystem') diff --git a/plugins/stats_pusher_socket/uwsgiplugin.py b/plugins/stats_pusher_socket/uwsgiplugin.py index 5c4d7fbb..49679bfe 100644 --- a/plugins/stats_pusher_socket/uwsgiplugin.py +++ b/plugins/stats_pusher_socket/uwsgiplugin.py @@ -1,4 +1,4 @@ -NAME='stats_pusher_socket' +NAME = 'stats_pusher_socket' CFLAGS = [] LDFLAGS = [] diff --git a/plugins/stats_pusher_statsd/uwsgiplugin.py b/plugins/stats_pusher_statsd/uwsgiplugin.py index bd2d31b7..ed27c8ba 100644 --- a/plugins/stats_pusher_statsd/uwsgiplugin.py +++ b/plugins/stats_pusher_statsd/uwsgiplugin.py @@ -1,4 +1,4 @@ -NAME='stats_pusher_statsd' +NAME = 'stats_pusher_statsd' CFLAGS = [] LDFLAGS = [] diff --git a/plugins/symcall/uwsgiplugin.py b/plugins/symcall/uwsgiplugin.py index e77df6bd..a28d85d7 100644 --- a/plugins/symcall/uwsgiplugin.py +++ b/plugins/symcall/uwsgiplugin.py @@ -1,4 +1,4 @@ -NAME='symcall' +NAME = 'symcall' CFLAGS = [] LDFLAGS = [] diff --git a/plugins/syslog/uwsgiplugin.py b/plugins/syslog/uwsgiplugin.py index 46bf4381..6d79e830 100644 --- a/plugins/syslog/uwsgiplugin.py +++ b/plugins/syslog/uwsgiplugin.py @@ -1,4 +1,4 @@ -NAME='syslog' +NAME = 'syslog' CFLAGS = [] LDFLAGS = [] diff --git a/plugins/systemd_logger/uwsgiplugin.py b/plugins/systemd_logger/uwsgiplugin.py index e876a0b9..fae248b7 100644 --- a/plugins/systemd_logger/uwsgiplugin.py +++ b/plugins/systemd_logger/uwsgiplugin.py @@ -1,7 +1,8 @@ import os -NAME='systemd_logger' + +NAME = 'systemd_logger' CFLAGS = os.popen('pkg-config --cflags libsystemd-journal').read().rstrip().split() LDFLAGS = [] -LIBS = os.popen('pkg-config --libs libsystemd-journal').read().rstrip().split() +LIBS = os.popen('pkg-config --libs libsystemd-journal').read().rstrip().split() GCC_LIST = ['systemd_logger'] diff --git a/plugins/tornado/uwsgiplugin.py b/plugins/tornado/uwsgiplugin.py index efd9e08e..c0179b60 100644 --- a/plugins/tornado/uwsgiplugin.py +++ b/plugins/tornado/uwsgiplugin.py @@ -1,7 +1,11 @@ from distutils import sysconfig -NAME='tornado' -CFLAGS = ['-I' + sysconfig.get_python_inc(), '-I' + sysconfig.get_python_inc(plat_specific=True)] +NAME = 'tornado' + +CFLAGS = [ + '-I' + sysconfig.get_python_inc(), + '-I' + sysconfig.get_python_inc(plat_specific=True), +] LDFLAGS = [] LIBS = [] diff --git a/plugins/transformation_chunked/uwsgiplugin.py b/plugins/transformation_chunked/uwsgiplugin.py index 0d957a86..c48eb6c6 100644 --- a/plugins/transformation_chunked/uwsgiplugin.py +++ b/plugins/transformation_chunked/uwsgiplugin.py @@ -1,4 +1,4 @@ -NAME='transformation_chunked' +NAME = 'transformation_chunked' CFLAGS = [] LDFLAGS = [] diff --git a/plugins/transformation_gzip/uwsgiplugin.py b/plugins/transformation_gzip/uwsgiplugin.py index 76a4bc91..d8cd28c3 100644 --- a/plugins/transformation_gzip/uwsgiplugin.py +++ b/plugins/transformation_gzip/uwsgiplugin.py @@ -1,4 +1,4 @@ -NAME='transformation_gzip' +NAME = 'transformation_gzip' CFLAGS = [] LDFLAGS = [] diff --git a/plugins/transformation_offload/uwsgiplugin.py b/plugins/transformation_offload/uwsgiplugin.py index 9221dc1e..ba550e7e 100644 --- a/plugins/transformation_offload/uwsgiplugin.py +++ b/plugins/transformation_offload/uwsgiplugin.py @@ -1,4 +1,4 @@ -NAME='transformation_offload' +NAME = 'transformation_offload' CFLAGS = [] LDFLAGS = [] diff --git a/plugins/transformation_template/uwsgiplugin.py b/plugins/transformation_template/uwsgiplugin.py index 7a0c07de..0cc51011 100644 --- a/plugins/transformation_template/uwsgiplugin.py +++ b/plugins/transformation_template/uwsgiplugin.py @@ -1,4 +1,4 @@ -NAME='transformation_template' +NAME = 'transformation_template' CFLAGS = [] LDFLAGS = [] diff --git a/plugins/transformation_tofile/uwsgiplugin.py b/plugins/transformation_tofile/uwsgiplugin.py index aa278991..4082ec88 100644 --- a/plugins/transformation_tofile/uwsgiplugin.py +++ b/plugins/transformation_tofile/uwsgiplugin.py @@ -1,4 +1,4 @@ -NAME='transformation_tofile' +NAME = 'transformation_tofile' CFLAGS = [] LDFLAGS = [] diff --git a/plugins/transformation_toupper/uwsgiplugin.py b/plugins/transformation_toupper/uwsgiplugin.py index 8f3f5746..4dd48405 100644 --- a/plugins/transformation_toupper/uwsgiplugin.py +++ b/plugins/transformation_toupper/uwsgiplugin.py @@ -1,4 +1,4 @@ -NAME='transformation_toupper' +NAME = 'transformation_toupper' CFLAGS = [] LDFLAGS = [] diff --git a/plugins/tuntap/uwsgiplugin.py b/plugins/tuntap/uwsgiplugin.py index 4cf8dad7..853defe2 100644 --- a/plugins/tuntap/uwsgiplugin.py +++ b/plugins/tuntap/uwsgiplugin.py @@ -1,5 +1,6 @@ -NAME='tuntap' -CFLAGS=[] -LDFLAGS=[] -LIBS=[] -GCC_LIST=['common','firewall','tuntap'] +NAME = 'tuntap' + +CFLAGS = [] +LDFLAGS = [] +LIBS = [] +GCC_LIST = ['common', 'firewall', 'tuntap'] diff --git a/plugins/ugreen/uwsgiplugin.py b/plugins/ugreen/uwsgiplugin.py index b206c620..b01429fe 100644 --- a/plugins/ugreen/uwsgiplugin.py +++ b/plugins/ugreen/uwsgiplugin.py @@ -1,5 +1,5 @@ +NAME = 'ugreen' -NAME='ugreen' CFLAGS = [] LDFLAGS = [] LIBS = [] diff --git a/plugins/v8/uwsgiplugin.py b/plugins/v8/uwsgiplugin.py index edf8f096..9e037493 100644 --- a/plugins/v8/uwsgiplugin.py +++ b/plugins/v8/uwsgiplugin.py @@ -1,5 +1,6 @@ import os -NAME='v8' + +NAME = 'v8' CFLAGS = ['-Wno-deprecated-declarations'] LDFLAGS = [] diff --git a/plugins/webdav/uwsgiplugin.py b/plugins/webdav/uwsgiplugin.py index ab4f4454..121590db 100644 --- a/plugins/webdav/uwsgiplugin.py +++ b/plugins/webdav/uwsgiplugin.py @@ -1,6 +1,7 @@ import os -NAME='webdav' +NAME = 'webdav' + CFLAGS = os.popen('xml2-config --cflags').read().rstrip().split() LDFLAGS = [] LIBS = os.popen('xml2-config --libs').read().rstrip().split() diff --git a/plugins/xattr/uwsgiplugin.py b/plugins/xattr/uwsgiplugin.py index 5baa48c8..2d6efbaa 100644 --- a/plugins/xattr/uwsgiplugin.py +++ b/plugins/xattr/uwsgiplugin.py @@ -1,5 +1,6 @@ -NAME='xattr' -CFLAGS=[] -LDFLAGS=[] -LIBS=[] +NAME = 'xattr' + +CFLAGS = [] +LDFLAGS = [] +LIBS = [] GCC_LIST = ['xattr'] diff --git a/plugins/xslt/uwsgiplugin.py b/plugins/xslt/uwsgiplugin.py index 8a8c20c1..54625ff5 100644 --- a/plugins/xslt/uwsgiplugin.py +++ b/plugins/xslt/uwsgiplugin.py @@ -1,6 +1,7 @@ import os -NAME='xslt' +NAME = 'xslt' + CFLAGS = os.popen('xslt-config --cflags').read().rstrip().split() LDFLAGS = [] LIBS = os.popen('xslt-config --libs').read().rstrip().split() diff --git a/plugins/zabbix/uwsgiplugin.py b/plugins/zabbix/uwsgiplugin.py index 469f07ca..9ab3121e 100644 --- a/plugins/zabbix/uwsgiplugin.py +++ b/plugins/zabbix/uwsgiplugin.py @@ -1,4 +1,4 @@ -NAME='zabbix' +NAME = 'zabbix' CFLAGS = [] LDFLAGS = [] diff --git a/plugins/zergpool/uwsgiplugin.py b/plugins/zergpool/uwsgiplugin.py index d8720456..13a3a745 100644 --- a/plugins/zergpool/uwsgiplugin.py +++ b/plugins/zergpool/uwsgiplugin.py @@ -1,5 +1,5 @@ +NAME = 'zergpool' -NAME='zergpool' CFLAGS = [] LDFLAGS = [] LIBS = [] diff --git a/setup.cpyext.py b/setup.cpyext.py index ee89dbc5..c29b1d3a 100644 --- a/setup.cpyext.py +++ b/setup.cpyext.py @@ -10,13 +10,9 @@ import os import sys import errno import shlex -import shutil import uwsgiconfig from setuptools import setup -from setuptools.dist import Distribution -from setuptools.command.install import install -from setuptools.command.install_lib import install_lib from setuptools.command.build_ext import build_ext from distutils.core import Extension @@ -28,42 +24,33 @@ class uWSGIBuildExt(build_ext): def build_extensions(self): self.uwsgi_setup() - #XXX: needs uwsgiconfig fix + # XXX: needs uwsgiconfig fix self.uwsgi_build() if 'UWSGI_USE_DISTUTILS' not in os.environ: - #XXX: needs uwsgiconfig fix - #uwsgiconfig.build_uwsgi(self.uwsgi_config) + # XXX: needs uwsgiconfig fix + # uwsgiconfig.build_uwsgi(self.uwsgi_config) return else: - #XXX: needs uwsgiconfig fix + # XXX: needs uwsgiconfig fix os.unlink(self.uwsgi_config.get('bin_name')) - #FIXME: else build fails :( - for baddie in set(self.compiler.compiler_so) & set(( - '-Wstrict-prototypes', - )): + # FIXME: else build fails :( + for baddie in set(self.compiler.compiler_so) & set(('-Wstrict-prototypes',)): self.compiler.compiler_so.remove(baddie) build_ext.build_extensions(self) def uwsgi_setup(self): - default = ( - '__pypy__' in sys.builtin_module_names - and 'pypy' - or 'default' - ) - profile = ( - os.environ.get('UWSGI_PROFILE') - or 'buildconf/%s.ini' % default - ) + default = 'pypy' if '__pypy__' in sys.builtin_module_names else 'default' + profile = os.environ.get('UWSGI_PROFILE') or 'buildconf/%s.ini' % default if not profile.endswith('.ini'): profile = profile + '.ini' - if not '/' in profile: + if '/' not in profile: profile = 'buildconf/' + profile - #FIXME: update uwsgiconfig to properly set _EVERYTHING_! + # FIXME: update uwsgiconfig to properly set _EVERYTHING_! config = uwsgiconfig.uConf(profile) # insert in the beginning so UWSGI_PYTHON_NOLIB is exported # before the python plugin compiles @@ -86,7 +73,7 @@ class uWSGIBuildExt(build_ext): def uwsgi_build(self): uwsgiconfig.build_uwsgi(self.uwsgi_config) - #XXX: merge uwsgi_setup (see other comments) + # XXX: merge uwsgi_setup (see other comments) for ext in self.extensions: if ext.name == self.UWSGI_NAME: ext.sources = [s + '.c' for s in self.uwsgi_config.gcc_list] @@ -96,7 +83,7 @@ class uWSGIBuildExt(build_ext): for x in uwsgiconfig.uniq_warnings( self.uwsgi_config.ldflags + self.uwsgi_config.libs, - ): + ): for y in shlex.split(x): if y.startswith('-l'): ext.libraries.append(y[2:]) diff --git a/setup.py b/setup.py index 584797ee..0b63df40 100644 --- a/setup.py +++ b/setup.py @@ -1,7 +1,6 @@ import os import sys import uwsgiconfig as uc -import shutil from setuptools import setup from setuptools.dist import Distribution @@ -21,7 +20,7 @@ uwsgi_compiled = False def get_profile(): is_pypy = False try: - import __pypy__ + import __pypy__ # NOQA is_pypy = True except ImportError: pass @@ -31,7 +30,7 @@ def get_profile(): profile = os.environ.get('UWSGI_PROFILE', 'buildconf/default.ini') if not profile.endswith('.ini'): profile = "%s.ini" % profile - if not '/' in profile: + if '/' not in profile: profile = "buildconf/%s" % profile return profile @@ -99,12 +98,13 @@ class uWSGIDistribution(Distribution): return False -setup(name='uWSGI', - version=uc.uwsgi_version, - description='The uWSGI server', - author='Unbit', - author_email='info@unbit.it', - license='GPL2', - py_modules=['uwsgidecorators'], - distclass=uWSGIDistribution, - ) +setup( + name='uWSGI', + version=uc.uwsgi_version, + description='The uWSGI server', + author='Unbit', + author_email='info@unbit.it', + license='GPL2', + py_modules=['uwsgidecorators'], + distclass=uWSGIDistribution, +) diff --git a/t/cachebitmap.py b/t/cachebitmap.py index d3791d4a..d9880042 100644 --- a/t/cachebitmap.py +++ b/t/cachebitmap.py @@ -3,9 +3,20 @@ import unittest import random import string + class BitmapTest(unittest.TestCase): - __caches__ = ['items_1', 'items_2', 'items_3', 'items_4', 'items_17', 'items_4_10', 'items_1_100000', 'items_non_bitmap', 'items_lru'] + __caches__ = [ + 'items_1', + 'items_2', + 'items_3', + 'items_4', + 'items_17', + 'items_4_10', + 'items_1_100000', + 'items_non_bitmap', + 'items_lru' + ] def setUp(self): for cache in self.__caches__: @@ -27,7 +38,7 @@ class BitmapTest(unittest.TestCase): def test_overlapping(self): self.assertTrue(uwsgi.cache_update('key1', 'HE', 0, 'items_2')) self.assertIsNone(uwsgi.cache_update('key1', 'HELL', 0, 'items_2')) - self.assertTrue(uwsgi.cache_del('key1', 'items_2')) + self.assertTrue(uwsgi.cache_del('key1', 'items_2')) self.assertTrue(uwsgi.cache_update('key1', 'HELL', 0, 'items_2')) def test_big_item(self): @@ -49,7 +60,7 @@ class BitmapTest(unittest.TestCase): self.assertIsNone(uwsgi.cache_set('key5', 'HELLO', 0, 'items_4_10')) def test_big_delete(self): - self.assertTrue(uwsgi.cache_set('key1', 'X' * 50 , 0, 'items_4_10')) + self.assertTrue(uwsgi.cache_set('key1', 'X' * 50, 0, 'items_4_10')) self.assertTrue(uwsgi.cache_del('key1', 'items_4_10')) self.assertTrue(uwsgi.cache_set('key1', 'HELLOHELLO', 0, 'items_4_10')) self.assertTrue(uwsgi.cache_set('key2', 'HELLOHELLO', 0, 'items_4_10')) @@ -58,11 +69,11 @@ class BitmapTest(unittest.TestCase): self.assertIsNone(uwsgi.cache_set('key5', 'HELLOHELLO', 0, 'items_4_10')) def test_big_update(self): - self.assertTrue(uwsgi.cache_set('key1', 'X' * 40 , 0, 'items_4_10')) - self.assertTrue(uwsgi.cache_update('key1', 'X' * 10 , 0, 'items_4_10')) + self.assertTrue(uwsgi.cache_set('key1', 'X' * 40, 0, 'items_4_10')) + self.assertTrue(uwsgi.cache_update('key1', 'X' * 10, 0, 'items_4_10')) self.assertTrue(uwsgi.cache_del('key1', 'items_4_10')) - self.assertIsNone(uwsgi.cache_update('key1', 'X' * 51 , 0, 'items_4_10')) - self.assertTrue(uwsgi.cache_update('key1', 'X' * 50 , 0, 'items_4_10')) + self.assertIsNone(uwsgi.cache_update('key1', 'X' * 51, 0, 'items_4_10')) + self.assertTrue(uwsgi.cache_update('key1', 'X' * 50, 0, 'items_4_10')) def test_multi_clear(self): for i in range(0, 100): @@ -70,23 +81,23 @@ class BitmapTest(unittest.TestCase): def test_multi_delete(self): for i in range(0, 100): - self.assertTrue(uwsgi.cache_set('key1', 'X' * 50 , 0, 'items_4_10')) + self.assertTrue(uwsgi.cache_set('key1', 'X' * 50, 0, 'items_4_10')) self.assertTrue(uwsgi.cache_del('key1', 'items_4_10')) for i in range(0, 100): - self.assertIsNone(uwsgi.cache_set('key1', 'X' * 51 , 0, 'items_4_10')) + self.assertIsNone(uwsgi.cache_set('key1', 'X' * 51, 0, 'items_4_10')) self.assertIsNone(uwsgi.cache_del('key1', 'items_4_10')) for i in range(0, 100): - self.assertTrue(uwsgi.cache_set('key1', 'X' * 50 , 0, 'items_4_10')) + self.assertTrue(uwsgi.cache_set('key1', 'X' * 50, 0, 'items_4_10')) self.assertTrue(uwsgi.cache_del('key1', 'items_4_10')) def test_big_key(self): - self.assertTrue(uwsgi.cache_set('K' * 2048, 'X' * 50 , 0, 'items_4_10')) - self.assertIsNone(uwsgi.cache_set('K' * 2049, 'X' * 50 , 0, 'items_4_10')) + self.assertTrue(uwsgi.cache_set('K' * 2048, 'X' * 50, 0, 'items_4_10')) + self.assertIsNone(uwsgi.cache_set('K' * 2049, 'X' * 50, 0, 'items_4_10')) def rand_blob(self, n=32): - return ''.join([random.choice(string.ascii_letters + string.digits) for n in range(n)]) + return ''.join(random.choice(string.ascii_letters + string.digits) for x in range(n)) def test_big_random(self): blob = self.rand_blob(100000) @@ -108,9 +119,9 @@ class BitmapTest(unittest.TestCase): self.assertTrue(uwsgi.cache_set('KEY2', 'X' * 20, 0, 'items_lru')) self.assertTrue(uwsgi.cache_set('KEY3', 'Y' * 20, 0, 'items_lru')) self.assertIsNone(uwsgi.cache_get('KEY1', 'items_lru')) - second_item = uwsgi.cache_get('KEY3', 'items_lru') - for i in range(4,100): + uwsgi.cache_get('KEY3', 'items_lru') + for i in range(4, 100): self.assertTrue(uwsgi.cache_set('KEY%d' % i, 'Y' * 20, 0, 'items_lru')) self.assertIsNone(uwsgi.cache_get('KEY%d' % (i-2), 'items_lru')) - + unittest.main() diff --git a/t/cachetest.py b/t/cachetest.py index 82096867..b717e8d3 100644 --- a/t/cachetest.py +++ b/t/cachetest.py @@ -5,20 +5,22 @@ import string items = {} + def gen_rand_n(max_n): return random.randint(8, max_n) + def gen_rand_s(size): - return ''.join( [ random.choice(string.letters) for i in range(size) ]) + return ''.join(random.choice(string.letters) for i in range(size)) print 'filling cache...' for i in range(0, 1000): - kl = gen_rand_n(200) - key = gen_rand_s(kl) - vl = gen_rand_n(10000) - val = gen_rand_s(vl) - items[key] = val - uwsgi.cache_set(key, val) + kl = gen_rand_n(200) + key = gen_rand_s(kl) + vl = gen_rand_n(10000) + val = gen_rand_s(vl) + items[key] = val + uwsgi.cache_set(key, val) print 'checking cache...' count = 0 @@ -26,8 +28,8 @@ for key in items.keys(): val = uwsgi.cache_get(key) count += 1 if val != items[key]: - print len(val), val - print len(items[key]), items[key] - raise Exception('CACHE TEST FAILED AFTER %d ITERATIONS !!!' % count) + print len(val), val + print len(items[key]), items[key] + raise Exception('CACHE TEST FAILED AFTER %d ITERATIONS !!!' % count) print "TEST PASSED" diff --git a/t/pypy/t_continulet1.py b/t/pypy/t_continulet1.py index 2b72423f..d4ad90c4 100644 --- a/t/pypy/t_continulet1.py +++ b/t/pypy/t_continulet1.py @@ -7,11 +7,13 @@ uwsgi --pypy-wsgi-file t/pypy/t_continulet1.py --http-socket :9090 --pypy-home / """ import uwsgi + + def application(e, sr): - sr('200 OK', [('Content-Type','text/plain')]) + sr('200 OK', [('Content-Type', 'text/plain')]) # call suspend 10 times and yield some value - for i in range(0,10): + for i in range(0, 10): print i uwsgi.suspend() yield str(i) diff --git a/t/pypy/t_continulet2.py b/t/pypy/t_continulet2.py index 5a6926fa..0d7ab6d1 100644 --- a/t/pypy/t_continulet2.py +++ b/t/pypy/t_continulet2.py @@ -7,11 +7,13 @@ uwsgi --pypy-wsgi-file t/pypy/t_continulet2.py --http-socket :9090 --pypy-home / """ import uwsgi + + def application(e, sr): - sr('200 OK', [('Content-Type','text/plain')]) + sr('200 OK', [('Content-Type', 'text/plain')]) # suspend 10 times and yield a value - for i in range(1,10): + for i in range(1, 10): print i uwsgi.suspend() yield str(i) @@ -21,7 +23,7 @@ def application(e, sr): try: command = "get /foobar\r\n" remains = len(command) - while remains > 0: + while remains > 0: # start waiting for socket availability (4 seconds max) uwsgi.wait_fd_write(fd, 4) # suspend execution 'til event diff --git a/t/python/spooler_decorators/spooler_handlers.py b/t/python/spooler_decorators/spooler_handlers.py index e5d059f7..44be5ed2 100644 --- a/t/python/spooler_decorators/spooler_handlers.py +++ b/t/python/spooler_decorators/spooler_handlers.py @@ -1,6 +1,6 @@ # See spooler_decorator_tests -from uwsgidecorators import * +from uwsgidecorators import spool, spoolraw import uwsgi ghostpath = "/tmp/ghost" diff --git a/t/python/spooler_handler.py b/t/python/spooler_handler.py index dfaa46e0..fb7b86e8 100644 --- a/t/python/spooler_handler.py +++ b/t/python/spooler_handler.py @@ -10,25 +10,25 @@ counter = 0 def spoolerHandler(env): - global counter - # Spooler is handling a task - with open(LOGFILE, "a") as log: - print("%s" % (env['name']), file=log) + global counter + # Spooler is handling a task + with open(LOGFILE, "a") as log: + print("%s" % (env['name']), file=log) - counter += 1 + counter += 1 - if counter == len(tasks): - # Each task has been processed. - uwsgi.signal(17) + if counter == len(tasks): + # Each task has been processed. + uwsgi.signal(17) - # Spooler has done handling the task - return uwsgi.SPOOL_OK + # Spooler has done handling the task + return uwsgi.SPOOL_OK uwsgi.spooler = spoolerHandler # Clear the logfile try: - remove(LOGFILE) + remove(LOGFILE) except OSError, e: # log does not exist - pass - # print(e) + pass + # print(e) diff --git a/t/python/spooler_priority/spooler_priority_constants.py b/t/python/spooler_priority/spooler_priority_constants.py index 4e77d15a..1b6421e8 100644 --- a/t/python/spooler_priority/spooler_priority_constants.py +++ b/t/python/spooler_priority/spooler_priority_constants.py @@ -2,21 +2,21 @@ # coding = utf-8 tasks = [ - (101, "101"), - (101, "101Bis"), - (2, "2"), - (1, "1"), - (0, "0"), - (None, "NoPriority") + (101, "101"), + (101, "101Bis"), + (2, "2"), + (1, "1"), + (0, "0"), + (None, "NoPriority") ] ordered_tasks = [ - "0", - "1", - "2", - "101", - "101Bis", - "NoPriority" + "0", + "1", + "2", + "101", + "101Bis", + "NoPriority" ] LOGFILE = "/tmp/spoolerlog" diff --git a/t/python/spooler_priority/spooler_priority_handler.py b/t/python/spooler_priority/spooler_priority_handler.py index 97d9a7da..bf47f060 100644 --- a/t/python/spooler_priority/spooler_priority_handler.py +++ b/t/python/spooler_priority/spooler_priority_handler.py @@ -10,24 +10,24 @@ counter = 0 def spoolerHandler(env): - global counter - # Spooler is handling a task - with open(LOGFILE, "a") as log: - print("%s" % (env['name']), file=log) + global counter + # Spooler is handling a task + with open(LOGFILE, "a") as log: + print("%s" % (env['name']), file=log) - counter += 1 + counter += 1 - if counter == len(tasks): - # Each task has been processed. - uwsgi.signal(17) + if counter == len(tasks): + # Each task has been processed. + uwsgi.signal(17) - # Spooler has done handling the task - return uwsgi.SPOOL_OK + # Spooler has done handling the task + return uwsgi.SPOOL_OK uwsgi.spooler = spoolerHandler # Clear the logfile try: - remove(LOGFILE) + remove(LOGFILE) except OSError, e: # log does not exist - print(e) + print(e) diff --git a/t/python/spooler_priority/spooler_priority_test.py b/t/python/spooler_priority/spooler_priority_test.py index a30dc889..c9d4a661 100644 --- a/t/python/spooler_priority/spooler_priority_test.py +++ b/t/python/spooler_priority/spooler_priority_test.py @@ -7,76 +7,75 @@ import os import fcntl from shutil import rmtree import time -from signal import * +from signal import signal, SIGINT import spooler_priority_constants def spoolersTaskList(): - # Get the list of tasks - tasks = [ - os.path.join(s, fn) - for s in uwsgi.spoolers - for fn in os.listdir(s) - ] + # Get the list of tasks + tasks = [ + os.path.join(s, fn) + for s in uwsgi.spoolers + for fn in os.listdir(s) + ] - for t in tasks[:]: - if os.path.isdir(t): - tasks += [os.path.join(t, fn) for fn in os.listdir(t)] - tasks.remove(t) + for t in tasks[:]: + if os.path.isdir(t): + tasks += [os.path.join(t, fn) for fn in os.listdir(t)] + tasks.remove(t) - return tasks + return tasks def is_locked(filepath): - # Check if file is locked - with open(filepath, "a+") as f: - try: - fcntl.lockf(f.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB) - is_locked = False - except IOError: - is_locked = True - return is_locked + # Check if file is locked + with open(filepath, "a+") as f: + try: + fcntl.lockf(f.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB) + is_locked = False + except IOError: + is_locked = True + return is_locked def lockedTasks(tasklist): - # List of locked tasks - return [fp for fp in spoolersTaskList() if is_locked(fp)] + # List of locked tasks + return [fp for fp in spoolersTaskList() if is_locked(fp)] def taskParameters(filepath): - # Retrieve parameters - return uwsgi.parsefile(filepath) + # Retrieve parameters + return uwsgi.parsefile(filepath) def cleanTasks(): - # Clean any remaining task - for s in uwsgi.spoolers: - for f in os.listdir(s): - path = os.path.join(s, f) - if os.path.isdir(path): - rmtree(os.path.join(s, f)) - else: - os.remove(path) + # Clean any remaining task + for s in uwsgi.spoolers: + for f in os.listdir(s): + path = os.path.join(s, f) + if os.path.isdir(path): + rmtree(os.path.join(s, f)) + else: + os.remove(path) class BitmapTest(unittest.TestCase): - def setUp(self): - for priority, name in spooler_priority_constants.tasks: - task = {'name': name, 'at': int(time.time() + 10)} - if priority is not None: - task['priority'] = str(priority) - uwsgi.spool(task) + def setUp(self): + for priority, name in spooler_priority_constants.tasks: + task = {'name': name, 'at': int(time.time() + 10)} + if priority is not None: + task['priority'] = str(priority) + uwsgi.spool(task) - def test_priority(self): - uwsgi.signal_wait(17) - print("Signal received.") + def test_priority(self): + uwsgi.signal_wait(17) + print("Signal received.") - with open(spooler_priority_constants.LOGFILE, "r") as log: - # Check logging ordering. - loglines = [line.rstrip() for line in log] - self.assertEqual(loglines, spooler_priority_constants.ordered_tasks) + with open(spooler_priority_constants.LOGFILE, "r") as log: + # Check logging ordering. + loglines = [line.rstrip() for line in log] + self.assertEqual(loglines, spooler_priority_constants.ordered_tasks) signal(SIGINT, cleanTasks) unittest.main() - diff --git a/t/python/testba.py b/t/python/testba.py index 461f54b7..3bef9e5c 100644 --- a/t/python/testba.py +++ b/t/python/testba.py @@ -1,7 +1,9 @@ import array + + def application(e, sr): - sr('200 OK', [('Content-Type','text/html')]) - a = array.array('b',[54,55,56,57]) + sr('200 OK', [('Content-Type', 'text/html')]) + a = array.array('b', [54, 55, 56, 57]) yield a yield bytearray(b'abcdef') yield b'ciao' diff --git a/tests/badthread.py b/tests/badthread.py index f0ed029f..a0f459a8 100644 --- a/tests/badthread.py +++ b/tests/badthread.py @@ -1,3 +1,3 @@ def application(env, start_response): - while 1: - pass + while 1: + pass diff --git a/tests/badwrites.py b/tests/badwrites.py index d060f995..2feb628e 100644 --- a/tests/badwrites.py +++ b/tests/badwrites.py @@ -1,5 +1,5 @@ import time -import sys + def application(e, sr): time.sleep(3) diff --git a/tests/cpubound_async.py b/tests/cpubound_async.py index 1a117bbc..03517fc4 100644 --- a/tests/cpubound_async.py +++ b/tests/cpubound_async.py @@ -1,6 +1,7 @@ import time + def application(env, start_response): - start_response( '200 OK', [ ('Content-Type','text/html') ]) - for i in range(1,1000): - yield "

%s at %s

" % (i, str(time.time())) + start_response('200 OK', [('Content-Type', 'text/html')]) + for i in range(1, 1000): + yield "

%s at %s

" % (i, str(time.time())) diff --git a/tests/cpubound_green.py b/tests/cpubound_green.py index 80640e5c..b669f041 100644 --- a/tests/cpubound_green.py +++ b/tests/cpubound_green.py @@ -1,15 +1,16 @@ import uwsgi import time -def application(env, start_response): - counter = 0 - start_response( '200 OK', [ ('Content-Type','text/html') ]) - start_time = time.time() - for i in range(1,100000): - uwsgi.suspend() - # print every 100 - if i % 100 == 0: - yield "

%d

\n" % i - counter = counter + i - yield "

%d cycles after %d

\n" % (counter, time.time() - start_time) +def application(env, start_response): + counter = 0 + start_response('200 OK', [('Content-Type', 'text/html')]) + start_time = time.time() + for i in range(1, 100000): + uwsgi.suspend() + # print every 100 + if i % 100 == 0: + yield "

%d

\n" % i + counter = counter + i + + yield "

%d cycles after %d

\n" % (counter, time.time() - start_time) diff --git a/tests/cpubound_stackless.py b/tests/cpubound_stackless.py index 16aa4a9d..a4c39724 100644 --- a/tests/cpubound_stackless.py +++ b/tests/cpubound_stackless.py @@ -1,14 +1,14 @@ import time import stackless -def application(env, start_response): - start_response( '200 OK', [ ('Content-Type','text/html') ]) - #print env - for i in range(1,100000): - #print i - yield "

%s at %s

\n" % (i, str(time.time())) - #schedule every 2 - if i % 2 == 0: - stackless.schedule() - print "DONE AT %d" % i +def application(env, start_response): + start_response('200 OK', [('Content-Type', 'text/html')]) + + for i in range(1, 100000): + yield "

%s at %s

\n" % (i, str(time.time())) + # schedule every 2 + if i % 2 == 0: + stackless.schedule() + + print "DONE AT %d" % i diff --git a/tests/decoratortest.py b/tests/decoratortest.py index bc99dd32..3fb538e0 100644 --- a/tests/decoratortest.py +++ b/tests/decoratortest.py @@ -3,7 +3,7 @@ import uwsgi from uwsgidecorators import * -from uwsgicc import app as application +from uwsgicc import app as application # NOQA import time @@ -13,11 +13,13 @@ import time def hello2(): return "[RPC] Hello World" + # register signal 1 @signal(1) def what_time_is_it(num): print(time.asctime()) + # register signal 100 @signal(100, target='workers') def what_time_is_it(num): @@ -29,11 +31,13 @@ def what_time_is_it(num): def salut(num): print("Salut !!! 3 seconds elapsed and signal %d raised" % num) + # a 10 seconds red black timer (executed by the spooler) @rbtimer(10, target='spooler') def tenseconds(num): print("red black timer !!! 10 seconds elapsed and signal %d raised" % num) + # monitor /tmp directory @filemon("/tmp") def tmpmodified(num): @@ -43,15 +47,16 @@ def tmpmodified(num): # spool a long running task @spool def a_long_task(args): - for i in xrange(1,10): - print("%s = %d" % ( str(args), i)) + for i in xrange(1, 10): + print("%s = %d" % (str(args), i)) print(uwsgi.call('helloworld')) time.sleep(1) + # continuosly spool a long running task @spoolforever def an_infinite_task(args): - for i in xrange(1,4): + for i in xrange(1, 4): print("infinite: %d %s" % (i, str(args))) print(uwsgi.call('helloworld')) uwsgi.signal(100) @@ -65,28 +70,33 @@ def delayed_task(args): # send a signal to all workers uwsgi.signal(100) + @spool def big_body_task(args): print("*** managing a task with a body of %d bytes ***" % len(args['body'])) - print(args['body'].swapcase()) + print(args['body'].swapcase()) + # run a task every hour @cron(59, -1, -1, -1, -1) def one_hour_passed(num): print("received signal %d after 1 hour" % num) + @thread def a_running_thread(): while True: time.sleep(2) print("i am a no-args thread") + @thread def a_running_thread_with_args(who): while True: time.sleep(2) print("Hello %s (from arged-thread)" % who) + @postfork @thread def a_post_fork_thread(): @@ -97,10 +107,12 @@ def a_post_fork_thread(): else: print("Hello from a thread in worker %d" % uwsgi.worker_id()) + @postfork def fork_happened(): print("fork() has been called [1]") + @postfork def fork_happened2(): if uwsgi.i_am_the_spooler(): @@ -110,6 +122,7 @@ def fork_happened2(): print("worker %d received signal %d" % (uwsgi.worker_id(), uwsgi.signal_received())) print("fork() has been called [2] wid: %d" % uwsgi.worker_id()) + @postfork @lock def locked_func(): @@ -120,7 +133,7 @@ def locked_func(): print("done with locked function on worker %d" % uwsgi.worker_id()) print(uwsgi.call('helloworld')) -spool_filename = a_long_task.spool({'foo':'bar'}, hello='world') +spool_filename = a_long_task.spool({'foo': 'bar'}, hello='world') print("spool filename = %s" % spool_filename) an_infinite_task.spool(foo='bar', priority=3) when = int(time.time())+5 @@ -128,6 +141,6 @@ print("scheduling a delayed task at %d" % when) delayed_task.spool(foo2='bar2', at=when) a_running_thread() a_running_thread_with_args("uWSGI") -uwsgi_source_file = open('uwsgi.c','r') -print(big_body_task.spool(priority=9,filename='uwsgi.c',body=uwsgi_source_file.read())) +uwsgi_source_file = open('uwsgi.c', 'r') +print(big_body_task.spool(priority=9, filename='uwsgi.c', body=uwsgi_source_file.read())) uwsgi_source_file.close() diff --git a/tests/fileserve_async.py b/tests/fileserve_async.py index 165b9c76..b51828a4 100644 --- a/tests/fileserve_async.py +++ b/tests/fileserve_async.py @@ -6,12 +6,12 @@ mimetypes.init() def application(environ, start_response): - - filename = basedir + environ['PATH_INFO'] - (content_type, encoding) = mimetypes.guess_type(filename) - if not content_type: - content_type = 'text/plain' - start_response('200 OK', [('Content-Type', content_type)]) - fd = open(filename,'r') - yield environ['wsgi.file_wrapper'](fd, 32*1024) + filename = basedir + environ['PATH_INFO'] + (content_type, encoding) = mimetypes.guess_type(filename) + if not content_type: + content_type = 'text/plain' + + start_response('200 OK', [('Content-Type', content_type)]) + fd = open(filename, 'r') + yield environ['wsgi.file_wrapper'](fd, 32*1024) diff --git a/tests/gevent_spool.py b/tests/gevent_spool.py index 22b2c340..bdf90363 100644 --- a/tests/gevent_spool.py +++ b/tests/gevent_spool.py @@ -1,17 +1,21 @@ from uwsgidecorators import * import gevent + @spool def longtask(*args): print args return uwsgi.SPOOL_OK + def level2(): - longtask.spool(foo='bar',test1='test2') + longtask.spool(foo='bar', test1='test2') + def level1(): gevent.spawn(level2) + def application(environ, start_response): start_response('200 OK', [('Content-Type', 'text/html')]) diff --git a/tests/grunter.py b/tests/grunter.py index b60f89ad..d3af2c77 100644 --- a/tests/grunter.py +++ b/tests/grunter.py @@ -1,22 +1,21 @@ import uwsgi import time + def application(env, start_response): - start_response('200 Ok', [ ('Content-Type','text/html') ] ) + start_response('200 Ok', [('Content-Type', 'text/html')]) - yield "I am the worker %d
" % uwsgi.worker_id() + yield "I am the worker %d
" % uwsgi.worker_id() - grunt = uwsgi.grunt() - - if grunt is None: - print "worker %d detached" % uwsgi.worker_id() - else: - yield "And now i am the grunt with a fix worker id of %d
" % uwsgi.worker_id() - time.sleep(2) - yield "Now, i will start a very slow task...
" - for i in xrange(1,10): - yield "waiting for %d seconds
" % i - time.sleep(i) - - + grunt = uwsgi.grunt() + + if grunt is None: + print "worker %d detached" % uwsgi.worker_id() + else: + yield "And now i am the grunt with a fix worker id of %d
" % uwsgi.worker_id() + time.sleep(2) + yield "Now, i will start a very slow task...
" + for i in xrange(1, 10): + yield "waiting for %d seconds
" % i + time.sleep(i) diff --git a/tests/iobound_async.py b/tests/iobound_async.py index be6062de..e990ddbc 100644 --- a/tests/iobound_async.py +++ b/tests/iobound_async.py @@ -1,43 +1,43 @@ import uwsgi + def send_request(env, client): - uwsgi.send(client, b"GET /intl/it_it/images/logo.gif HTTP/1.0\r\n") + uwsgi.send(client, b"GET /intl/it_it/images/logo.gif HTTP/1.0\r\n") - # test for suspend/resume - uwsgi.suspend() + # test for suspend/resume + uwsgi.suspend() - uwsgi.send(client, b"Host: www.google.it\r\n\r\n") + uwsgi.send(client, b"Host: www.google.it\r\n\r\n") + while 1: + yield uwsgi.wait_fd_read(client, 2) + if env['x-wsgiorg.fdevent.timeout']: + return - while 1: - yield uwsgi.wait_fd_read(client, 2) - if env['x-wsgiorg.fdevent.timeout']: - return - - buf = uwsgi.recv(client, 4096) - if buf: - yield buf - else: - break + buf = uwsgi.recv(client, 4096) + if buf: + yield buf + else: + break def application(env, start_response): - c = uwsgi.async_connect('74.125.232.115:80') + c = uwsgi.async_connect('74.125.232.115:80') - # wait for connection - yield uwsgi.wait_fd_write(c, 2) - - if env['x-wsgiorg.fdevent.timeout']: - uwsgi.close(c) - raise StopIteration + # wait for connection + yield uwsgi.wait_fd_write(c, 2) - if uwsgi.is_connected(c): - for r in send_request(env, c): - yield r - else: - start_response( '500 Internal Server Error', [ ('Content-Type', 'text/html')]) - yield "Internal Server Error" + if env['x-wsgiorg.fdevent.timeout']: + uwsgi.close(c) + raise StopIteration - uwsgi.close(c) + if uwsgi.is_connected(c): + for r in send_request(env, c): + yield r + else: + start_response('500 Internal Server Error', [('Content-Type', 'text/html')]) + yield "Internal Server Error" + + uwsgi.close(c) diff --git a/tests/iobound_async_unix.py b/tests/iobound_async_unix.py index a5432204..8fb23e78 100644 --- a/tests/iobound_async_unix.py +++ b/tests/iobound_async_unix.py @@ -1,51 +1,51 @@ import socket -import select import errno import struct + def send_request(env, client): - client.setblocking(1) + client.setblocking(1) - data = "hello world\r\n" - - # send uwsgi-echo header - client.send(struct.pack('I am Mako at ${thetime}") - uwsgi.green_schedule() + mytemplate = Template("

I am Mako at ${thetime}

") + uwsgi.green_schedule() - yield mytemplate.render(thetime = time.time() ) + yield mytemplate.render(thetime=time.time()) - for i in range(1, 100): - mytemplate = Template("Iteration ${thei} at ${thetime}
") - uwsgi.green_schedule() - yield mytemplate.render(thei = i, thetime = time.time() ) - + for i in range(1, 100): + mytemplate = Template("Iteration ${thei} at ${thetime}
") + uwsgi.green_schedule() + yield mytemplate.render(thei=i, thetime=time.time()) diff --git a/tests/mulefunc.py b/tests/mulefunc.py index 6bacfafd..a05bebb2 100644 --- a/tests/mulefunc.py +++ b/tests/mulefunc.py @@ -1,5 +1,6 @@ from uwsgidecorators import * + @timer(3, target='mule1') def hello_timer(signum): print "3 seconds elapsed" @@ -7,21 +8,22 @@ def hello_timer(signum): @mulefunc def conto_fino_a_dieci(uno, due, tre): - print "MULE ID %d: conto_fino_a_dieci" % uwsgi.mule_id(),uno,due,tre + print "MULE ID %d: conto_fino_a_dieci" % uwsgi.mule_id(), uno, due, tre + @mulefunc(2) def conto_fino_a_venti(uno, due, tre): - print "MULE ID %d: conto_fino_a_venti" % uwsgi.mule_id(),uno,due,tre + print "MULE ID %d: conto_fino_a_venti" % uwsgi.mule_id(), uno, due, tre + @mulefunc('topogigio') def conto_fino_a_trenta(uno, due, tre): - print "MULE ID %d: conto_fino_a_trenta" % uwsgi.mule_id(),uno,due,tre - + print "MULE ID %d: conto_fino_a_trenta" % uwsgi.mule_id(), uno, due, tre def application(e, sr): - conto_fino_a_dieci(1,2,3) - conto_fino_a_venti(4,5,6) - conto_fino_a_trenta(7,8,9) - sr('200 OK', [('Content-Type','text/html')]) - return "MULE !!!" + conto_fino_a_dieci(1, 2, 3) + conto_fino_a_venti(4, 5, 6) + conto_fino_a_trenta(7, 8, 9) + sr('200 OK', [('Content-Type', 'text/html')]) + return "MULE !!!" diff --git a/tests/myadmin.py b/tests/myadmin.py index af5d5a7d..f05df27c 100644 --- a/tests/myadmin.py +++ b/tests/myadmin.py @@ -4,14 +4,13 @@ import sys print sys.argv if len(sys.argv) == 3: - chunks = uwsgi.send_message(sys.argv[1], 10, int(sys.argv[2]), '') + chunks = uwsgi.send_message(sys.argv[1], 10, int(sys.argv[2]), '') - pkt = '' + pkt = '' - for chunk in chunks: - pkt += chunk + for chunk in chunks: + pkt += chunk - print "%d = %d" % (int(sys.argv[2]), struct.unpack("I", pkt)[0]) + print "%d = %d" % (int(sys.argv[2]), struct.unpack("I", pkt)[0]) elif len(sys.argv) == 4: - uwsgi.send_message(sys.argv[1], 10, int(sys.argv[2]), struct.pack("I", int(sys.argv[3]))) - + uwsgi.send_message(sys.argv[1], 10, int(sys.argv[2]), struct.pack("I", int(sys.argv[3]))) diff --git a/tests/pgbound_async.py b/tests/pgbound_async.py index ec160758..b7d6101c 100644 --- a/tests/pgbound_async.py +++ b/tests/pgbound_async.py @@ -1,38 +1,39 @@ import psycopg2 + def pg_wait(conn, env, timeout=0): - while 1: - state = conn.poll() - if state == psycopg2.extensions.POLL_OK: - raise StopIteration - elif state == psycopg2.extensions.POLL_WRITE: - yield env['x-wsgiorg.fdevent.writable'](conn.fileno(), timeout) - elif state == psycopg2.extensions.POLL_READ: - yield env['x-wsgiorg.fdevent.readable'](conn.fileno(), timeout) - else: - raise psycopg2.OperationalError("poll() returned %s" % state) + while 1: + state = conn.poll() + if state == psycopg2.extensions.POLL_OK: + raise StopIteration + elif state == psycopg2.extensions.POLL_WRITE: + yield env['x-wsgiorg.fdevent.writable'](conn.fileno(), timeout) + elif state == psycopg2.extensions.POLL_READ: + yield env['x-wsgiorg.fdevent.readable'](conn.fileno(), timeout) + else: + raise psycopg2.OperationalError("poll() returned %s" % state) def application(env, start_response): - start_response('200 OK', [('Content-Type', 'text/html')]) + start_response('200 OK', [('Content-Type', 'text/html')]) - connection = psycopg2.connect(database='uwsgi',user='uwsgi',password='uwsgi',host='192.168.173.100', async=1) + connection = psycopg2.connect(database='uwsgi', user='uwsgi', password='uwsgi', host='192.168.173.100', async=1) - for i in pg_wait(connection, env, 3): - yield i + for i in pg_wait(connection, env, 3): + yield i - print "connected" - cursor = connection.cursor() + print "connected" + cursor = connection.cursor() - cursor.execute("SELECT * FROM foo") + cursor.execute("SELECT * FROM foo") - for i in pg_wait(cursor.connection, env, 3): - yield i + for i in pg_wait(cursor.connection, env, 3): + yield i - print "query result available" + print "query result available" - for record in cursor: - yield str(record) + for record in cursor: + yield str(record) - connection.close() + connection.close() diff --git a/tests/picazzo.py b/tests/picazzo.py index 8bdc65f8..87e19743 100644 --- a/tests/picazzo.py +++ b/tests/picazzo.py @@ -1,22 +1,26 @@ from picasso import * + def home(req): - if not req["session"].get("user"): - return redirect("/login") - return "

Welcome back, %s!

" % req["session"]["user"] + if not req["session"].get("user"): + return redirect("/login") + return "

Welcome back, %s!

" % req["session"]["user"] + def login(req): - return "
" + return "
" + def login_post(req): - print req - req["session"]["user"] = "James" - return redirect("/") + print req + req["session"]["user"] = "James" + return redirect("/") routes = setup_routes( - GET("/", home), - GET("/login", login), - POST("/login", login_post), - routing.not_found("

Not Found

")) + GET("/", home), + GET("/login", login), + POST("/login", login_post), + routing.not_found("

Not Found

") +) app = setup_app(routes) diff --git a/tests/psycogreen_green.py b/tests/psycogreen_green.py index a3527a91..6515a140 100644 --- a/tests/psycogreen_green.py +++ b/tests/psycogreen_green.py @@ -3,19 +3,18 @@ import psycopg2 def ugreen_wait_callback(conn, timeout=-1): - """A wait callback useful to allow uWSGI/uGreen to work with Psycopg.""" - while True: - state = conn.poll() - if state == psycopg2.extensions.POLL_OK: - break - elif state == psycopg2.extensions.POLL_READ: - uwsgi.green_wait_fdread(conn.fileno()) - elif state == psycopg2.extensions.POLL_WRITE: - uwsgi.green_wait_fdwrite(conn.fileno()) - else: - raise Exception("Unexpected result from poll: %r", state) + """A wait callback useful to allow uWSGI/uGreen to work with Psycopg.""" + while True: + state = conn.poll() + if state == psycopg2.extensions.POLL_OK: + break + elif state == psycopg2.extensions.POLL_READ: + uwsgi.green_wait_fdread(conn.fileno()) + elif state == psycopg2.extensions.POLL_WRITE: + uwsgi.green_wait_fdwrite(conn.fileno()) + else: + raise Exception("Unexpected result from poll: %r", state) - # set the wait callback psycopg2.extensions.set_wait_callback(ugreen_wait_callback) @@ -23,23 +22,24 @@ psycopg2.extensions.set_wait_callback(ugreen_wait_callback) def application(env, start_response): - start_response('200 Ok', [('Content-type', 'text/html')]) + start_response('200 Ok', [('Content-type', 'text/html')]) - # connect - conn = psycopg2.connect("dbname=prova user=postgres") - # get cursor - curs = conn.cursor() + # connect + conn = psycopg2.connect("dbname=prova user=postgres") + # get cursor + curs = conn.cursor() - yield "" + yield "
" - # run query - curs.execute("SELECT * FROM tests") + # run query + curs.execute("SELECT * FROM tests") - while True: - row = curs.fetchone() - if not row: break - yield "" % str(row) + while True: + row = curs.fetchone() + if not row: + break + yield "" % str(row) - yield "
%s
%s
" + yield "" - conn.close() + conn.close() diff --git a/tests/psycopg2_green.py b/tests/psycopg2_green.py index 328f4a80..11cd1490 100644 --- a/tests/psycopg2_green.py +++ b/tests/psycopg2_green.py @@ -2,52 +2,51 @@ import uwsgi import psycopg2 + def async_wait(conn): - # conn can be a connection or a cursor - if not hasattr(conn, 'poll'): - conn = conn.connection - - # interesting part: suspend until ready - while True: - state = conn.poll() - if state == psycopg2.extensions.POLL_OK: - break - elif state == psycopg2.extensions.POLL_READ: - uwsgi.wait_fd_read(conn.fileno()) - uwsgi.suspend() - elif state == psycopg2.extensions.POLL_WRITE: - uwsgi.wait_fd_write(conn.fileno()) - uwsgi.suspend() - else: - raise Exception("Unexpected result from poll: %r", state) - - + # conn can be a connection or a cursor + if not hasattr(conn, 'poll'): + conn = conn.connection + # interesting part: suspend until ready + while True: + state = conn.poll() + if state == psycopg2.extensions.POLL_OK: + break + elif state == psycopg2.extensions.POLL_READ: + uwsgi.wait_fd_read(conn.fileno()) + uwsgi.suspend() + elif state == psycopg2.extensions.POLL_WRITE: + uwsgi.wait_fd_write(conn.fileno()) + uwsgi.suspend() + else: + raise Exception("Unexpected result from poll: %r", state) def application(env, start_response): - start_response('200 Ok', [('Content-type', 'text/html')]) + start_response('200 Ok', [('Content-type', 'text/html')]) - conn = psycopg2.connect("dbname=template1 user=postgres", async=True) + conn = psycopg2.connect("dbname=template1 user=postgres", async=True) - # suspend until connection - async_wait(conn) + # suspend until connection + async_wait(conn) - curs = conn.cursor() + curs = conn.cursor() - yield "" + yield "
" - curs.execute("SELECT * FROM tests") + curs.execute("SELECT * FROM tests") - # suspend until result - async_wait(curs) + # suspend until result + async_wait(curs) - while True: - row = curs.fetchone() - if not row: break - yield "" % str(row) + while True: + row = curs.fetchone() + if not row: + break + yield "" % str(row) - yield "
%s
%s
" + yield "" - conn.close() + conn.close() diff --git a/tests/pump.py b/tests/pump.py index b6c6e360..c35ebfee 100644 --- a/tests/pump.py +++ b/tests/pump.py @@ -1,7 +1,12 @@ def app(req): - print(req) - ret = {"status": 200, - "headers": {"content_type": "text/html", "foo":['bar0','bar1','bar2']}, - "body": "

Hello!

"} - print(ret) - return ret + print(req) + ret = { + "status": 200, + "headers": { + "content_type": "text/html", + "foo": ['bar0', 'bar1', 'bar2'] + }, + "body": "

Hello!

", + } + print(ret) + return ret diff --git a/tests/queue.py b/tests/queue.py index f7332ae2..3947dbd6 100644 --- a/tests/queue.py +++ b/tests/queue.py @@ -2,17 +2,18 @@ import uwsgi import os -from flask import Flask,render_template,request,redirect,flash +from flask import Flask, render_template, request, redirect, flash app = Flask(__name__) app.debug = True app.secret_key = os.urandom(24) + @app.route('/') def index(): - return render_template('queue.html', uwsgi=uwsgi) + @app.route('/push', methods=['POST']) def push_item(): if uwsgi.queue_push(request.form['body']): @@ -22,19 +23,22 @@ def push_item(): flash('unable to enqueue item') return render_template('queue.html', uwsgi=uwsgi) + @app.route('/get', methods=['POST']) def get_item(): - flash( "slot %s value = %s" % (request.form['slot'], uwsgi.queue_get( int(request.form['slot']) ))) + flash("slot %s value = %s" % (request.form['slot'], uwsgi.queue_get(int(request.form['slot'])))) return redirect('/') + @app.route('/pop', methods=['POST']) def pop_item(): - flash( "popped value = %s" % uwsgi.queue_pop() ) + flash("popped value = %s" % uwsgi.queue_pop()) return redirect('/') + @app.route('/pull', methods=['POST']) def pull_item(): - flash( "pulled value = %s" % uwsgi.queue_pull() ) + flash("pulled value = %s" % uwsgi.queue_pull()) return redirect('/') diff --git a/tests/refcount.py b/tests/refcount.py index 9b8fe5ce..c83085f4 100644 --- a/tests/refcount.py +++ b/tests/refcount.py @@ -1,6 +1,7 @@ import sys + def application(e, sr): - sr('200 OK', [('Content-Type','text/html')]) + sr('200 OK', [('Content-Type', 'text/html')]) print sys.gettotalrefcount() yield '%s' % sys.gettotalrefcount() diff --git a/tests/runningthread.py b/tests/runningthread.py index c13f7ca1..dfed522c 100644 --- a/tests/runningthread.py +++ b/tests/runningthread.py @@ -2,6 +2,7 @@ from threading import Thread import time import uwsgi + def mess(): while True: for i in xrange(0, 100): diff --git a/tests/sharedarea.py b/tests/sharedarea.py index 1d8f2c4e..1c0de336 100644 --- a/tests/sharedarea.py +++ b/tests/sharedarea.py @@ -2,9 +2,10 @@ import uwsgi uwsgi.sharedarea_writelong(173, 30) + def application(e, sr): - sr('200 Ok', [('Content-Type','text/html')]) + sr('200 Ok', [('Content-Type', 'text/html')]) uwsgi.sharedarea_write(17, e['REQUEST_URI']) diff --git a/tests/signals.py b/tests/signals.py index 4377768c..4a2e8592 100644 --- a/tests/signals.py +++ b/tests/signals.py @@ -2,18 +2,21 @@ import uwsgi def hello_signal(num, payload): - print "i am the signal %d" % num + print "i am the signal %d" % num + def hello_signal2(num, payload): - print "i am the signal %d with payload: %s" % (num, payload) + print "i am the signal %d with payload: %s" % (num, payload) + def hello_file(num, filename): - print "file %s has been modified !!!" % filename + print "file %s has been modified !!!" % filename + def hello_timer(num, secs): - print "%s seconds elapsed" % secs + print "%s seconds elapsed" % secs -#uwsgi.register_signal(30, uwsgi.SIGNAL_KIND_WORKER, hello_signal) +# uwsgi.register_signal(30, uwsgi.SIGNAL_KIND_WORKER, hello_signal) uwsgi.register_signal(30, "workers", hello_signal) uwsgi.register_signal(22, "worker", hello_signal2, "*** PAYLOAD FOO ***") @@ -25,10 +28,10 @@ uwsgi.register_timer(5, 8, "worker3", hello_timer) def application(env, start_response): - start_response('200 Ok', [('Content-Type', 'text/html')] ) + start_response('200 Ok', [('Content-Type', 'text/html')]) - # this will send a signal to the master that will report it to the first available worker - uwsgi.signal(30) - uwsgi.signal(22) + # this will send a signal to the master that will report it to the first available worker + uwsgi.signal(30) + uwsgi.signal(22) - return "signals sent to workers" + return "signals sent to workers" diff --git a/tests/sigwait.py b/tests/sigwait.py index 30001847..2d60e80d 100644 --- a/tests/sigwait.py +++ b/tests/sigwait.py @@ -1,14 +1,17 @@ import uwsgi from uwsgidecorators import * + @signal(17, target='workers') def hello(signum): print("I AM THE WORKER %d" % uwsgi.worker_id()) + @signal(30, target='worker2') def hello2(signum): print("I AM THE WORKER 2") + @postfork def wait_for_signal(): if uwsgi.worker_id() != 2: @@ -25,4 +28,3 @@ def application(e, s): else: uwsgi.signal(17) return "Signal raised" - diff --git a/tests/sleeping_async.py b/tests/sleeping_async.py index ef7c8752..7a5d536a 100644 --- a/tests/sleeping_async.py +++ b/tests/sleeping_async.py @@ -2,8 +2,9 @@ import uwsgi sleepvalue = 5 + def application(env, start_response): start_response('200 Ok', [('Content-type', 'text/html')]) yield uwsgi.async_sleep(sleepvalue) - #print "TIMEOUT: ", env['x-wsgiorg.fdevent.timeout'] + # print "TIMEOUT: ", env['x-wsgiorg.fdevent.timeout'] yield "

Hello World after %d seconds

" % sleepvalue diff --git a/tests/sleeping_green.py b/tests/sleeping_green.py index 7e2ac2d2..df9ee8a5 100644 --- a/tests/sleeping_green.py +++ b/tests/sleeping_green.py @@ -4,11 +4,11 @@ import time def application(env, start_response): sleepvalue = 5 - if env.has_key('QUERY_STRING'): + if 'QUERY_STRING' in env: if env['QUERY_STRING'] != '': sleepvalue = int(env['QUERY_STRING']) start_response('200 Ok', [('Content-type', 'text/html')]) start_at = time.time() uwsgi.green_sleep(sleepvalue) - #print "TIMEOUT: ", env['x-wsgiorg.fdevent.timeout'] + # print "TIMEOUT: ", env['x-wsgiorg.fdevent.timeout'] yield "

Hello World after %s seconds

" % str(time.time() - start_at) diff --git a/tests/sleepthreadasync.py b/tests/sleepthreadasync.py index ebc759a5..5795099f 100644 --- a/tests/sleepthreadasync.py +++ b/tests/sleepthreadasync.py @@ -2,17 +2,19 @@ import uwsgi import threading import time + def foo(): while True: time.sleep(1) print "ciao, sono un thread" t = threading.Thread(target=foo) -t.daemon=True +t.daemon = True t.start() + + def application(e, s): - s('200 OK', [('Content-Type','text/html')]) - for i in range(0,3): + s('200 OK', [('Content-Type', 'text/html')]) + for i in range(0, 3): yield uwsgi.async_sleep(1) yield "iter: %d
" % i - diff --git a/tests/slow.py b/tests/slow.py index d762d8eb..61ca5d5b 100644 --- a/tests/slow.py +++ b/tests/slow.py @@ -1,12 +1,13 @@ import time import uwsgi -def application(e,s): + + +def application(e, s): print "locking" uwsgi.lock() print "locked" time.sleep(3) uwsgi.unlock() print "UN-locked" - s('200 OK', [('Content-Type','text/html')]) + s('200 OK', [('Content-Type', 'text/html')]) return "slow" - diff --git a/tests/spoolme.py b/tests/spoolme.py index 95ea8c32..306b8d43 100644 --- a/tests/spoolme.py +++ b/tests/spoolme.py @@ -1,6 +1,7 @@ import uwsgi import time + def slow_task(args): time.sleep(10) return uwsgi.SPOOL_OK @@ -8,12 +9,17 @@ def slow_task(args): uwsgi.spooler = slow_task - def application(env, start_response): - name = uwsgi.spool({'Hello':'World', 'I am a':'long running task'}) + name = uwsgi.spool({ + 'Hello': 'World', + 'I am a': 'long running task' + }) print("spooled as %s" % name) - start_response('200 Ok', [('Content-Type','text/plain'),('uWSGI-Status', 'spooled')]) + start_response('200 Ok', [ + ('Content-Type', 'text/plain'), + ('uWSGI-Status', 'spooled'), + ]) return "task spooled" diff --git a/tests/staticfile.py b/tests/staticfile.py index 46eee8bf..52e808a5 100644 --- a/tests/staticfile.py +++ b/tests/staticfile.py @@ -1,5 +1,4 @@ import sys -import uwsgi content_type = 'image/png' filename = 'logo_uWSGI.png' @@ -14,7 +13,8 @@ try: except: pass + def application(environ, start_response): start_response('200 OK', [('Content-Type', content_type)]) - fd = open(filename,'r') + fd = open(filename, 'r') yield environ['wsgi.file_wrapper'](fd, 32*1024) diff --git a/tests/testapp.py b/tests/testapp.py index cdee46a9..d76359d3 100644 --- a/tests/testapp.py +++ b/tests/testapp.py @@ -4,7 +4,7 @@ import time import sys import os -sys.path.insert(0,'/opt/apps') +sys.path.insert(0, '/opt/apps') os.environ['DJANGO_SETTINGS_MODULE'] = 'mysite.settings' @@ -14,6 +14,7 @@ os.environ['DJANGO_SETTINGS_MODULE'] = 'mysite.settings' from threading import Thread + class testthread(Thread): def run(self): while 1: @@ -30,44 +31,55 @@ p = "serena" #while 1: #print "MARSHALLED OUT: ",uwsgi.send_uwsgi_message("127.0.0.1", 3033, 33, 17, {'prodotto':p, 'tempo': time.time(), 'pippo':'pluto', 'topolino':'paperino', 'callable':4+1, 'nullo': None, 'embedded': {'a':1} }, 17) + def mako(filename, vars): return uwsgi.send_uwsgi_message("127.0.0.1", 3033, 33, 17, (filename, vars), 17) #print uwsgi.send_uwsgi_message("127.0.0.1", 3033, 33, 17, ('makotest.txt', {'whattimeisit':time.time(), 'roberta':'serena'}), 17) + def myspooler(env): print env - for i in range(1,100): + for i in range(1, 100): uwsgi.sharedarea_inclong(100) - #time.sleep(1) + # time.sleep(1) uwsgi.spooler = myspooler #print "SPOOLER: ", uwsgi.send_to_spooler({'TESTKEY':'TESTVALUE', 'APPNAME':'uWSGI'}) + def helloworld(): return 'Hello World' + def increment(): return "Shared counter is %d\n" % uwsgi.sharedarea_inclong(100) + def force_harakiri(): time.sleep(60) - def application(env, start_response): print env start_response('200 OK', [('Content-Type', 'text/plain')]) - yield { '/': helloworld, '/sleep': force_harakiri, '/counter': increment, '/uwsgi/':helloworld }[env['PATH_INFO']]() + yield { + '/': helloworld, + '/sleep': force_harakiri, + '/counter': increment, + '/uwsgi/': helloworld + }[env['PATH_INFO']]() print env + def gomako(): from mako.template import Template uwsgi.start_response('200 OK', [('Content-Type', 'text/html')]) yield Template("hello ${data}!").render(data="world") + def goxml(): import xml.dom.minidom doc = xml.dom.minidom.Document() @@ -76,16 +88,18 @@ def goxml(): uwsgi.start_response('200 OK', [('Content-Type', 'text/xml')]) return doc.toxml() + def djangohomepage(): from django.template import Template, Context uwsgi.start_response('200 OK', [('Content-Type', 'text/html')]) t = Template("My name is {{ my_name }}.") c = Context({"my_name": "Serena"}) - print t,c + print t, c a = t.render(c) print "ciao", a yield str(a) + def reload(env, start_response): start_response('200 OK', [('Content-Type', 'text/html')]) @@ -120,7 +134,7 @@ def reload(env, start_response): # yield 4/0 - yield '

uWSGI status ('+env['SCRIPT_NAME']+')

'; + yield '

uWSGI status ('+env['SCRIPT_NAME']+')

' yield 'masterpid: ' + str(uwsgi.masterpid()) + '
' yield 'started on: ' + time.ctime(uwsgi.started_on) + '
' @@ -134,7 +148,7 @@ def reload(env, start_response): yield '' yield '' - workers = uwsgi.workers(); + workers = uwsgi.workers() yield '

workers

' @@ -142,7 +156,7 @@ def reload(env, start_response): #print w #print w['running_time'] if w is not None: - yield '' + yield '' print w yield '
worker idpidin requestrequestsrunning timeaddress spacerss
'+ str(w['id']) +'' + str(w['pid']) + '' + str(w['pid']) + '' + str(w['requests']) + '' + str(w['running_time']) + '' + str(w['vsz']) + '' + str(w['rss']) + '
' + str(w['id']) + '' + str(w['pid']) + '' + str(w['pid']) + '' + str(w['requests']) + '' + str(w['running_time']) + '' + str(w['vsz']) + '' + str(w['rss']) + '
' @@ -150,18 +164,24 @@ def reload(env, start_response): #yield out #print "FATTOfattoFATTO" + def remotemako(env, start_response): start_response('200 OK', [('Content-Type', 'text/html')]) - clusters = ( ('192.168.173.5', 3431, [0,3000] ), - ('192.168.173.5', 3432, [3001, 6000] ), - ('192.168.173.5', 3433, [6001, 9000] ), - ('192.168.173.5', 3434, [9001, 12000] ), - ('192.168.173.5', 3435, [12001, 15000] ) - ); + clusters = ( + ('192.168.173.5', 3431, [0, 3000]), + ('192.168.173.5', 3432, [3001, 6000]), + ('192.168.173.5', 3433, [6001, 9000]), + ('192.168.173.5', 3434, [9001, 12000]), + ('192.168.173.5', 3435, [12001, 15000]) + ) print clusters - all_values = uwsgi.send_multi_uwsgi_message(clusters, 33, 17, 40); + all_values = uwsgi.send_multi_uwsgi_message(clusters, 33, 17, 40) print all_values - return mako('makotest.txt', {'whattimeisit':time.time(), 'roberta':'serena', 'cluster_values': all_values}) + return mako('makotest.txt', { + 'whattimeisit': time.time(), + 'roberta': 'serena', + 'cluster_values': all_values + }) uwsgi.fastfuncs.insert(10, gomako) @@ -171,7 +191,10 @@ uwsgi.fastfuncs.insert(17, djangohomepage) #djangoapp = django.core.handlers.wsgi.WSGIHandler() #applications = { '/':django.core.handlers.wsgi.WSGIHandler() } -uwsgi.applications = { '/':reload, '/pippo':reload } +uwsgi.applications = { + '/': reload, + '/pippo': reload +} print uwsgi.applications print uwsgi.applist diff --git a/tests/testgevent.py b/tests/testgevent.py index b0b64175..53849abf 100644 --- a/tests/testgevent.py +++ b/tests/testgevent.py @@ -4,16 +4,19 @@ import gevent import uwsgi import time + def microtask(wid): print "i am a gevent task" gevent.sleep(10) print "10 seconds elapsed in worker id %d" % wid + def athread(): while True: time.sleep(1) print "i am the thread 1" + def athread2(): while True: time.sleep(1) @@ -27,13 +30,13 @@ t2 = Thread(target=athread2) t2.daemon = True t2.start() + def application(environ, start_response): gevent.sleep() - start_response('200 OK', [('Content-Type','text/html')]) + start_response('200 OK', [('Content-Type', 'text/html')]) yield "sleeping for 3 seconds...
" gevent.sleep(3) yield "done
" gevent.spawn(microtask, uwsgi.worker_id()) yield "microtask started
" - diff --git a/tests/testpy3.py b/tests/testpy3.py index 6cd90229..f08f5c44 100644 --- a/tests/testpy3.py +++ b/tests/testpy3.py @@ -1,13 +1,15 @@ import uwsgi + def app1(e, sr): print(e) - sr('200 Ok', [('Content-Type','text/plain')]) + sr('200 Ok', [('Content-Type', 'text/plain')]) return b'i Am a Python 3.x bytestring' + def app2(e, sr): print(e) - sr('404 Not Found', [('Content-Type','text/plain')]) + sr('404 Not Found', [('Content-Type', 'text/plain')]) return b'i Am a Python 3.x Not Found page' uwsgi.applications = {b'': app1, b'/test': app2} diff --git a/tests/testsignals.py b/tests/testsignals.py index 1e9486ec..4beb6cc3 100644 --- a/tests/testsignals.py +++ b/tests/testsignals.py @@ -1,9 +1,9 @@ import uwsgi # send a raw signal to register with file_monitor subsystem -#uwsgi.signal(10, "/tmp/topolino") +# uwsgi.signal(10, "/tmp/topolino") uwsgi.signal(10, "/tmp") -#uwsgi.signal(10, "/root") +# uwsgi.signal(10, "/root") # send a raw signal to register with timer subsystem uwsgi.signal(11, "3") diff --git a/tests/threads.py b/tests/threads.py index 9c623c3a..be3dcffd 100644 --- a/tests/threads.py +++ b/tests/threads.py @@ -3,32 +3,36 @@ import threading import time import sys + def monitor1(): - while 1: - time.sleep(1) - print("i am the monitor 1") + while 1: + time.sleep(1) + print("i am the monitor 1") + def monitor2(): - while 1: - time.sleep(2) - print("i am the monitor 2") - print(sys.modules) + while 1: + time.sleep(2) + print("i am the monitor 2") + print(sys.modules) + def monitor3(): - while 1: - time.sleep(5) - print("5 seconds elapsed") - #reload(fake) - + while 1: + time.sleep(5) + print("5 seconds elapsed") + # reload(fake) + + def spawn_my_magic_threads(): - print("^^^ spawning magic threads ^^^") - t = threading.Thread(target=monitor1).start() - t2 = threading.Thread(target=monitor2).start() - t3 = threading.Thread(target=monitor3).start() + print("^^^ spawning magic threads ^^^") + threading.Thread(target=monitor1).start() + threading.Thread(target=monitor2).start() + threading.Thread(target=monitor3).start() uwsgi.post_fork_hook = spawn_my_magic_threads def application(e, s): - s('200 Ok', [('Content-Type','text/html')]) - return "Hello Threaded World !!!" + s('200 Ok', [('Content-Type', 'text/html')]) + return "Hello Threaded World !!!" diff --git a/tests/ugevent.py b/tests/ugevent.py index 4e520e51..bb03a1b2 100644 --- a/tests/ugevent.py +++ b/tests/ugevent.py @@ -2,47 +2,53 @@ import gevent import gevent.socket import sys import uwsgi -from uwsgidecorators import * +from uwsgidecorators import timer, signal, filemon if 'gettotalrefcount' in sys.__dict__: REFCNT = True else: REFCNT = False + @signal(17) def hello(signum): print "hello i am signal %d, i am here because the background job is finished" % signum if REFCNT: print sys.gettotalrefcount() + @timer(10) def ten_seconds(signum): print "10 seconds elapsed, signal %d raised" % signum if REFCNT: print sys.gettotalrefcount() + @filemon('/tmp') def tmp_modified(signum): print "/tmp has been touched, i am the greenlet %s running on worker %d" % (gevent.getcurrent(), uwsgi.worker_id()) if REFCNT: print sys.gettotalrefcount() + def bg_task(): - for i in range(1,10): + for i in range(1, 10): print "background task", i gevent.sleep(1) # task ended raise a signal !!! uwsgi.signal(17) + def long_task(): - for i in range(1,10): + for i in range(1, 10): print i gevent.sleep() + def application(e, sr): - sr('200 OK', [('Content-Type','text/html')]) + sr('200 OK', [('Content-Type', 'text/html')]) t = gevent.spawn(long_task) diff --git a/tests/websockets.py b/tests/websockets.py index 8f57e1aa..2ecb435b 100644 --- a/tests/websockets.py +++ b/tests/websockets.py @@ -6,6 +6,7 @@ from gevent.socket import wait_read queue = JoinableQueue() + def application(env, sr): ws_scheme = 'ws' @@ -13,7 +14,7 @@ def application(env, sr): ws_scheme = 'wss' if env['PATH_INFO'] == '/': - sr('200 OK', [('Content-Type','text/html')]) + sr('200 OK', [('Content-Type', 'text/html')]) return """ @@ -24,18 +25,18 @@ def application(env, sr): s.send("ciao"); }; s.onmessage = function(e) { - var bb = document.getElementById('blackboard') - var html = bb.innerHTML; - bb.innerHTML = html + '
' + e.data; + var bb = document.getElementById('blackboard') + var html = bb.innerHTML; + bb.innerHTML = html + '
' + e.data; }; - s.onerror = function(e) { - alert(e); - } + s.onerror = function(e) { + alert(e); + } - s.onclose = function(e) { - alert("connection closed"); - } + s.onclose = function(e) { + alert("connection closed"); + } function invia() { var value = document.getElementById('testo').value; @@ -47,13 +48,13 @@ def application(env, sr):

WebSocket

-
-
+
+
""" % (ws_scheme, env['HTTP_HOST']) elif env['PATH_INFO'] == '/foobar/': - uwsgi.websocket_handshake(env['HTTP_SEC_WEBSOCKET_KEY'], env.get('HTTP_ORIGIN', '')) + uwsgi.websocket_handshake(env['HTTP_SEC_WEBSOCKET_KEY'], env.get('HTTP_ORIGIN', '')) print "websockets..." while True: msg = uwsgi.websocket_recv_nb() diff --git a/tests/websockets_chat.py b/tests/websockets_chat.py index d6f5d70d..de91abf8 100644 --- a/tests/websockets_chat.py +++ b/tests/websockets_chat.py @@ -4,6 +4,7 @@ import time import gevent.select import redis + def application(env, sr): ws_scheme = 'ws' @@ -11,7 +12,7 @@ def application(env, sr): ws_scheme = 'wss' if env['PATH_INFO'] == '/': - sr('200 OK', [('Content-Type','text/html')]) + sr('200 OK', [('Content-Type', 'text/html')]) return """ @@ -22,18 +23,18 @@ def application(env, sr): s.send("ciao"); }; s.onmessage = function(e) { - var bb = document.getElementById('blackboard') - var html = bb.innerHTML; - bb.innerHTML = html + '
' + e.data; + var bb = document.getElementById('blackboard') + var html = bb.innerHTML; + bb.innerHTML = html + '
' + e.data; }; - s.onerror = function(e) { - alert(e); - } + s.onerror = function(e) { + alert(e); + } - s.onclose = function(e) { - alert("connection closed"); - } + s.onclose = function(e) { + alert("connection closed"); + } function invia() { var value = document.getElementById('testo').value; @@ -45,15 +46,15 @@ def application(env, sr):

WebSocket

-
-
+
+
""" % (ws_scheme, env['HTTP_HOST']) elif env['PATH_INFO'] == '/favicon.ico': return "" elif env['PATH_INFO'] == '/foobar/': - uwsgi.websocket_handshake(env['HTTP_SEC_WEBSOCKET_KEY'], env.get('HTTP_ORIGIN', '')) + uwsgi.websocket_handshake(env['HTTP_SEC_WEBSOCKET_KEY'], env.get('HTTP_ORIGIN', '')) print "websockets..." r = redis.StrictRedis(host='localhost', port=6379, db=0) channel = r.pubsub() @@ -61,7 +62,7 @@ def application(env, sr): websocket_fd = uwsgi.connection_fd() redis_fd = channel.connection._sock.fileno() - + while True: # wait max 4 seconds to allow ping to be sent ready = gevent.select.select([websocket_fd, redis_fd], [], [], 4.0) @@ -74,7 +75,7 @@ def application(env, sr): if msg: r.publish('foobar', msg) elif fd == redis_fd: - msg = channel.parse_response() + msg = channel.parse_response() # only interested in user messages if msg[0] == 'message': uwsgi.websocket_send("[%s] %s" % (time.time(), msg)) diff --git a/tests/websockets_chat_async.py b/tests/websockets_chat_async.py index 7e5fd834..bc054735 100644 --- a/tests/websockets_chat_async.py +++ b/tests/websockets_chat_async.py @@ -7,6 +7,7 @@ import time import redis import sys + def application(env, sr): ws_scheme = 'ws' @@ -14,7 +15,7 @@ def application(env, sr): ws_scheme = 'wss' if env['PATH_INFO'] == '/': - sr('200 OK', [('Content-Type','text/html')]) + sr('200 OK', [('Content-Type', 'text/html')]) output = """ @@ -25,18 +26,18 @@ def application(env, sr): s.send("ciao"); }; s.onmessage = function(e) { - var bb = document.getElementById('blackboard') - var html = bb.innerHTML; - bb.innerHTML = html + '
' + e.data; + var bb = document.getElementById('blackboard') + var html = bb.innerHTML; + bb.innerHTML = html + '
' + e.data; }; - s.onerror = function(e) { - alert(e); - } + s.onerror = function(e) { + alert(e); + } - s.onclose = function(e) { - alert("connection closed"); - } + s.onclose = function(e) { + alert("connection closed"); + } function invia() { var value = document.getElementById('testo').value; @@ -48,8 +49,8 @@ def application(env, sr):

WebSocket

-
-
+
+
""" % (ws_scheme, env['HTTP_HOST']) @@ -67,7 +68,7 @@ def application(env, sr): websocket_fd = uwsgi.connection_fd() redis_fd = channel.connection._sock.fileno() - + while True: uwsgi.wait_fd_read(websocket_fd, 3) uwsgi.wait_fd_read(redis_fd) @@ -79,7 +80,7 @@ def application(env, sr): if msg: r.publish('foobar', msg) elif fd == redis_fd: - msg = channel.parse_response() + msg = channel.parse_response() print(msg) # only interested in user messages t = 'message' diff --git a/tests/websockets_chat_asyncio.py b/tests/websockets_chat_asyncio.py index 78564f4e..849399e3 100644 --- a/tests/websockets_chat_asyncio.py +++ b/tests/websockets_chat_asyncio.py @@ -5,6 +5,7 @@ import asyncio_redis import time import greenlet + class GreenFuture(asyncio.Future): def __init__(self): super().__init__() @@ -16,36 +17,41 @@ class GreenFuture(asyncio.Future): if self.done(): return super().result() self.greenlet.parent.switch() - - + + @asyncio.coroutine def redis_open(f): connection = yield from asyncio_redis.Connection.create(host='localhost', port=6379) f.set_result(connection) f.greenlet.switch() + @asyncio.coroutine def redis_subscribe(f): - connection = yield from asyncio_redis.Connection.create(host='localhost', port=6379) + connection = yield from asyncio_redis.Connection.create(host='localhost', port=6379) subscriber = yield from connection.start_subscribe() - yield from subscriber.subscribe([ 'foobar' ]) + yield from subscriber.subscribe(['foobar']) f.set_result(subscriber) f.greenlet.switch() + def ws_recv_msg(g): g.has_ws_msg = True g.switch() + @asyncio.coroutine def redis_wait(subscriber, f): reply = yield from subscriber.next_published() f.set_result(reply.value) f.greenlet.switch() + @asyncio.coroutine def redis_publish(connection, msg): yield from connection.publish('foobar', msg.decode('utf-8')) + def application(env, sr): ws_scheme = 'ws' @@ -53,7 +59,7 @@ def application(env, sr): ws_scheme = 'wss' if env['PATH_INFO'] == '/': - sr('200 OK', [('Content-Type','text/html')]) + sr('200 OK', [('Content-Type', 'text/html')]) return (""" @@ -64,18 +70,18 @@ def application(env, sr): s.send("ciao"); }; s.onmessage = function(e) { - var bb = document.getElementById('blackboard') - var html = bb.innerHTML; - bb.innerHTML = html + '
' + e.data; + var bb = document.getElementById('blackboard') + var html = bb.innerHTML; + bb.innerHTML = html + '
' + e.data; }; - s.onerror = function(e) { - alert(e); - } + s.onerror = function(e) { + alert(e); + } - s.onclose = function(e) { - alert("connection closed"); - } + s.onclose = function(e) { + alert("connection closed"); + } function invia() { var value = document.getElementById('testo').value; @@ -87,8 +93,8 @@ def application(env, sr):

WebSocket

-
-
+
+
""" % (ws_scheme, env['HTTP_HOST'])).encode() @@ -97,11 +103,11 @@ def application(env, sr): elif env['PATH_INFO'] == '/foobar/': uwsgi.websocket_handshake() print("websockets...") - # a future for waiting for redis connection + # a future for waiting for redis connection f = GreenFuture() asyncio.Task(redis_subscribe(f)) # the result() method will switch greenlets if needed - subscriber = f.result() + subscriber = f.result() # open another redis connection for publishing messages f0 = GreenFuture() @@ -135,6 +141,6 @@ def application(env, sr): myself.has_ws_msg = False msg = uwsgi.websocket_recv_nb() if msg: - asyncio.Task(redis_publish(connection, msg)) + asyncio.Task(redis_publish(connection, msg)) # switch again f.greenlet.parent.switch() diff --git a/tests/websockets_echo.py b/tests/websockets_echo.py index 9efce679..5db57cea 100644 --- a/tests/websockets_echo.py +++ b/tests/websockets_echo.py @@ -2,14 +2,15 @@ import uwsgi import time + def application(env, sr): - + ws_scheme = 'ws' if 'HTTPS' in env or env['wsgi.url_scheme'] == 'https': ws_scheme = 'wss' - + if env['PATH_INFO'] == '/': - sr('200 OK', [('Content-Type','text/html')]) + sr('200 OK', [('Content-Type', 'text/html')]) return """ @@ -24,15 +25,15 @@ def application(env, sr): var html = bb.innerHTML; bb.innerHTML = html + '
' + e.data; }; - + s.onerror = function(e) { alert(e); } - + s.onclose = function(e) { alert("connection closed"); } - + function invia() { var value = document.getElementById('testo').value; s.send(value); diff --git a/tests/werkzeug.py b/tests/werkzeug.py index 38cb69d6..c2496e94 100644 --- a/tests/werkzeug.py +++ b/tests/werkzeug.py @@ -2,4 +2,4 @@ import uwsgi print(uwsgi.opt) print(uwsgi.magic_table) -from werkzeug.testapp import test_app as application +from werkzeug.testapp import test_app as application # NOQA diff --git a/uwsgiconfig.py b/uwsgiconfig.py index f4bc2db2..77e1e968 100644 --- a/uwsgiconfig.py +++ b/uwsgiconfig.py @@ -12,7 +12,7 @@ uwsgi_cpu = os.uname()[4] import sys import subprocess -from threading import Thread,Lock +from threading import Thread, Lock from optparse import OptionParser try: @@ -31,6 +31,7 @@ GCC = os.environ.get('CC', sysconfig.get_config_var('CC')) if not GCC: GCC = 'gcc' + def get_preprocessor(): if 'clang' in GCC: return 'clang -xc core/clang_fake.c' @@ -56,7 +57,7 @@ if CPUCOUNT < 1: # force single cpu in cygwin mode if uwsgi_os.startswith('CYGWIN'): - CPUCOUNT=1 + CPUCOUNT = 1 binary_list = [] @@ -86,6 +87,7 @@ report = { verbose_build = False + def print_compilation_output(default_str, verbose_str): if verbose_build: print(verbose_str) @@ -96,31 +98,31 @@ compile_queue = None print_lock = None thread_compilers = [] + def thread_compiler(num): while True: (objfile, cmdline) = compile_queue.get() if objfile: print_lock.acquire() print_compilation_output("[thread %d][%s] %s" % (num, GCC, objfile), "[thread %d] %s" % (num, cmdline)) - print_lock.release() + print_lock.release() ret = os.system(cmdline) if ret != 0: os._exit(1) elif cmdline: - print_lock.acquire() + print_lock.acquire() print(cmdline) - print_lock.release() + print_lock.release() else: return - - def binarize(name): - return name.replace('/', '_').replace('.','_').replace('-','_') + return name.replace('/', '_').replace('.', '_').replace('-', '_') + def spcall(cmd): - p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE,stderr=open('uwsgibuild.log','w')) + p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=open('uwsgibuild.log', 'w')) if p.wait() == 0: if sys.version_info[0] > 2: @@ -129,19 +131,20 @@ def spcall(cmd): else: return None + # commodity function to remove -W* duplicates def uniq_warnings(elements): new_elements = [] for element in elements: if element.startswith('-W'): - if not element in new_elements: + if element not in new_elements: new_elements.append(element) else: new_elements.append(element) return new_elements -if uwsgi_version.endswith('-dev') and os.path.exists('%s/.git' % os.path.dirname(os.path.abspath( __file__ ))): +if uwsgi_version.endswith('-dev') and os.path.exists('%s/.git' % os.path.dirname(os.path.abspath(__file__))): try: uwsgi_version += '-%s' % spcall('git rev-parse --short HEAD') except: @@ -158,6 +161,7 @@ def spcall2(cmd): else: return None + def spcall3(cmd): p = subprocess.Popen(cmd, shell=True, stdin=open('/dev/null'), stderr=subprocess.PIPE, stdout=subprocess.PIPE) @@ -177,12 +181,14 @@ def add_o(x): x = x + '.o' return x + def push_print(msg): if not compile_queue: print(msg) else: compile_queue.put((None, msg)) + def push_command(objfile, cmdline): if not compile_queue: print_compilation_output("[%s] %s" % (GCC, objfile), cmdline) @@ -191,7 +197,7 @@ def push_command(objfile, cmdline): sys.exit(1) else: compile_queue.put((objfile, cmdline)) - + def compile(cflags, last_cflags_ts, objfile, srcfile): source_stat = os.stat(srcfile) @@ -227,8 +233,8 @@ def build_uwsgi(uc, print_only=False, gcll=None): if CPUCOUNT > 1: print_lock = Lock() compile_queue = Queue(maxsize=CPUCOUNT) - for i in range(0,CPUCOUNT): - t = Thread(target=thread_compiler,args=(i,)) + for i in range(0, CPUCOUNT): + t = Thread(target=thread_compiler, args=(i,)) t.daemon = True t.start() thread_compilers.append(t) @@ -284,21 +290,18 @@ def build_uwsgi(uc, print_only=False, gcll=None): uwsgi_cflags = ' '.join(cflags).encode('hex') last_cflags_ts = 0 - + if os.path.exists('uwsgibuild.lastcflags'): - ulc = open('uwsgibuild.lastcflags','r') - last_cflags = ulc.read() - ulc.close() - if uwsgi_cflags != last_cflags: - os.environ['UWSGI_FORCE_REBUILD'] = '1' - else: - last_cflags_ts = os.stat('uwsgibuild.lastcflags')[8] - - - ulc = open('uwsgibuild.lastcflags','w') - ulc.write(uwsgi_cflags) - ulc.close() + ulc = open('uwsgibuild.lastcflags', 'r') + last_cflags = ulc.read() + ulc.close() + if uwsgi_cflags != last_cflags: + os.environ['UWSGI_FORCE_REBUILD'] = '1' + else: + last_cflags_ts = os.stat('uwsgibuild.lastcflags')[8] + with open('uwsgibuild.lastcflags', 'w') as ulc: + ulc.write(uwsgi_cflags) # embed uwsgi.h in the server binary. It increases the binary size, but will be very useful # for various tricks (like cffi integration) @@ -316,8 +319,8 @@ def build_uwsgi(uc, print_only=False, gcll=None): uwsgi_dot_h = binascii.b2a_hex(uwsgi_dot_h_content).decode('ascii') else: uwsgi_dot_h = uwsgi_dot_h_content.encode('hex') - open('core/dot_h.c', 'w').write('char *uwsgi_dot_h = "%s";\n' % uwsgi_dot_h); - gcc_list.append('core/dot_h') + open('core/dot_h.c', 'w').write('char *uwsgi_dot_h = "%s";\n' % uwsgi_dot_h) + gcc_list.append('core/dot_h') # embed uwsgiconfig.py in the server binary. It increases the binary size, but will be very useful # if possibile, the blob is compressed @@ -334,7 +337,7 @@ def build_uwsgi(uc, print_only=False, gcll=None): uwsgi_config_py = binascii.b2a_hex(uwsgi_config_py_content).decode('ascii') else: uwsgi_config_py = uwsgi_config_py_content.encode('hex') - open('core/config_py.c', 'w').write('char *uwsgi_config_py = "%s";\n' % uwsgi_config_py); + open('core/config_py.c', 'w').write('char *uwsgi_config_py = "%s";\n' % uwsgi_config_py) gcc_list.append('core/config_py') additional_sources = os.environ.get('UWSGI_ADDITIONAL_SOURCES') @@ -343,7 +346,7 @@ def build_uwsgi(uc, print_only=False, gcll=None): if additional_sources: for item in additional_sources.split(','): gcc_list.append(item) - + cflags.append('-DUWSGI_CFLAGS=\\"%s\\"' % uwsgi_cflags) cflags.append('-DUWSGI_BUILD_DATE="\\"%s\\""' % time.strftime("%d %B %Y %H:%M:%S")) @@ -357,7 +360,7 @@ def build_uwsgi(uc, print_only=False, gcll=None): if not objfile.endswith('.a') and not objfile.endswith('.o'): if objfile.endswith('.c') or objfile.endswith('.cc') or objfile.endswith('.m') or objfile.endswith('.go'): if objfile.endswith('.go'): - cflags.append('-Wno-error') + cflags.append('-Wno-error') compile(' '.join(cflags), last_cflags_ts, objfile + '.o', file) if objfile.endswith('.go'): cflags.pop() @@ -438,13 +441,13 @@ def build_uwsgi(uc, print_only=False, gcll=None): gcc_list.append('%s/%s' % (path, cfile)) elif not cfile.endswith('.c') and not cfile.endswith('.cc') and not cfile.endswith('.go') and not cfile.endswith('.m'): compile(' '.join(uniq_warnings(p_cflags)), last_cflags_ts, - path + '/' + cfile + '.o', path + '/' + cfile + '.c') + path + '/' + cfile + '.o', path + '/' + cfile + '.c') gcc_list.append('%s/%s' % (path, cfile)) else: if cfile.endswith('.go'): p_cflags.append('-Wno-error') compile(' '.join(uniq_warnings(p_cflags)), last_cflags_ts, - path + '/' + cfile + '.o', path + '/' + cfile) + path + '/' + cfile + '.o', path + '/' + cfile) gcc_list.append('%s/%s' % (path, cfile)) for bfile in up.get('BINARY_LIST', []): try: @@ -452,7 +455,7 @@ def build_uwsgi(uc, print_only=False, gcll=None): print(binary_link_cmd) if os.system(binary_link_cmd) != 0: raise Exception('unable to link binary file') - for kind in ('start','end'): + for kind in ('start', 'end'): objcopy_cmd = "objcopy --redefine-sym _binary_%s_%s=%s_%s %s/%s.o" % (binarize('%s/%s' % (path, bfile[1])), kind, bfile[0], kind, path, bfile[1]) print(objcopy_cmd) if os.system(objcopy_cmd) != 0: @@ -503,8 +506,13 @@ def build_uwsgi(uc, print_only=False, gcll=None): t.join() print("*** uWSGI linking ***") - ldline = "%s -o %s %s %s %s" % (GCC, bin_name, ' '.join(uniq_warnings(ldflags)), - ' '.join(map(add_o, gcc_list)), ' '.join(uniq_warnings(libs))) + ldline = "%s -o %s %s %s %s" % ( + GCC, + bin_name, + ' '.join(uniq_warnings(ldflags)), + ' '.join(map(add_o, gcc_list)), + ' '.join(uniq_warnings(libs)) + ) print(ldline) ret = os.system(ldline) if ret != 0: @@ -530,6 +538,7 @@ def build_uwsgi(uc, print_only=False, gcll=None): for pb in post_build: pb(uc) + def open_profile(filename): if filename.startswith('http://') or filename.startswith('https://') or filename.startswith('ftp://'): wrapped = False @@ -545,6 +554,7 @@ def open_profile(filename): return urllib2.urlopen(filename) return open(filename) + class uConf(object): def __init__(self, filename, mute=False): @@ -555,25 +565,35 @@ class uConf(object): print("using profile: %s" % filename) if os.path.exists('uwsgibuild.lastprofile'): - ulp = open('uwsgibuild.lastprofile','r') + ulp = open('uwsgibuild.lastprofile', 'r') last_profile = ulp.read() ulp.close() if last_profile != filename: os.environ['UWSGI_FORCE_REBUILD'] = '1' - ulp = open('uwsgibuild.lastprofile','w') - ulp.write(filename) - ulp.close() + with open('uwsgibuild.lastprofile', 'w') as ulp: + ulp.write(filename) self.config.readfp(open_profile(filename)) - self.gcc_list = ['core/utils', 'core/protocol', 'core/socket', 'core/logging', 'core/master', 'core/master_utils', 'core/emperor', - 'core/notify', 'core/mule', 'core/subscription', 'core/stats', 'core/sendfile', 'core/async', 'core/master_checks', 'core/fifo', - 'core/offload', 'core/io', 'core/static', 'core/websockets', 'core/spooler', 'core/snmp', 'core/exceptions', 'core/config', - 'core/setup_utils', 'core/clock', 'core/init', 'core/buffer', 'core/reader', 'core/writer', 'core/alarm', 'core/cron', 'core/hooks', - 'core/plugins', 'core/lock', 'core/cache', 'core/daemons', 'core/errors', 'core/hash', 'core/master_events', 'core/chunked', - 'core/queue', 'core/event', 'core/signal', 'core/strings', 'core/progress', 'core/timebomb', 'core/ini', 'core/fsmon', 'core/mount', - 'core/metrics', 'core/plugins_builder', 'core/sharedarea', 'core/fork_server', 'core/webdav', 'core/zeus', - 'core/rpc', 'core/gateway', 'core/loop', 'core/cookie', 'core/querystring', 'core/rb_timers', 'core/transformations', 'core/uwsgi'] + self.gcc_list = [ + 'core/utils', 'core/protocol', 'core/socket', 'core/logging', + 'core/master', 'core/master_utils', 'core/emperor', 'core/notify', + 'core/mule', 'core/subscription', 'core/stats', 'core/sendfile', + 'core/async', 'core/master_checks', 'core/fifo', 'core/offload', + 'core/io', 'core/static', 'core/websockets', 'core/spooler', + 'core/snmp', 'core/exceptions', 'core/config', 'core/setup_utils', + 'core/clock', 'core/init', 'core/buffer', 'core/reader', + 'core/writer', 'core/alarm', 'core/cron', 'core/hooks', + 'core/plugins', 'core/lock', 'core/cache', 'core/daemons', + 'core/errors', 'core/hash', 'core/master_events', 'core/chunked', + 'core/queue', 'core/event', 'core/signal', 'core/strings', + 'core/progress', 'core/timebomb', 'core/ini', 'core/fsmon', + 'core/mount', 'core/metrics', 'core/plugins_builder', + 'core/sharedarea', 'core/fork_server', 'core/webdav', 'core/zeus', + 'core/rpc', 'core/gateway', 'core/loop', 'core/cookie', + 'core/querystring', 'core/rb_timers', 'core/transformations', + 'core/uwsgi', + ] # add protocols self.gcc_list.append('proto/base') self.gcc_list.append('proto/uwsgi') @@ -586,8 +606,14 @@ class uConf(object): if 'UWSGI_INCLUDES' in os.environ: self.include_path += os.environ['UWSGI_INCLUDES'].split(',') - - self.cflags = ['-O2', '-I.', '-Wall', '-Werror', '-D_LARGEFILE_SOURCE', '-D_FILE_OFFSET_BITS=64'] + os.environ.get("CFLAGS", "").split() + self.get('cflags','').split() + self.cflags = [ + '-O2', + '-I.', + '-Wall', + '-Werror', + '-D_LARGEFILE_SOURCE', + '-D_FILE_OFFSET_BITS=64' + ] + os.environ.get("CFLAGS", "").split() + self.get('cflags', '').split() report['kernel'] = uwsgi_os @@ -597,7 +623,7 @@ class uConf(object): try: lk_ver = uwsgi_os_k.split('.') if int(lk_ver[0]) <= 2 and int(lk_ver[1]) <= 6 and int(lk_ver[2]) <= 9: - self.cflags.append('-DOBSOLETE_LINUX_KERNEL') + self.cflags.append('-DOBSOLETE_LINUX_KERNEL') report['kernel'] = 'Old Linux' except: pass @@ -623,9 +649,9 @@ class uConf(object): add_it = False elif add_it: self.include_path.append(line.strip().split()[0]) - + if not self.include_path: - raise + raise except: self.include_path = ['/usr/include', '/usr/local/include'] @@ -641,7 +667,6 @@ class uConf(object): except: pass - if not mute: print("detected include path: %s" % self.include_path) @@ -652,9 +677,9 @@ class uConf(object): raise Exception("you need a C compiler to build uWSGI") # add -fno-strict-aliasing only on python2 and gcc < 4.3 if (sys.version_info[0] == 2) or (gcc_major < 4) or (gcc_major == 4 and gcc_minor < 3): - self.cflags = self.cflags + ['-fno-strict-aliasing'] + self.cflags += ['-fno-strict-aliasing'] if gcc_major >= 4: - self.cflags = self.cflags + [ '-Wextra', '-Wno-unused-parameter', '-Wno-missing-field-initializers' ] + self.cflags += ['-Wextra', '-Wno-unused-parameter', '-Wno-missing-field-initializers'] if gcc_major == 4 and gcc_minor < 9: self.cflags.append('-Wno-format -Wno-format-security') @@ -669,7 +694,7 @@ class uConf(object): # check for inherit option inherit = self.get('inherit') if inherit: - if not '/' in inherit: + if '/' not in inherit: inherit = 'buildconf/%s' % inherit if not inherit.endswith('.ini'): @@ -690,11 +715,10 @@ class uConf(object): elif self.get(opt) == 'null': self.config.remove_option('uwsgi', opt) - def set(self, key, value): - self.config.set('uwsgi',key, value) + self.config.set('uwsgi', key, value) - def get(self,key,default=None): + def get(self, key, default=None): try: value = self.config.get('uwsgi', key) if value == "" or value == "false": @@ -713,7 +737,7 @@ class uConf(object): def has_include(self, what): for include in self.include_path: - if os.path.exists("%s/%s" %(include, what)): + if os.path.exists("%s/%s" % (include, what)): return True return False @@ -725,7 +749,7 @@ class uConf(object): if 'UWSGI_PROFILE_OVERRIDE' in os.environ: for item in os.environ['UWSGI_PROFILE_OVERRIDE'].split(';'): - k,v = item.split('=', 2) + k, v = item.split('=', 1) self.set(k, v) if 'UWSGI_AS_LIB' in os.environ: @@ -803,7 +827,7 @@ class uConf(object): self.gcc_list.append(extra) # set locking subsystem - locking_mode = self.get('locking','auto') + locking_mode = self.get('locking', 'auto') if locking_mode == 'auto': if uwsgi_os == 'Linux' or uwsgi_os == 'SunOS': @@ -811,12 +835,12 @@ class uConf(object): # FreeBSD umtx is still not ready for process shared locking # starting from FreeBSD 9 posix semaphores can be shared between processes elif uwsgi_os in ('FreeBSD', 'GNU/kFreeBSD'): - try: - fbsd_major = int(uwsgi_os_k.split('.')[0]) - if fbsd_major >= 9: - locking_mode = 'posix_sem' - except: - pass + try: + fbsd_major = int(uwsgi_os_k.split('.')[0]) + if fbsd_major >= 9: + locking_mode = 'posix_sem' + except: + pass elif uwsgi_os == 'GNU': locking_mode = 'posix_sem' elif uwsgi_os == 'Darwin': @@ -842,7 +866,7 @@ class uConf(object): report['locking'] = locking_mode # set event subsystem - event_mode = self.get('event','auto') + event_mode = self.get('event', 'auto') if event_mode == 'auto': if uwsgi_os == 'Linux': @@ -872,13 +896,13 @@ class uConf(object): report['event'] = event_mode # set timer subsystem - timer_mode = self.get('timer','auto') + timer_mode = self.get('timer', 'auto') if timer_mode == 'auto': if uwsgi_os == 'Linux': k_all = uwsgi_os_k.split('.') k_base = k_all[0] - k_major = k_all[1] + # k_major = k_all[1] if len(k_all) > 2: k_minor = k_all[2] else: @@ -913,7 +937,7 @@ class uConf(object): report['timer'] = timer_mode # set filemonitor subsystem - filemonitor_mode = self.get('filemonitor','auto') + filemonitor_mode = self.get('filemonitor', 'auto') if filemonitor_mode == 'auto': if uwsgi_os == 'Linux': @@ -935,7 +959,6 @@ class uConf(object): else: self.cflags.append('-DUWSGI_EVENT_FILEMONITOR_USE_NONE') - report['filemonitor'] = filemonitor_mode if self.get('malloc_implementation') != 'libc': @@ -946,7 +969,6 @@ class uConf(object): report['malloc'] = self.get('malloc_implementation') - if self.get('as_shared_library'): self.ldflags.append('-shared') # on cygwin we do not need PIC (it is implicit) @@ -998,14 +1020,13 @@ class uConf(object): if self.get('routing') == 'auto': if has_pcre: self.gcc_list.append('core/routing') - self.cflags.append("-DUWSGI_ROUTING") + self.cflags.append("-DUWSGI_ROUTING") report['routing'] = True else: self.gcc_list.append('core/routing') self.cflags.append("-DUWSGI_ROUTING") report['routing'] = True - if self.has_include('sys/capability.h') and uwsgi_os == 'Linux': self.cflags.append("-DUWSGI_CAP") self.libs.append('-lcap') @@ -1021,8 +1042,7 @@ class uConf(object): uwsgi_version += '-' uwsgi_version += self.get('append_version') - - if uwsgi_os in ('FreeBSD','GNU/kFreeBSD') and self.has_include('jail.h'): + if uwsgi_os in ('FreeBSD', 'GNU/kFreeBSD') and self.has_include('jail.h'): self.cflags.append('-DUWSGI_HAS_FREEBSD_LIBJAIL') self.libs.append('-ljail') @@ -1056,7 +1076,7 @@ class uConf(object): print(binary_link_cmd) os.system(binary_link_cmd) if symbase: - for kind in ('start','end'): + for kind in ('start', 'end'): objcopy_cmd = "objcopy --redefine-sym _binary_%s_%s=_binary_%s%s_%s build/%s.o" % (binarize(fname), kind, binarize(symbase), binarize(fname[len(ef):]), kind, binarize(fname)) print(objcopy_cmd) os.system(objcopy_cmd) @@ -1067,12 +1087,10 @@ class uConf(object): os.system(binary_link_cmd) binary_list.append(binarize(ef)) if symbase: - for kind in ('start','end'): + for kind in ('start', 'end'): objcopy_cmd = "objcopy --redefine-sym _binary_%s_%s=_binary_%s_%s build/%s.o" % (binarize(ef), kind, binarize(symbase), kind, binarize(ef)) print(objcopy_cmd) os.system(objcopy_cmd) - - self.cflags.append('-DUWSGI_VERSION="\\"' + uwsgi_version + '\\""') @@ -1094,7 +1112,6 @@ class uConf(object): if len(uver_dots) > 3: uver_rev = uver_dots[3] - self.cflags.append('-DUWSGI_VERSION_BASE="' + uver_base + '"') self.cflags.append('-DUWSGI_VERSION_MAJOR="' + uver_maj + '"') @@ -1179,8 +1196,7 @@ class uConf(object): else: print("*** yajl headers unavailable. uWSGI build is interrupted. You have to install yajl development package or use jansson or disable JSON") sys.exit(1) - - + if self.get('ssl'): if self.get('ssl') == 'auto': if self.has_include('openssl/ssl.h'): @@ -1249,8 +1265,10 @@ class uConf(object): return self.gcc_list, self.cflags, self.ldflags, self.libs + def is_remote_plugin(path): - return path.startswith('http://') or path.startswith('https://') or path.startswith('git://') or path.startswith('ssh://') + return any(path.startswith(pfx) for pfx in ('http://', 'https://', 'git://', 'ssh://')) + def get_remote_plugin(path): git_dir = path.split('/').pop() @@ -1264,6 +1282,7 @@ def get_remote_plugin(path): sys.exit(1) return git_dir + def get_plugin_up(path): up = {} if os.path.isfile(path): @@ -1299,7 +1318,8 @@ def get_plugin_up(path): return (path, up) -def build_plugin(path, uc, cflags, ldflags, libs, name = None): + +def build_plugin(path, uc, cflags, ldflags, libs, name=None): path = path.rstrip('/') plugin_started_at = time.time() @@ -1352,7 +1372,7 @@ def build_plugin(path, uc, cflags, ldflags, libs, name = None): shared_flag = '-dynamiclib -undefined dynamic_lookup' for cfile in up['GCC_LIST']: - if cfile.endswith('.a'): + if cfile.endswith('.a'): gcc_list.append(cfile) elif not cfile.endswith('.c') and not cfile.endswith('.cc') and not cfile.endswith('.m') and not cfile.endswith('.go') and not cfile.endswith('.o'): gcc_list.append(path + '/' + cfile + '.c') @@ -1366,8 +1386,15 @@ def build_plugin(path, uc, cflags, ldflags, libs, name = None): print(binary_link_cmd) if os.system(binary_link_cmd) != 0: raise Exception('unable to link binary file') - for kind in ('start','end'): - objcopy_cmd = "objcopy --redefine-sym _binary_%s_%s=%s_%s %s/%s.o" % (binarize('%s/%s' % (path, bfile[1])), kind, bfile[0], kind, path, bfile[1]) + for kind in ('start', 'end'): + objcopy_cmd = "objcopy --redefine-sym _binary_%s_%s=%s_%s %s/%s.o" % ( + binarize('%s/%s' % (path, bfile[1])), + kind, + bfile[0], + kind, + path, + bfile[1] + ) print(objcopy_cmd) if os.system(objcopy_cmd) != 0: raise Exception('unable to link binary file') @@ -1375,14 +1402,12 @@ def build_plugin(path, uc, cflags, ldflags, libs, name = None): except: pass - p_ldflags_blacklist = ( - '-Wl,--no-undefined', - ) + p_ldflags_blacklist = ('-Wl,--no-undefined',) for ldflag in p_ldflags_blacklist: - try: - p_ldflags.remove(ldflag) - except: - pass + try: + p_ldflags.remove(ldflag) + except: + pass p_cflags_blacklist = ( '-Wdeclaration-after-statement', @@ -1393,10 +1418,10 @@ def build_plugin(path, uc, cflags, ldflags, libs, name = None): '-pie', ) for cflag in p_cflags_blacklist: - try: - p_cflags.remove(cflag) - except: - pass + try: + p_cflags.remove(cflag) + except: + pass if GCC in ('clang',): try: @@ -1417,7 +1442,16 @@ def build_plugin(path, uc, cflags, ldflags, libs, name = None): if uwsgi_os.startswith('CYGWIN'): need_pic = ' -L. -luwsgi' - gccline = "%s%s %s -o %s.so %s %s %s %s" % (GCC, need_pic, shared_flag, plugin_dest, ' '.join(uniq_warnings(p_cflags)), ' '.join(gcc_list), ' '.join(uniq_warnings(p_ldflags)), ' '.join(uniq_warnings(p_libs)) ) + gccline = "%s%s %s -o %s.so %s %s %s %s" % ( + GCC, + need_pic, + shared_flag, + plugin_dest, + ' '.join(uniq_warnings(p_cflags)), + ' '.join(gcc_list), + ' '.join(uniq_warnings(p_ldflags)), + ' '.join(uniq_warnings(p_libs)) + ) print_compilation_output("[%s] %s.so" % (GCC, plugin_dest), gccline) ret = os.system(gccline) @@ -1444,6 +1478,7 @@ def build_plugin(path, uc, cflags, ldflags, libs, name = None): print("build time: %d seconds" % (time.time() - plugin_started_at)) print("*** %s plugin built and available in %s ***" % (name, plugin_dest + '.so')) + def vararg_callback(option, opt_str, value, parser): assert value is None value = [] @@ -1481,12 +1516,12 @@ if __name__ == "__main__": add_ldflags = [] if options.debug: - add_cflags.append('-g') - add_ldflags.append('-g') + add_cflags.append('-g') + add_ldflags.append('-g') if options.asan: - add_cflags.extend(['-g', '-fsanitize=address', '-fno-omit-frame-pointer']) - add_ldflags.extend(['-g', '-fsanitize=address']) + add_cflags.extend(['-g', '-fsanitize=address', '-fno-omit-frame-pointer']) + add_ldflags.extend(['-g', '-fsanitize=address']) if options.build is not None or options.cflags is not None: is_cflags = options.cflags is not None @@ -1496,10 +1531,10 @@ if __name__ == "__main__": else: bconf = options.cflags[0] except: - bconf = os.environ.get('UWSGI_PROFILE','default.ini') + bconf = os.environ.get('UWSGI_PROFILE', 'default.ini') if not bconf.endswith('.ini'): bconf += '.ini' - if not '/' in bconf: + if '/' not in bconf: bconf = 'buildconf/%s' % bconf uc = uConf(bconf, is_cflags) @@ -1519,10 +1554,10 @@ if __name__ == "__main__": try: bconf = options.plugin[1] except: - bconf = os.environ.get('UWSGI_PROFILE','default.ini') + bconf = os.environ.get('UWSGI_PROFILE', 'default.ini') if not bconf.endswith('.ini'): bconf += '.ini' - if not '/' in bconf: + if '/' not in bconf: bconf = 'buildconf/%s' % bconf uc = uConf(bconf) gcc_list, cflags, ldflags, libs = uc.get_gcll() @@ -1530,7 +1565,7 @@ if __name__ == "__main__": name = options.plugin[2] except: name = None - print("*** uWSGI building and linking plugin %s ***" % options.plugin[0] ) + print("*** uWSGI building and linking plugin %s ***" % options.plugin[0]) build_plugin(options.plugin[0], uc, cflags, ldflags, libs, name) elif options.extra_plugin: print("*** uWSGI building and linking plugin from %s ***" % options.extra_plugin[0]) diff --git a/uwsgidecorators.py b/uwsgidecorators.py index 0924cfb7..dfc79b1e 100644 --- a/uwsgidecorators.py +++ b/uwsgidecorators.py @@ -119,7 +119,7 @@ class _spoolraw(object): return self.__class__.__call__(self, *args, **kwargs) def __init__(self, f, pass_arguments): - if not 'spooler' in uwsgi.opt: + if 'spooler' not in uwsgi.opt: raise Exception( "you have to enable the uWSGI spooler to use @%s decorator" % self.__class__.__name__) self.f = f diff --git a/vhosttest/flask001/app1.py b/vhosttest/flask001/app1.py index bbf7e467..591872eb 100644 --- a/vhosttest/flask001/app1.py +++ b/vhosttest/flask001/app1.py @@ -1,6 +1,7 @@ from flask import Flask app = Flask(__name__) + @app.route("/") def hello(): return "Hello World!" diff --git a/vhosttest/flask002/app2.py b/vhosttest/flask002/app2.py index 346eca47..5e89f91e 100644 --- a/vhosttest/flask002/app2.py +++ b/vhosttest/flask002/app2.py @@ -1,6 +1,7 @@ from flask import Flask app = Flask(__name__) + @app.route("/") def hello(): return "Hello World! app2 !!!" diff --git a/vhosttest/flask003/app3.py b/vhosttest/flask003/app3.py index 9e33a753..c54da9dd 100644 --- a/vhosttest/flask003/app3.py +++ b/vhosttest/flask003/app3.py @@ -1,6 +1,7 @@ from flask import Flask app = Flask(__name__) + @app.route("/") def hello(): return "Hello World! app3" diff --git a/vhosttest/flask004/app4.py b/vhosttest/flask004/app4.py index 313aa7a3..2dfb661c 100644 --- a/vhosttest/flask004/app4.py +++ b/vhosttest/flask004/app4.py @@ -1,6 +1,7 @@ from flask import Flask app = Flask(__name__) + @app.route("/") def hello(): return "Hello World! app4" diff --git a/vhosttest/flask005/app5.py b/vhosttest/flask005/app5.py index 54f51c34..973ae4a3 100644 --- a/vhosttest/flask005/app5.py +++ b/vhosttest/flask005/app5.py @@ -1,6 +1,7 @@ from flask import Flask app = Flask(__name__) + @app.route("/") def hello(): return "Hello World! app5"