Пример #1
0
def run_production_server(config: object, mysql: object) -> NoReturn:
    app = create_app(config, mysql)
    if sys.platform == "win32":
        from gevent.pywsgi import WSGIServer

        server = WSGIServer((config.HOST, int(config.PORT)), app)
        try:
            logger.info("Starting server on {}://{}:{}".format(
                "http", config.HOST, config.PORT))
            server.serve_forever()
        except KeyboardInterrupt:
            logger.info("Server shutting down...")
    else:
        from meinheld import server

        logger.warning(
            "This is not the recommended way to go with on non-windows systems. "
            "Please use gunicorn instead")

        server.listen((config.HOST, int(config.PORT)), )
        try:
            logger.info("Starting server on {}://{}:{}".format(
                "http", config.HOST, config.PORT))
            server.run(app)
        except KeyboardInterrupt:
            logger.info("Server shutting down...")
Пример #2
0
 def run(self, port, hostname, **kwargs):
     from meinheld import server, patch
     patch.patch_all()
     print(" - Running Hosting Server using Meinheld")
     print(" - http://%s:%s/" % (hostname, port))
     server.listen((hostname, port))
     server.run(self.app)
Пример #3
0
def test_sock():
    def _test():
        s = msocket.socket(msocket.AF_INET, msocket.SOCK_STREAM)
        assert (type(s) == msocket.socket)
        server.shutdown()

    server.listen(("0.0.0.0", 8000))
    server.spawn(_test)
    server.run(App())
Пример #4
0
    def run(self, handler):
        from meinheld import server

        if self.quiet:
            server.set_access_logger(None)
            server.set_error_logger(None)

        server.listen((self.host, self.port))
        server.run(handler)
Пример #5
0
def main():
    opts, args = getopt.parse_args()

    if opts.debug:
        application.debug = True

    print "Server listen: http://%s:%s/" % (opts.address, opts.port)
    server.listen((opts.address, opts.port))
    server.run(application)
Пример #6
0
def test_connect_ex():
    def _test():
        s = msocket.socket(msocket.AF_INET, msocket.SOCK_STREAM)
        s.connect_ex(("localhost", 8000))
        server.shutdown()

    server.listen(("0.0.0.0", 8000))
    server.spawn(_test)
    server.run(App())
Пример #7
0
def test_detach():
    def _test():
        s = msocket.socket(msocket.AF_INET, msocket.SOCK_STREAM)
        s.detach()
        server.shutdown()

    server.listen(("0.0.0.0", 8000))
    server.spawn(_test)
    server.run(App())
Пример #8
0
    def run(self, handler):
        from meinheld import server

        if self.quiet:
            server.set_access_logger(None)
            server.set_error_logger(None)

        server.listen((self.host, self.port))
        server.run(handler)
Пример #9
0
def test_fileno():
    def _test():
        s = msocket.socket(msocket.AF_INET, msocket.SOCK_STREAM)
        assert (s.fileno() > 2)
        server.shutdown()

    server.listen(("0.0.0.0", 8000))
    server.spawn(_test)
    server.run(App())
Пример #10
0
def test_sock():

    def _test():
        s = msocket.socket(msocket.AF_INET, msocket.SOCK_STREAM)
        assert(type(s) == msocket.socket)
        server.shutdown()

    server.listen(("0.0.0.0", 8000))
    server.spawn(_test)
    server.run(App())
Пример #11
0
def test_fileno():

    def _test():
        s = msocket.socket(msocket.AF_INET, msocket.SOCK_STREAM)
        assert(s.fileno() > 2)
        server.shutdown()

    server.listen(("0.0.0.0", 8000))
    server.spawn(_test)
    server.run(App())
Пример #12
0
    def run(self):
        fd = self.socket.fileno()
        server.set_keepalive(self.cfg.keepalive)
        server.set_picoev_max_fd(self.cfg.worker_connections)

        server.set_fastwatchdog(self.tmp.fileno(), self.ppid)
        #server.set_watchdog(self.watchdog)

        server.set_listen_socket(fd)
        server.run(self.wsgi)
Пример #13
0
def test_getsockopt():
    def _test():
        s = msocket.socket(msocket.AF_INET, msocket.SOCK_STREAM)
        tr = s.getsockopt(msocket.IPPROTO_TCP, msocket.TCP_NODELAY)
        assert(tr > 0)
        server.shutdown()

    server.listen(("0.0.0.0", 8000))
    server.spawn(_test)
    server.run(App())
Пример #14
0
def test_detach():

    def _test():
        s = msocket.socket(msocket.AF_INET, msocket.SOCK_STREAM)
        s.detach()
        server.shutdown()

    server.listen(("0.0.0.0", 8000))
    server.spawn(_test)
    server.run(App())
Пример #15
0
def test_connect_fail():
    def _test():
        s = msocket.socket(msocket.AF_INET, msocket.SOCK_STREAM)
        with raises(msocket.gaierror):
            s.connect(("google.comaaa", 80))
        server.shutdown()

    server.listen(("0.0.0.0", 8000))
    server.spawn(_test)
    server.run(App())
Пример #16
0
 def run(self):
     fd = self.socket.fileno()
     server.set_keepalive(self.cfg.keepalive)
     server.set_picoev_max_fd(self.cfg.worker_connections)
     
     server.set_fastwatchdog(self.tmp.fileno(), self.ppid, int(self.timeout))
     #server.set_watchdog(self.watchdog)
     
     server.set_listen_socket(fd)
     server.run(self.wsgi)
Пример #17
0
def test_connect_ex():

    def _test():
        s = msocket.socket(msocket.AF_INET, msocket.SOCK_STREAM)
        s.connect_ex(("localhost", 8000))
        server.shutdown()

    server.listen(("0.0.0.0", 8000))
    server.spawn(_test)
    server.run(App())
Пример #18
0
def test_connect_fail():

    def _test():
        s = msocket.socket(msocket.AF_INET, msocket.SOCK_STREAM)
        with raises(msocket.gaierror):
            s.connect(("google.comaaa", 80))
        server.shutdown()

    server.listen(("0.0.0.0", 8000))
    server.spawn(_test)
    server.run(App())
Пример #19
0
def test_sendto():
    def _test():
        s = msocket.socket(msocket.AF_INET, msocket.SOCK_STREAM)
        s.connect(("localhost", 8000))
        s.sendto(b"GET / HTTP/1.0\r\n\r\n", (b'localhost',8000))
        assert(len(s.recv(1024)) == 135)
        server.shutdown()

    server.listen(("0.0.0.0", 8000))
    server.spawn(_test)
    server.run(App())
Пример #20
0
def meinheld_server_runner(wsgi_app, global_config, **settings):
    from meinheld import server, middleware
    host = settings.get('host', '0.0.0.0')
    port = int(settings.get('port', 8080))

    server.listen((host, port))
    server.set_access_logger(None)
    server.set_error_logger(None)

    print('Starting HTTP server on http://%s:%s' % (host, port))
    server.run(middleware.WebSocketMiddleware(wsgi_app))
Пример #21
0
def test_timeout():
    def _test():
        val = 5
        s = msocket.socket(msocket.AF_INET, msocket.SOCK_STREAM)
        s.settimeout(val)
        assert(val == s.gettimeout())
        server.shutdown()

    server.listen(("0.0.0.0", 8000))
    server.spawn(_test)
    server.run(App())
Пример #22
0
    def run(self, shutdown=False):
        if self.running:
            return

        server.listen(("0.0.0.0", 8000))
        self.running = True
        if shutdown:
            server.schedule_call(2, server.shutdown, 3)
        if self.middleware:
            server.run(self.middleware(self.app))
        else:
            server.run(self.app)
Пример #23
0
def main():
    args = parse_args()
    app = import_app(args)

    address, port = args.bind.split(':')

    if args.disable_logging:
        server.set_access_logger(None)

    server.listen((address, int(port)))
    server.set_keepalive(10)
    server.run(app)
Пример #24
0
def test_makefile():
    def _test():
        s = msocket.socket(msocket.AF_INET, msocket.SOCK_STREAM)
        s.connect(("localhost", 8000))
        f = s.makefile()
        assert(f)

        server.shutdown()

    server.listen(("0.0.0.0", 8000))
    server.spawn(_test)
    server.run(App())
    def run(self, port, hostname, **kwargs):
        if port is None:
            port = self.app.config.setdefault('LISTEN_PORT', 8000)
        if hostname is None:
            hostname = self.app.config.setdefault('LISTEN_HOST', '127.0.0.1')

        from meinheld import server, patch
        patch.patch_all()
        print(" - Running Hosting Server using Meinheld")
        print(" - http://%s:%s/" % (hostname, port))
        server.listen((hostname, port))
        server.run(self.app)
Пример #26
0
    def run(self, shutdown=False):
        if self.running:
            return

        server.listen(("0.0.0.0", 8000))
        self.running = True
        if shutdown:
            server.schedule_call(1, server.shutdown, 3)
        if self.middleware:
            server.run(self.middleware(self.app))
        else:
            server.run(self.app)
def start(name):
    print "started server at "+str(host)+":"+str(port)
    if name =="meinheld":
        from meinheld import server
        server.set_access_logger(None)
        server.set_error_logger(None)
        server.listen((host, port))
        server.run(app)
    elif name =="gevent":
        #from gevent import wsgi 
        #wsgi.WSGIServer((host, port), application=app.application, log=None).serve_forever() 
        from gevent.pywsgi import WSGIServer
        WSGIServer((host, port), app, log=None).serve_forever()
    elif name =="bjoern":
        import bjoern
        bjoern.listen(app, host, port)
        bjoern.run() 
    elif name =="eventlet":
        import eventlet
        from eventlet import wsgi
        #worker_pool = eventlet.GreenPool(2000)
        #wsgi.server(eventlet.listen(('', port)), app, custom_pool=worker_pool, log=file('/dev/null', 'w'))
        # max_size
        wsgi.server(eventlet.listen(('', port)), app, max_size=10000, log=file('/dev/null', 'w'))
    elif name =="fapws":
        import fapws._evwsgi as evwsgi
        from fapws import base
        evwsgi.start(host, str(port)) 
        evwsgi.set_base_module(base)
        evwsgi.wsgi_cb(('/', app))
        evwsgi.set_debug(0)        
        evwsgi.run()
    elif name=="uwsgi":
        print ("""Enter this command in the console
                \nsudo uwsgi --http :8000 --master --disable-logging --pythonpath /home/a/g --wsgi-file w.py --listen 2  --buffer-size 2048 --async 10000 --ugreen -p 4
            """)
        #  http://osdir.com/ml/python-wsgi-uwsgi-general/2011-02/msg00136.html
        # 
        #  Re: strange SIGPIPE: writing to a closed pipe/socket/fd on image requested from facebook -msg#00136
        """
SIGPIPE: writing to a closed pipe/socket/fd (probably the client disconnected) on request /1 (ip 127.0.0.1) !!!
uwsgi_response_write_body_do(): Broken pipe [core/writer.c line 260]
IOError: write error
        """
        cmd_txt = "sudo uwsgi --http :8000 --master --harakiri 1 --harakiri-verbose --close-on-exec --disable-logging --pythonpath /home/a/todo/test --wsgi-file w2.py --listen 2  --buffer-size 2048 --async 10000 --ugreen -p 4"
        cmd(cmd_txt)
    elif name=="pycgi":
        from wsgiref.handlers import CGIHandler 
        CGIHandler().run(app)
    elif name=="pystandard":
        from wsgiref.simple_server import make_server
        make_server(host, port, app).serve_forever()
Пример #28
0
def test_sockname():
    def _test():
        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        shost, sport = s.getsockname()
        ms = msocket.socket(msocket.AF_INET, msocket.SOCK_STREAM)
        host, port = ms.getsockname()
        assert (host == shost)
        assert (port == sport)
        server.shutdown()

    server.listen(("0.0.0.0", 8000))
    server.spawn(_test)
    server.run(App())
Пример #29
0
def start_server(app, middleware=None):
    global running 
    if running:
        return

    server.listen(("0.0.0.0", 8000))
    running = True
    if middleware:
        server.run(middleware(app))
    else:
        server.run(app)

    return app.environ
Пример #30
0
def start_server(app, middleware=None):
    global running
    if running:
        return

    server.listen(("0.0.0.0", 8000))
    running = True
    if middleware:
        server.run(middleware(app))
    else:
        server.run(app)

    return app.environ
Пример #31
0
def test_getpeername():
    def _test():
        s = msocket.socket(msocket.AF_INET, msocket.SOCK_STREAM)
        s.connect(("localhost", 8000))
        assert (s)
        host, port = s.getpeername()
        assert (host == "127.0.0.1")
        assert (port == 8000)
        server.shutdown()

    server.listen(("0.0.0.0", 8000))
    server.spawn(_test)
    server.run(App())
Пример #32
0
def test_recvfrom():
    def _test():
        s = msocket.socket(msocket.AF_INET, msocket.SOCK_STREAM)
        s.connect(("localhost", 8000))
        s.send(b"GET / HTTP/1.0\r\n")
        s.send(b"\r\n")
        c, addr = s.recvfrom(1024)
        assert (len(c) == RESPONSE_LEN)

        server.shutdown()

    server.listen(("0.0.0.0", 8000))
    server.spawn(_test)
    server.run(App())
Пример #33
0
def test_getpeername():

    def _test():
        s = msocket.socket(msocket.AF_INET, msocket.SOCK_STREAM)
        s.connect(("localhost", 8000))
        assert(s)
        host, port = s.getpeername()
        assert(host == "127.0.0.1")
        assert(port == 8000)
        server.shutdown()

    server.listen(("0.0.0.0", 8000))
    server.spawn(_test)
    server.run(App())
Пример #34
0
def test_sockname():

    def _test():
        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        shost, sport = s.getsockname()
        ms = msocket.socket(msocket.AF_INET, msocket.SOCK_STREAM)
        host, port = ms.getsockname()
        assert(host == shost)
        assert(port == sport)
        server.shutdown()

    server.listen(("0.0.0.0", 8000))
    server.spawn(_test)
    server.run(App())
Пример #35
0
def test_recv_into():
    def _test():
        s = msocket.socket(msocket.AF_INET, msocket.SOCK_STREAM)
        s.connect(("localhost", 8000))
        s.send(b"GET / HTTP/1.0\r\n")
        s.send(b"\r\n")
        buf = array.array('b', [0] * 1024)
        r = s.recv_into(buf)
        assert (r == RESPONSE_LEN)

        server.shutdown()

    server.listen(("0.0.0.0", 8000))
    server.spawn(_test)
    server.run(App())
Пример #36
0
    def run(self):

        if hasattr(self, "sockets"):
            fds = [s.fileno() for s in self.sockets]
        else:
            fds = [self.socket.fileno()]

        server.set_keepalive(self.cfg.keepalive)
        server.set_picoev_max_fd(self.cfg.worker_connections)

        server.set_fastwatchdog(self.tmp.fileno(), self.ppid, int(self.timeout))
        #server.set_watchdog(self.watchdog)

        server.set_listen_socket(fds)
        server.run(self.wsgi)
Пример #37
0
def test_recvfrom():

    def _test():
        s = msocket.socket(msocket.AF_INET, msocket.SOCK_STREAM)
        s.connect(("localhost", 8000))
        s.send(b"GET / HTTP/1.0\r\n")
        s.send(b"\r\n")
        c, addr = s.recvfrom(1024)
        assert(len(c) == 135)

        server.shutdown()

    server.listen(("0.0.0.0", 8000))
    server.spawn(_test)
    server.run(App())
Пример #38
0
    def run(self):

        if hasattr(self, "sockets"):
            fds = [s.fileno() for s in self.sockets]
        else:
            fds = [self.socket.fileno()]

        server.set_keepalive(self.cfg.keepalive)
        server.set_picoev_max_fd(self.cfg.worker_connections)

        server.set_fastwatchdog(self.tmp.fileno(), self.ppid,
                                int(self.timeout))
        #server.set_watchdog(self.watchdog)

        server.set_listen_socket(fds)
        server.run(self.wsgi)
Пример #39
0
def test_recv_into():

    def _test():
        s = msocket.socket(msocket.AF_INET, msocket.SOCK_STREAM)
        s.connect(("localhost", 8000))
        s.send(b"GET / HTTP/1.0\r\n")
        s.send(b"\r\n")
        buf = array.array('b', [0] *1024)
        r = s.recv_into(buf)
        assert(r == 135)

        server.shutdown()

    server.listen(("0.0.0.0", 8000))
    server.spawn(_test)
    server.run(App())
Пример #40
0
def test_makefile_write_read():
    def _test():
        s = msocket.socket(msocket.AF_INET, msocket.SOCK_STREAM)
        s.connect(("localhost", 8000))
        f = s.makefile(mode="rwb")
        assert(f)
        f.write(b"GET / HTTP/1.0\r\n")
        f.write(b"\r\n")
        f.flush()
        c = f.read(1024)
        assert(len(c) == 135)
        server.shutdown()

    server.listen(("0.0.0.0", 8000))
    server.spawn(_test)
    server.run(App())
Пример #41
0
def cli_server_meinheld(managed, application=None, port=None):
    try:
        from meinheld import server
    except ImportError:
        print('failed to import meinheld, bailing', file=sys.stderr)
        sys.exit(1)

    port = get_port_number() if not managed and port is None else port

    if not managed and application is None:
        # inspect the caller
        outer_frame = inspect.getouterframes(inspect.currentframe())[2][0]
        app = outer_frame.f_globals['application']
    else:
        app = application

    server.listen(('0.0.0.0', port, ))
    server.run(app)
Пример #42
0
 def run_webapp(self):
     from meinheld import server, middleware
     server.listen((self.host, self.port))
     server.run(middleware.WebSocketMiddleware(app))
Пример #43
0
from meinheld import server
import socket

def hello_world(environ, start_response):
    status = '200 OK'
    res = b"Hello world!"
    response_headers = [('Content-type','text/plain')]
    start_response(status, response_headers)
    return [res]

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind(("0.0.0.0", 8000))
s.listen(50)
fd = s.fileno()

# server.set_listen_socket(fd)
server.listen(socket_fd=fd)

server.run(hello_world)


Пример #44
0
from meinheld import server


def hello_world(environ, start_response):
    status = '200 OK'
    res = "Hello world!"
    response_headers = [('Content-type', 'text/plain')]
    start_response(status, response_headers)
    return [res]


server.listen(("0.0.0.0", 8000))
server.run(hello_world)
Пример #45
0
import codeart.benchmarks
import codeart.benchmarks.servers as _util
import codeart.benchmarks.servers._meinheld as _meinheld
from codeart.benchmarks._wsgi import *
from codeart.benchmarks.responses import *


if __name__ == '__main__':
    _util.disable_logs()
    _meinheld.disable_logs()
    _meinheld.configure()

    from meinheld import server
    server.listen(('0.0.0.0', _util.get_port()))
    server.run(app)
Пример #46
0
 def serve_forever(self):
     server.run(self.application)
Пример #47
0
#!/usr/bin/env python
from meinheld import server
from pymongo import MongoClient


db = MongoClient()['documents']


def application(environ, start_response):
    data = str(db.items.find_one({})['data'])

    start_response(
        '200 OK',
        [
            ('Content-Type', 'text/plain'),
            ('Content-Length', str(len(data)))
        ]
    )

    yield data


if __name__ == '__main__':
    server.listen(('127.0.0.1', 7777))
    server.run(application)
Пример #48
0
 def run(self, handler):
     from meinheld import server
     server.listen((self.host, self.port))
     server.run(handler)
Пример #49
0
def insert():

    from pymongo import Connection
    connection = Connection()

    db = connection.test_database
    test_collection = db.test_collection

    for i in xrange(10):
        name = "long name %s" % i
        data = "A" * 1024 * 1024
        if test_collection.insert(dict(id=i, index=i, name=name, data=data)):
            pass

    for t in test_collection.find():
        pass


def wsgi_app(environ, start_response):
    status = '200 OK'
    res = "Hello world!"
    response_headers = [('Content-type', 'text/plain')]
    start_response(status, response_headers)
    insert()
    return [res]


server.listen(("0.0.0.0", 8000))
server.run(wsgi_app)
Пример #50
0
from meinheld import server


def hello(environ, start_response):
    if (environ['PATH_INFO'] == '/' and environ['REQUEST_METHOD'] == 'GET'):
        status = '200 OK'
        text = "Hello world!"
    else:
        status = '404 Not Found'
        text = "Not Found"

    body = text.encode('utf-8')
    response_headers = [('Content-type', 'text/plain; charset=utf-8'),
                        ('Content-Length', str(len(body)))]
    start_response(status, response_headers)
    return [body]


server.listen(('0.0.0.0', 8080))
server.set_access_logger(None)
server.set_keepalive(1)
server.run(hello)
Пример #51
0
        while True:
            print("ws.wait()...")
            m = ws.wait()
            print("recv msg %s" % m)
            if m is None:
                break
            for p in participants:
                print("send message %s" % m)
                p.send(m)
    finally:
        participants.remove(ws)
    return [""]

def dispatch(environ, start_response):
    """Resolves to the web page or the websocket depending on the path."""
    if environ['PATH_INFO'] == '/chat':
        return websocket_handle(environ, start_response)
    else:
        start_response('200 OK', [('Content-Type', 'text/html')])
        ret = [open(os.path.join(
                     os.path.dirname(__file__),
                     'templates/websocket_chat.html'), 'rb').read()]
        return ret
        
if __name__ == "__main__":
    server.listen(("0.0.0.0", 8000))
    server.run(middleware.WebSocketMiddleware(dispatch))



Пример #52
0
    session['visit_count'] = session.get('visit_count', 0) + 1

    start_response('200 OK', [('Content-Type', 'text/html')])
    return [
        '''
        <!doctype html>
        <title>Session Example</title>
        <h1>Session Example</h1>
        <p>You visited this page %d times.</p>
    ''' % session['visit_count']
    ]


def make_app():
    return SessionMiddleware(application)


if __name__ == '__main__':
    if len(sys.argv) != 4:
        print "python %s ip port server_no" % sys.argv[0]
        sys.exit(1)

    sIp = sys.argv[1]
    lPort = int(sys.argv[2])
    #global server_no
    server_no = int(sys.argv[3])

    server.listen((sIp, lPort))
    app = create_app("svr_conf.cnf")
    server.run(app)
Пример #53
0
            print("ws.wait()...")
            m = ws.wait()
            print("recv msg %s" % m)
            if m is None:
                break
            for p in participants:
                print("send message %s" % m)
                p.send(m)
    finally:
        participants.remove(ws)
    return [""]


def dispatch(environ, start_response):
    """Resolves to the web page or the websocket depending on the path."""
    if environ['PATH_INFO'] == '/chat':
        return websocket_handle(environ, start_response)
    else:
        start_response('200 OK', [('Content-Type', 'text/html')])
        ret = [
            open(
                os.path.join(os.path.dirname(__file__),
                             'templates/websocket_chat.html'), 'rb').read()
        ]
        return ret


if __name__ == "__main__":
    server.listen(("0.0.0.0", 8000))
    server.run(middleware.WebSocketMiddleware(dispatch))
Пример #54
0
    return 'id' in news_item


def add_news_item_to_db(news_item):
    get_mongo_connector(is_async=True).news.insert_one(news_item)


def add_news_handle(environ):
    news_item = json.loads(environ["wsgi.input"].read().decode('utf-8'))
    if is_news_item_valid(news_item):
        add_news_item_to_db(news_item)
        status, res = '200 OK', b''
    else:
        status, res = '400 OK', b'bad data'
    return status, res


def dispatch(environ, start_response):
    if environ['REQUEST_METHOD'] == 'POST' and environ['PATH_INFO'] == '/news/add':
        status, res = add_news_handle(environ)
    else:
        status, res = '404 Not Found', b'not found'
    response_headers = [('Content-type', 'text/plain'), ('Content-Length', str(len(res)))]
    start_response(status, response_headers)
    return [res]


if __name__ == '__main__':
    server.listen(("0.0.0.0", 8000))
    server.run(dispatch)
Пример #55
0
 def run(self, handler):
     from meinheld import server
     server.listen((self.host, self.port))
     server.run(handler)