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...")
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)
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())
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)
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)
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())
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())
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())
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())
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())
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)
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())
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())
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)
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())
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))
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())
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)
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)
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)
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()
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())
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
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())
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())
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())
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())
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())
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)
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())
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())
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())
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)
def run_webapp(self): from meinheld import server, middleware server.listen((self.host, self.port)) server.run(middleware.WebSocketMiddleware(app))
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)
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)
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)
def serve_forever(self): server.run(self.application)
#!/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)
def run(self, handler): from meinheld import server server.listen((self.host, self.port)) server.run(handler)
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)
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)
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))
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)
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))
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)