Giter Club home page Giter Club logo

python-pooledprocessmixin's Introduction

PooledProcessMixIn For Python

Python Logo

Fast Concurrent Pool of preforked-processes and threads Mix-in for python's socket server Replace the usual ThreadingMixIn and ForkingMixIn

This is a pure-python module that provides asynchronous mix-in similar to standard ThreadingMixIn and ForkingMixIn but provides better performance by utilizing a pool of processes forked at initialization time each process allocate a pool of given number of threads

Installation and Dependencies

This module has no external dependencies other than the standard python library.

To get the latest development snapshot type the following command

git clone https://github.com/muayyad-alsadi/python-PooledProcessMixIn.git

Example

from PooledProcessMixIn import PooledProcessMixIn
from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer

# ... define MyTestHandler somewhere

class MyHTTPTest (PooledProcessMixIn, HTTPServer):
    def __init__(self):
        self._process_n=7  # if not set will default to number of CPU cores
        self._thread_n=64  # if not set will default to number of threads
        HTTPServer.__init__(self, ('127.0.0.1',8888), MyTestHandler)
        self._init_pool() # this is optional, will be called automatically
        print "listing on http://127.0.0.1:8888/"

Details

You can set initial number of processes by setting self._process_n before calling self._init_pool()

You can set initial number of threads for each forked process by setting self._thread_n before calling self._init_pool()

You should call self._init_pool() AFTER super class __init__ but if you did not call it, it will be called automatically when we get first request

When Benchmarked against ThreadingMixIn and ForkingMixIn, it gives double performance (was able to handle about 1,500 request per second while other mix-ins reached 800 requests/second )

siege -b -c 100 -t10s localhost:8888/test
      Date & Time,  Trans,  Elap Time,  Data Trans,  Resp Time,  Trans Rate,  Throughput,  Concurrent,    OKAY,   Failed
2012-08-02 12:51:47,  14663,       9.58,           0,       0.01,     1530.58,        0.00,       22.87,   14663,       0
2012-08-02 12:52:44,   7653,       9.58,           0,       0.04,      798.85,        0.00,       29.42,    7653,       5
2012-08-02 12:53:14,   7726,       9.47,           0,       0.05,      815.84,        0.00,       43.57,    7726,       0

Can I use it to run my Django applications ?

Yes, Django provides WSGI application which can be used like the wsgi-demo included in this packages

import sys, os
    
from PooledProcessMixIn import PooledProcessMixIn
from wsgiref.simple_server import make_server, WSGIServer
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mysite.settings")
    
d=os.path.dirname(__file__)
sys.path.insert(0, d)
sys.path.insert(0, os.path.join(d, ".."))
    
from django import VERSION as DJ_VERSION
if DJ_VERSION>=(1,4):
    from django.core.wsgi import get_wsgi_application
else:
    from django.core.handlers.wsgi import WSGIHandler as get_wsgi_application
    
class WSGIServerPool(PooledProcessMixIn, WSGIServer):
    pass
    
application = get_wsgi_application()
make_server('127.0.0.1', 8080, application, server_class=WSGIServerPool).serve_forever()

python-pooledprocessmixin's People

Contributors

alsadi avatar muayyad-alsadi avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar

python-pooledprocessmixin's Issues

report each thread status

a thread status can be ready, busy, unresponsive
we should be able to tell the status of each thread to be able to manage the pool (eg. fork more processes)

Memory leak

After around 24 hours of running and accommodating 100.000s of requests, the script never frees memory and builds up to even 32GB.


class Handler(BaseHTTPRequestHandler):
    handle_request: Callable

    def __init__(self, *args, **kwargs):
        self.handle_request = kwargs['handle_request']
        del kwargs['handle_request']
        super(Handler,self).__init__(*args, **kwargs)


    def setup(self) -> None:
        self.timeout = HTTP_REQUEST_TIMEOUT
        BaseHTTPRequestHandler.setup(self)
        self.request.settimeout(HTTP_REQUEST_TIMEOUT)
        
    def do_POST(self):
        try:
            length = int(self.headers.get('content-length'))

            b64_auth = self.headers.get('authorization')

            if b64_auth != HTTP_SERVICE_AUTHENTICATION_B64:
                self.send_response(401)
                self.end_headers()
                return

            js = json.loads(self.rfile.read(length))
            #self.rfile.read(length)
            #print(js)
            response = self.handle_request(js)
            self.send_response(200)
            self.end_headers()
            self.wfile.write(json.dumps(response).encode('utf-8'))
        except Exception as ex:
            self.send_response(503, json.dumps(ex.__dict__))
            self.end_headers()
            pass

    def do_GET(self):
        self.send_response(200)
        self.end_headers()

class ThreadingSimpleServer(PooledProcessMixIn, HTTPServer):
    def __init__(self,bind_addr, handler, processes, threads) -> None:
        self._process_n=processes  # if not set will default to number of CPU cores
        self._thread_n=threads  # if not set will default to number of threads
        HTTPServer.__init__(self, bind_addr, handler)
        #self._init_pool() # this is optional, will be called automatically

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.