Ejemplo n.º 1
0
def main():
    app = create_app()

    log_fmt = logging.Formatter("[%(asctime)s] %(module)s "
                                "%(levelname)s %(message)s")

    suggestion_log_path = os.path.join(app.instance_path, 'database.log')
    suggestion_handler = logging.FileHandler(suggestion_log_path)
    suggestion_handler.setFormatter(log_fmt)
    database.log.addHandler(suggestion_handler)

    import sys
    if len(sys.argv) > 1:
        cmd = sys.argv[1]
    else:
        cmd = 'runserver'

    if cmd == 'runserver':
        app.run(debug=True)
    elif cmd == 'shell':
        from code import interact
        with app.test_request_context():
            interact(local={'app': app})
    elif cmd == 'fastcgi':
        from flup.server.fcgi import WSGIServer
        error_log_path = os.path.join(app.instance_path, 'error.log')
        error_handler = logging.FileHandler(error_log_path)
        error_handler.setFormatter(log_fmt)
        error_handler.setLevel(logging.ERROR)
        logging.getLogger().addHandler(error_handler)
        sock_path = os.path.join(app.instance_path, 'fcgi.sock')
        server = WSGIServer(app, bindAddress=sock_path, umask=0)
        server.run()
Ejemplo n.º 2
0
def _runFlup(app, config, mode):
    """Run WsgiDAV using flup.server.fcgi, if Flup is installed."""
    try:
        # http://trac.saddi.com/flup/wiki/FlupServers
        if mode == "flup-fcgi" or "runfcgi":
            from flup.server.fcgi import WSGIServer, __version__ as flupver
        elif mode == "flup-fcgi_fork":
            from flup.server.fcgi_fork import WSGIServer, __version__ as flupver
        else:
            raise ValueError    

        if config["verbose"] >= 2:
            print "Running WsgiDAV/%s %s/%s..." % (__version__,
                                                   WSGIServer.__module__,
                                                   flupver)
        server = WSGIServer(app,
                            bindAddress=(config["host"], config["port"]),
#                            bindAddress=("127.0.0.1", 8001),
#                            debug=True,
                            )
        server.run()
    except ImportError, e:
        if config["verbose"] >= 1:
            print "Could not import flup.server.fcgi", e
        return False
Ejemplo n.º 3
0
class FlupFCGIServer(object):
    """Adapter for a flup.server.fcgi.WSGIServer."""
    
    def __init__(self, *args, **kwargs):
        from flup.server.fcgi import WSGIServer
        self.fcgiserver = WSGIServer(*args, **kwargs)
        # TODO: report this bug upstream to flup.
        # If we don't set _oldSIGs on Windows, we get:
        #   File "C:\Python24\Lib\site-packages\flup\server\threadedserver.py",
        #   line 108, in run
        #     self._restoreSignalHandlers()
        #   File "C:\Python24\Lib\site-packages\flup\server\threadedserver.py",
        #   line 156, in _restoreSignalHandlers
        #     for signum,handler in self._oldSIGs:
        #   AttributeError: 'WSGIServer' object has no attribute '_oldSIGs'
        self.fcgiserver._oldSIGs = []
        self.ready = False
    
    def start(self):
        """Start the FCGI server."""
        self.ready = True
        self.fcgiserver.run()
    
    def stop(self):
        """Stop the HTTP server."""
        self.ready = False
        # Forcibly stop the fcgi server main event loop.
        self.fcgiserver._keepGoing = False
        # Force all worker threads to die off.
        self.fcgiserver._threadPool.maxSpare = 0
Ejemplo n.º 4
0
class FlupSCGIServer(object):
    """Adapter for a flup.server.scgi.WSGIServer."""
    
    def __init__(self, *args, **kwargs):
        self.args = args
        self.kwargs = kwargs
        self.ready = False
    
    def start(self):
        """Start the SCGI server."""
        # We have to instantiate the server class here because its __init__
        # starts a threadpool. If we do it too early, daemonize won't work.
        from flup.server.scgi import WSGIServer
        self.scgiserver = WSGIServer(*self.args, **self.kwargs)
        # TODO: report this bug upstream to flup.
        # If we don't set _oldSIGs on Windows, we get:
        #   File "C:\Python24\Lib\site-packages\flup\server\threadedserver.py",
        #   line 108, in run
        #     self._restoreSignalHandlers()
        #   File "C:\Python24\Lib\site-packages\flup\server\threadedserver.py",
        #   line 156, in _restoreSignalHandlers
        #     for signum,handler in self._oldSIGs:
        #   AttributeError: 'WSGIServer' object has no attribute '_oldSIGs'
        self.scgiserver._installSignalHandlers = lambda: None
        self.scgiserver._oldSIGs = []
        self.ready = True
        self.scgiserver.run()
    
    def stop(self):
        """Stop the HTTP server."""
        self.ready = False
        # Forcibly stop the scgi server main event loop.
        self.scgiserver._keepGoing = False
        # Force all worker threads to die off.
        self.scgiserver._threadPool.maxSpare = 0
Ejemplo n.º 5
0
def main():
    app = create_app()

    log_fmt = logging.Formatter("[%(asctime)s] %(module)s " "%(levelname)s %(message)s")

    suggestion_log_path = os.path.join(app.instance_path, "database.log")
    suggestion_handler = logging.FileHandler(suggestion_log_path)
    suggestion_handler.setFormatter(log_fmt)
    database.log.addHandler(suggestion_handler)

    import sys

    if len(sys.argv) > 1:
        cmd = sys.argv[1]
    else:
        cmd = "runserver"

    if cmd == "runserver":
        app.run(debug=True)
    elif cmd == "shell":
        from code import interact

        with app.test_request_context():
            interact(local={"app": app})
    elif cmd == "fastcgi":
        from flup.server.fcgi import WSGIServer

        error_log_path = os.path.join(app.instance_path, "error.log")
        error_handler = logging.FileHandler(error_log_path)
        error_handler.setFormatter(log_fmt)
        error_handler.setLevel(logging.ERROR)
        logging.getLogger().addHandler(error_handler)
        sock_path = os.path.join(app.instance_path, "fcgi.sock")
        server = WSGIServer(app, bindAddress=sock_path, umask=0)
        server.run()
    elif cmd == "update_identities":
        import sync

        with app.test_request_context():
            sync.update_identities()
    elif cmd == "new_people":
        with app.test_request_context():
            database.add_people(line.strip() for line in sys.stdin)
            database.db.session.commit()
Ejemplo n.º 6
0
class FlupFCGIServer(object):
    """Adapter for a flup.server.fcgi.WSGIServer."""
    
    def __init__(self, *args, **kwargs):
        if kwargs.get('bindAddress', None) is None:
            import socket
            if not hasattr(socket.socket, 'fromfd'):
                raise ValueError(
                    'Dynamic FCGI server not available on this platform. '
                    'You must use a static or external one by providing a '
                    'legal bindAddress.')
        self.args = args
        self.kwargs = kwargs
        self.ready = False
    
    def start(self):
        """Start the FCGI server."""
        # We have to instantiate the server class here because its __init__
        # starts a threadpool. If we do it too early, daemonize won't work.
        from flup.server.fcgi import WSGIServer
        self.fcgiserver = WSGIServer(*self.args, **self.kwargs)
        # TODO: report this bug upstream to flup.
        # If we don't set _oldSIGs on Windows, we get:
        #   File "C:\Python24\Lib\site-packages\flup\server\threadedserver.py",
        #   line 108, in run
        #     self._restoreSignalHandlers()
        #   File "C:\Python24\Lib\site-packages\flup\server\threadedserver.py",
        #   line 156, in _restoreSignalHandlers
        #     for signum,handler in self._oldSIGs:
        #   AttributeError: 'WSGIServer' object has no attribute '_oldSIGs'
        self.fcgiserver._installSignalHandlers = lambda: None
        self.fcgiserver._oldSIGs = []
        self.ready = True
        self.fcgiserver.run()
    
    def stop(self):
        """Stop the HTTP server."""
        # Forcibly stop the fcgi server main event loop.
        self.fcgiserver._keepGoing = False
        # Force all worker threads to die off.
        self.fcgiserver._threadPool.maxSpare = self.fcgiserver._threadPool._idleCount
        self.ready = False
Ejemplo n.º 7
0
 def __init__(self, *args, **kwargs):
     from flup.server.fcgi import WSGIServer
     self.fcgiserver = WSGIServer(*args, **kwargs)
     # TODO: report this bug upstream to flup.
     # If we don't set _oldSIGs on Windows, we get:
     #   File "C:\Python24\Lib\site-packages\flup\server\threadedserver.py",
     #   line 108, in run
     #     self._restoreSignalHandlers()
     #   File "C:\Python24\Lib\site-packages\flup\server\threadedserver.py",
     #   line 156, in _restoreSignalHandlers
     #     for signum,handler in self._oldSIGs:
     #   AttributeError: 'WSGIServer' object has no attribute '_oldSIGs'
     self.fcgiserver._oldSIGs = []
     self.ready = False
Ejemplo n.º 8
0
 def start(self):
     """Start the SCGI server."""
     # We have to instantiate the server class here because its __init__
     # starts a threadpool. If we do it too early, daemonize won't work.
     from flup.server.scgi import WSGIServer
     self.scgiserver = WSGIServer(*self.args, **self.kwargs)
     # TODO: report this bug upstream to flup.
     # If we don't set _oldSIGs on Windows, we get:
     #   File "C:\Python24\Lib\site-packages\flup\server\threadedserver.py",
     #   line 108, in run
     #     self._restoreSignalHandlers()
     #   File "C:\Python24\Lib\site-packages\flup\server\threadedserver.py",
     #   line 156, in _restoreSignalHandlers
     #     for signum,handler in self._oldSIGs:
     #   AttributeError: 'WSGIServer' object has no attribute '_oldSIGs'
     self.scgiserver._installSignalHandlers = lambda: None
     self.scgiserver._oldSIGs = []
     self.ready = True
     self.scgiserver.run()
Ejemplo n.º 9
0
					print I_N_P_U_T""" % code

    from os import urandom
    random_filename = '/tmp/' + urandom(10).encode('hex')
    f = open(random_filename, 'w')
    f.write(python_code)
    f.close()

    f = open('log/code', 'a')
    f.write(request.remote_addr + "\n" + code + "\r\n-------------\r\n")
    f.close()

    result = subprocess.Popen('python %s' % (random_filename),
                              shell=True,
                              stdout=subprocess.PIPE).communicate()[0]

    os.remove(random_filename)

    HTML += "\n\t\t\t\t-----------------------------------\n\t\t\t\t<strong style='color:White;'>%s</strong>\n</pre>" % result
    return HTML


if __name__ == "__main__":
    if (sys.argv[1] == 'test'):
        app.run(host='0.0.0.0', port=4000, debug=True)
    else:
        PORT = 40002
        print '------------------------'
        print 'Running on port', int(PORT)
        WSGIServer(app, multithreaded=True,
                   bindAddress=('0.0.0.0', int(PORT))).run()
Ejemplo n.º 10
0
 def run(self, handler):
     from flup.server.fcgi import WSGIServer
     WSGIServer(handler, bindAddress=(self.host, self.port)).run()
Ejemplo n.º 11
0
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

import logging

from flup.server.fcgi import WSGIServer
from talkatv import app

# Explicitly set app.debug to false, otherwise flask will swallow any exceptions
# that are raised from the app.
app.debug = False

if __name__ == '__main__':
    # Set up logging, even though app.debug is off we'll probably want the logs.
    handler = logging.StreamHandler()
    handler.setFormatter(logging.Formatter(app.debug_log_format))
    app.logger.addHandler(handler)
    app.logger.setLevel(logging.DEBUG)

    app.logger.info('Starting WSGI server on {0}'.format(
        app.config['WSGI_BIND_ADDR']))
    WSGIServer(app, bindAddress=app.config['WSGI_BIND_ADDR']).run()
Ejemplo n.º 12
0
session = web.session.Session(app, web.session.DiskStore('sessions'))
web.config._session = session


def notfound():
    return web.notfound(render.notfound())


app.notfound = notfound
app.add_processor(web.loadhook(auth_admin))
app.add_processor(web.unloadhook(baseutils.assert_closed))

if __name__ == '__main__':
    if len(sys.argv) == 1:
        app.run()
    elif sys.argv[1] == 'deploy':
        #    if "deploy" in sys.argv:
        from flup.server.fcgi import WSGIServer
        func = app.wsgifunc()
        server_address = '/tmp/nowater_novel.sock'
        WSGIServer(
            func,
            bindAddress=server_address,
            maxSpare=16,
            minSpare=16,
            #            maxRequests=128,
            #            maxChildren=32
        ).run()
else:
    application = app.wsgifunc()
Ejemplo n.º 13
0
#!/usr/bin/python


def myapp(environ, start_response):
    start_response('200 OK', [('Content-Type', 'text/plain')])
    return ['PONG']


from flup.server.fcgi import WSGIServer
WSGIServer(myapp).run()
Ejemplo n.º 14
0
    logger.info("%s replies with %s results" %
                (VEP.getRESTserver(), len(rows)))

    # check if assembly is correct in each variation.
    # SUPPORTED_ASSEMBLIES[assembly] is a dictionary where keys are SNPchimp
    # assemblies, and values are HARD CODED ensembl assemblies
    logger.debug("Checking if assembly is supported...")

    try:
        VEP.CheckAssembly(SUPPORTED_ASSEMBLIES[assembly])
    except EnsEMBL.VEP.VePException as e:
        message = "Assembly '%s' is not supported by EnsEMBL: %s" % (assembly,
                                                                     e)
        logger.critical(message)
        return mytemplate.render(header=[], rows=[], message=message)

    # now transforming ensembl names in link
    logger.debug("Add html link to table...")
    rows = linkifyTable(rows, header, animal)
    logger.debug("completed!")

    # Script finish here
    logger.info("CGI script finished")

    # print data with mako templayes
    return mytemplate.render(header=header, rows=rows)


if __name__ == '__main__':
    WSGIServer(myapp, bindAddress=('0.0.0.0', 8000), umask=0).run()
Ejemplo n.º 15
0
#!/usr/bin/env python
from webapp import create_app

app = create_app('config.cfg')

from flup.server.fcgi import WSGIServer

WSGIServer(app, bindAddress='/tmp/webapp.sock').run()
Ejemplo n.º 16
0
                        default='0.0.0.0',
                        help='accesible address')
    parser.add_argument('-p', '--port', default=5125, type=int, help='port')
    parser.add_argument('-d',
                        '--debug',
                        action='store_true',
                        help='debug mode')

    return parser.parse_args(argv[1:])


if __name__ == "__main__":
    args = parse_arg(sys.argv)
    controler = Controler(os.path.abspath('../model'))
    # emotions = np.array(controler.list_model()['LJ40K_svm'])
    emotions = np.array(controler.list_model()['YAHOO_svm'])
    logger = Logger()

    if args.debug:
        args.port += 1
        app.run(args.address,
                args.port,
                debug=False,
                threaded=True,
                use_reloader=False)
    else:
        print "* Running on http://{}:{}/".format(args.address, args.port)
        WSGIServer(app,
                   multithreaded=True,
                   bindAddress=(args.address, args.port)).run()
Ejemplo n.º 17
0
 def _mainloopPeriodic(self):
     WSGIServer._mainloopPeriodic(self)
     if getmtime(__file__) != START_TIME:
         self._keepGoing = False
Ejemplo n.º 18
0
Archivo: lawn.py Proyecto: mgax/Lawn
 def handle(self, app):
     _error_log(os.path.join(app.instance_path, 'error.log'))
     from flup.server.fcgi import WSGIServer
     sock_path = os.path.join(app.instance_path, 'fcgi.sock')
     server = WSGIServer(app, bindAddress=sock_path, umask=0)
     server.run()
Ejemplo n.º 19
0
def run( app=None, components=(), method=STANDALONE, name="retro",
root = ".", resetlog=False, address="", port=None, prefix='', asynchronous=False,
sessions=False, withReactor=None, processStack=lambda x:x, runCondition=lambda:True,
onError=None ):
	"""Runs this web application with the given method (easiest one is STANDALONE),
	with the given root (directory from where the web app-related resource
	will be resolved).

	This function is the 'main' for your web application, so this is basically
	the last call you should have in your web application main."""
	if app == None:
		app = Application(prefix=prefix,components=components)
	else:
		for _ in components: app.register(_)
	# We set up the configuration if necessary
	config = app.config()
	if not config: config = Configuration(CONFIG)
	# Adjusts the working directory to basepath
	root = os.path.abspath(root)
	if os.path.isfile(root): root = os.path.dirname(root)
	# We set the application root to the given root, and do a chdir
	os.chdir(root)
	config.setdefault("root",    root)
	config.setdefault("name",    name)
	config.setdefault("logfile", name + ".log")
	if resetlog: os.path.unlink(config.logfile())
	# We set the configuration
	app.config(config)
	# And start the application
	app.start()
	# NOTE: Maybe we should always print it
	#print app.config()
	# We start the WSGI stack
	stack = app._dispatcher
	stack = processStack(stack)
	# == FCGI (Flup-provided)
	#
	if method == FCGI:
		if not has(FLUP):
			raise ImportError("Flup is required to run FCGI")
		fcgi_address = address or config.get("address")
		fcgi_port    = port or config.get("port")
		if fcgi_port and fcgi_address:
			server = FLUP_FCGIServer(stack, bindAddress=(fcgi_address, fcgi_port))
		elif fcgi_address:
			server = FLUP_FCGIServer(stack, bindAddress=fcgi_address)
		else:
			server = FLUP_FCGIServer(stack)
		server.run()
	#
	# == SCGI (Flup-provided)
	#
	elif method == SCGI:
		if not has(FLUP):
			raise ImportError("Flup is required to run SCGI")
		fcgi_address = address or config.get("address")
		fcgi_port    = port or config.get("port")
		if fcgi_port and fcgi_address:
			server = FLUP_SCGIServer(stack, bindAddress=(fcgi_address, fcgi_port))
		elif fcgi_address:
			server = FLUP_SCGIServer(stack, bindAddress=fcgi_address)
		else:
			server = FLUP_SCGIServer(stack)
		server.run()
	#
	# == CGI
	#
	elif method == CGI:
		environ         = {} ; environ.update(os.environ)
		# From <http://www.python.org/dev/peps/pep-0333/#the-server-gateway-side>
		environ['wsgi.input']        = sys.stdin
		environ['wsgi.errors']       = sys.stderr
		environ['wsgi.version']      = (1,0)
		environ['wsgi.multithread']  = False
		environ['wsgi.multiprocess'] = True
		environ['wsgi.run_once']     = True
		if environ.get('HTTPS','off') in ('on','1'):
			environ['wsgi.url_scheme'] = 'https'
		else:
			environ['wsgi.url_scheme'] = 'http'
		# FIXME: Don't know if it's the proper solution
		req_uri = environ["REQUEST_URI"]
		script_name = environ["SCRIPT_NAME"]
		if req_uri.startswith(script_name):
			environ["PATH_INFO"]  = req_uri[len(script_name):]
		else:
			environ["PATH_INFO"]  = "/"
		if sessions:
			environ["com.saddi.service.session"] = sessions
		def start_response( status, headers, executionInfo=None ):
			for key, value in headers:
				print ("%s: %s" % (key, value))
			print ()
		# FIXME: This is broken
		res = "".join(tuple(self.dispatcher(environ, start_response)))
		print (res)
		if sessions:
			sessions.close()
	#
	# == GEVENT, BJOERN, ROCKET & WSGI
	#
	elif method in (GEVENT, BJOERN, ROCKET, WSGI):

		host   = config.get("host")
		port   = config.get("port")
		try:
			import reporter as logging
		except:
			import logging
		def application(environ, startResponse):
			# Gevent needs a wrapper
			if "retro.app" not in environ: environ["retro.app"] = stack.app()
			return environ["retro.app"](environ, startResponse)
		def logged_application(environ, startResponse):
			logging.info("{0} {1}".format(environ["REQUEST_METHOD"], environ["PATH_INFO"]))
			if "retro.app" not in environ: environ["retro.app"] = stack.app()
			return environ["retro.app"](environ, startResponse)
		if method == "GEVENT":
			try:
				from gevent import wsgi
			except ImportError:
				raise ImportError("gevent is required to run `gevent` method")
			# NOTE: This starts using gevent's WSGI server (faster!)
			wsgi.WSGIServer((host,port), application, spawn=None).serve_forever()
		elif method == BJOERN:
			try:
				import bjoern
			except ImportError:
				raise ImportError("bjoern is required to run `bjoern` method")
			bjoern.run(logged_application, host, port)
		elif method == ROCKET:
			try:
				import rocket
			except ImportError:
				raise ImportError("rocket is required to run `rocket` method")
			rocket.Rocket((host, int(port)), "wsgi", {"wsgi_app":application}).start()
		elif method == WSGI:
			# When using standalone WSGI, we make sure to wrap RendezVous objects
			# that might be returned by the handlers, and make sure we wait for
			# them -- we could use a callback version instead for specific web
			# servers.
			def retro_rendezvous_wrapper( environ, start_response, request=None):
				results = stack(environ, start_response, request)
				for result in results:
					if isinstance(result, RendezVous):
						result.wait()
						continue
					yield result
			retro_rendezvous_wrapper.stack = stack
			return retro_rendezvous_wrapper
	# == STANDALONE (WSGIREF)
	#
	# elif method == STANDALONE_WSGIREF:
	# 	server_address     = (
	# 		address or app.config("address") or DEFAULT_ADDRESS,
	# 		port or app.config("port") or DEFAULT_PORT
	# 	)
	# 	server = WSGIServer(server_address, WSGIRequestHandler)
	# 	server.set_app(stack)
	# 	socket = server.socket.getsockname()
	# 	print "WSGIREF server listening on %s:%s" % ( socket[0], socket[1])
	# 	try:
	# 		while runCondition: server.handle_request()
	# 	except KeyboardInterrupt:
	# 		print "done"
	#
	# == STANDALONE (Retro WSGI server)
	#
	elif method in (STANDALONE, AIO):
		try:
			import reporter as logging
		except:
			import logging
		server_address     = (
			address or app.config("address") or DEFAULT_ADDRESS,
			int(port or app.config("port") or DEFAULT_PORT)
		)
		stack.fromRetro = True
		stack.app       = lambda: app
		if method == STANDALONE and not asynchronous:
			import retro.wsgi
			try:
				server   = retro.wsgi.WSGIServer(server_address, stack)
				retro.wsgi.onError(onError)
				socket = server.socket.getsockname()
				print ("Retro embedded server listening on %s:%s" % ( socket[0], socket[1]))
			except Exception as e:
				logging.error("Retro: Cannot bind to {0}:{1}, error: {2}".format(server_address[0], server_address[1], e))
				return -1
			# TODO: Support runCondition
			try:
				while runCondition():
					server.handle_request()
			except KeyboardInterrupt:
				print ("done")
		else:
			import retro.aio
			import asyncio
			retro.aio.run(app, server_address[0], server_address[1])
			# TODO: Support runCondition
	else:
		raise Exception("Unknown retro setup method:" + method)
Ejemplo n.º 20
0
 def __init__(self):
     WSGIServer.__init__(self, self.application, debug=False)
Ejemplo n.º 21
0
 def handle(self, app, sock):
     _production_logging(app)
     from flup.server.fcgi import WSGIServer
     server = WSGIServer(app, bindAddress=sock, umask=0, maxThreads=5)
     server.run()
Ejemplo n.º 22
0
#!/usr/bin/env python
import os
from flup.server.fcgi import WSGIServer
import server

wsgi = WSGIServer(server.app,
    bindAddress="/var/www/run/starroamer.sock", umask=0002)

print("running as process %s" % os.getpid())

while wsgi.run():
    reload(server)
    wsgi.application = server.app
    print("application reloaded")
Ejemplo n.º 23
0
        if message:
            headers[0] = ('Content-Type', 'image/png')

            try:
                font = ImageFont.truetype(_FONT_PATH, _FONT_SIZE)
                size = [i.__add__(_OFFSET[0]) for i in font.getsize(message)]

                image = Image.new("RGB", size, _BG_COLOR)
                draw = ImageDraw.Draw(image)
                draw.text(_OFFSET, message, font=font, fill=_FONT_COLOR)

                output = StringIO()
                image.save(output, _FORMAT)
                message = output.getvalue()
                output.close()
            except:
                error = open(_ERROR_IMAGE)
                message = error.read()
                error.close()
    else:
        message = "Usage: http://%s?addr=base64-string" % environ['HTTP_HOST']

    start_response('200 OK', headers)

    return [message]


if __name__ == '__main__':
    WSGIServer(MageHandler, **wsgi_opts).run()
Ejemplo n.º 24
0
    # testLang = u"en";

    # testItems = {
    #     u"Luis Hernández": 1,
    #     u"Mexikói labdarúgó-válogatott": 1,
    #     u"Labdarúgó": 1,
    #     u"CA Boca Juniors": 1,
    #     u"CF Monterrey": 1
    #     }
    # testLang = u"hu";

    # testItems = {
    #     u"باشگاه فوتبال بوکا جونیورز": 1,
    #     u"فوتبال": 1,
    #     u"زبان اسپانیایی": 1,
    #     u"آرژانتین": 1};
    # testLang = u"fa";
   
    # logging.basicConfig(level=logging.DEBUG)

    # recommender = LinkRecommender(lang=testLang, nrecs=2500, verbose=True);
    # recommender.connect();
    # recs = recommender.get_recs(item_map=testItems, \
    #                                 param_map=dict({u'nrecs': 2500,u'lang': testLang}));
    # recommender.close();
    # print "Received %d recommendations." % (len(recs),);

# Also, comment out these if you run from command line
wsgi = WSGIServer(app);
wsgi.run();
Ejemplo n.º 25
0
#!/usr/bin/python
"""
FastCGI server using flup. Reloads on SIGHUP.
"""
import site, os
site.addsitedir(os.path.dirname(__file__))
import restrack.server
from flup.server.fcgi import WSGIServer
import os, sys, logging, site

lh = logging.StreamHandler(sys.stderr)
lh.setFormatter(logging.Formatter(restrack.server.FORMAT))
logging.root.addHandler(lh)
logging.root.setLevel(logging.DEBUG)

f = open('/tmp/restracker.pid', 'w')
f.write(str(os.getpid()))
f.close()

try:
	ws = WSGIServer(restrack.server.restracker_app, bindAddress='/tmp/restracker.sock')
	rerun = ws.run()
finally:
	os.unlink('/tmp/restracker.pid')

if rerun:
	os.spawnv(__file__, sys.argv)

Ejemplo n.º 26
0
from flup.server.fcgi import WSGIServer
from weeklypedia.labs import wsgi_app


wsgi_server = WSGIServer(wsgi_app)


if __name__ == "__main__":
    wsgi_server.run()
Ejemplo n.º 27
0
def fastcgi(wsgi_application,
            spawn=False,
            address=('127.0.0.1', 9000),
            use=os.environ.get("WSGI_FCGI_LIB")):
    "Creates an FastCGI server for wsgi_application."

    if spawn:
        valid_libs = VALID_FCGI_SPAWN
        address = None
    else:
        valid_libs = VALID_FCGI_SERVER

    if use is None:
        use_libs = valid_libs
    else:
        if use.lower() not in valid_libs:
            raise ValueError("Invalid FastCGI library. "
                             "Valid for the selected mode are: {}".format(
                                 ", ".join(valid_libs)))
        use_libs = [use.lower()]

    for lib in use_libs:
        try:
            if lib == "gevent-fastcgi":
                from gevent_fastcgi.server import FastCGIServer
                from gevent_fastcgi.wsgi import WSGIRequestHandler

                request_handler = WSGIRequestHandler(wsgi_application)
                server = FastCGIServer(address,
                                       request_handler,
                                       num_workers=cpu_count())
                sys.stderr.write("FCGI library: gevent-fastcgi\n")
                server.serve_forever()
                break

            elif lib in ("flup", "flup6"):
                from flup.server.fcgi import WSGIServer
                server = WSGIServer(wsgi_application, bindAddress=address)
                sys.stderr.write("FCGI library: flup/flup6\n")
                server.run()
                break

            elif lib == "flipflop":
                from flipflop import WSGIServer
                server = WSGIServer(wsgi_application)

                sys.stderr.write("FCGI library: flipflop\n")
                server.run()
                break

        except (ImportError, SyntaxError):
            continue
        except KeyboardInterrupt:
            sys.stderr.write("\nAborted.\n")
            break
    else:
        if len(use_libs) == 1:
            sys.stderr.write(
                "The selected FastCGI library could not be used.\n")
        else:
            sys.stderr.write("No usable FastCGI library found.\n")
        return 1

    return 0
Ejemplo n.º 28
0
    answer = dns.resolver.query(domain + ".lan", "a")
    for record in answer:
        if record.address == ip:
            break
    else:
        return
    update = dns.update.Update("lan")
    update.delete(domain, "a")
    dns.query.tcp(update, "127.0.0.1")


def domain_manager(env, responde):
    if not env["QUERY_STRING"]:
        return info_page(env, responde)
    params = urlparse.parse_qs(env["QUERY_STRING"])
    if "action" in params and "domain" in params:
        domain = validate_domain(params["domain"][0].decode("utf-8"))
        if domain:
            if "add" in params["action"]:
                domain_add(domain, env["REMOTE_ADDR"])
            elif "delete" in params["action"]:
                domain_delete(domain, env["REMOTE_ADDR"])
    responde("303 Did it. Now go back",
             [("Location", env.get("HTTP_REFERER", env["SCRIPT_NAME"]))])
    return []


if __name__ == "__main__":
    from flup.server.fcgi import WSGIServer
    WSGIServer(domain_manager).run()
Ejemplo n.º 29
0
# http://www.gnu.org/licenses/gpl.html
#
# Contributors:
#     Proxima Centauri srl <*****@*****.**> - initial API and implementation
#-------------------------------------------------------------------------------
#!/usr/bin/python
# -*- coding: utf-8 -*-

from bottle import route, run, request, abort, static_file, template, default_app
import bottle
from gui import *
from gzipper import Gzipper

# set up the application path
# first the static file path
# the second the api path
setup('/static/gui', "/api", "/gui/", "/rrd/graph/")

app = Gzipper(app,
              content_types=set([
                  'text/plain', 'text/html', 'text/css', 'application/json',
                  'application/x-javascript', 'text/xml',
                  'application/javascript', 'application/xml',
                  'application/xml+rss', 'text/javascript', 'image/svg',
                  'image/svg+xml'
              ]))

if __name__ == '__main__':
    from flup.server.fcgi import WSGIServer
    WSGIServer(app, multithreaded=False).run()
Ejemplo n.º 30
0
def runfcgi(socket):
    from flup.server.fcgi import WSGIServer
    app = create_app()
    WSGIServer(app, debug=app.debug, bindAddress=socket, umask=0).run()
Ejemplo n.º 31
0
from flup.server.fcgi import WSGIServer

from pygal import Line

from pp_log import posix_logger
from pp_db import mysql_db, redis_db

#=======================================

logger = posix_logger('pygal.log')
mysql = mysql_db()
redis = redis_db()

if mysql != None: logger.info('mysql connect init ok')
if redis != None: logger.info('redis connect init ok')

#=======================================


def application(env, start_response):
    global logger, mysql, redis
    req = env['REQUEST_URI'].split('/', 2)[2].strip().strip('?')
    logger.debug(req)
    data = redis.get(req)
    if data == None: data = (req + ':Data no found !!!').encode()
    start_response('200 OK', [('Content-Type', 'text/html')])
    return [data]


WSGIServer(application, bindAddress=('127.0.0.1', 9090)).run()
Ejemplo n.º 32
0
Archivo: fcgi.py Proyecto: ajaxj/fkmv
#!/usr/bin/env python
from bak.fkmv import create_app

app = create_app('config.cfg')

from flup.server.fcgi import WSGIServer

WSGIServer(app, bindAddress='/tmp/pypress-master.sock').run()
    sock.bind(('', 9999))
    sock.listen(1)
    while True:
        print 'Waiting for input stream'
        sd, addr = sock.accept()
        print 'Connected input stream from', addr
        data = True
        while data:
            readable = select([sd], [], [], 0.1)[0]
            for s in readable:
                data = s.recv(1024)
                if not data:
                    break
                q = Queue()
                for q in app.queues:
                    q.put(data)
        print 'Lost input stream from', addr
    
 
if __name__ == '__main__':
    
    app = LiveHTTPStreamer()
    server = WSGIServer(app, bindAddress=('', 9998))

    t1 = Thread(target=input_loop, args=[app])
    t1.setDaemon(True)
    t1.start()

    server.run()

Ejemplo n.º 34
0
        return '401 Authentication Required'

    if prj.owner == user:
        return '200 Ok'

    pm = q_get(ProjectMember, project=prj, user=user)
    if pm is not None:
        return '200 Ok'

    return '401 Authentication Required'


if __name__ == '__main__':
    from flup.server.fcgi import WSGIServer
    from flup.server.fcgi_base import FCGI_RESPONDER, FCGI_AUTHORIZER
    addr = sys.argv[1]

    if addr.find(':') != -1:
        addr = addr.split(':')
        addr[1] = int(addr[1])
        addr = tuple(addr)

    if len(sys.argv) >= 3 and sys.argv[2] == '-d':
        do_daemon(sys.argv[3])

    print 'serve in', sys.argv[1], '...'

    WSGIServer(authapp,
               bindAddress=addr,
               roles=[FCGI_RESPONDER, FCGI_AUTHORIZER]).run()
Ejemplo n.º 35
0
def server(num):
    WSGIServer(receiver.r_app,
               bindAddress=(config.get('server', 'host'), 8000 + num)).run()
Ejemplo n.º 36
0
from flup.server.fcgi import WSGIServer
from main import app
if __name__ == '__main__':
    #help (WSGIServer)
    WSGIServer(app,
               multithreaded=1,
               multiprocess=0,
               debug=1,
               bindAddress=('127.0.0.1', 8080)).run()
Ejemplo n.º 37
0
    def runServer(self, services=[]):
        """Starts up the server. It (will) support different config options via the config plugin."""
        self.add_routes()
        #debug = self.general_section.get("debug")
        host = self.general_section.get("host")
        use_reloader = ast.literal_eval(
            self.general_section.get("use_reloader"))
        app_port = int(self.general_section.get("port"))
        cFCGI = ast.literal_eval(self.fcgi_section.get("enabled"))
        fcgi_port = int(self.fcgi_section.get("port"))
        must_have_client_cert = ast.literal_eval(
            self.certificates_flask_section.get("force_client_certificate"))
        if cFCGI:
            logger.info("registering fcgi server at %s:%i", host, fcgi_port)
            from flup.server.fcgi import WSGIServer
            WSGIServer(self._app, bindAddress=(host, fcgi_port)).run()
        else:
            logger.info("registering app server at %s:%i", host, app_port)
            # this workaround makes sure that the client cert can be acquired later (even when running the development server)
            # copied all this stuff from the actual flask implementation, so we can intervene and adjust the ssl context
            # self._app.run(host=host, port=app_port, ssl_context='adhoc', debug=debug, request_handler=ClientCertHTTPRequestHandler)

            # the code from flask's `run...`
            # see https://github.com/mitsuhiko/flask/blob/master/flask/app.py
            #options = {}
            try:
                # now the code from werkzeug's `run_simple(host, app_port, self._app, **options)`
                # see https://github.com/mitsuhiko/werkzeug/blob/master/werkzeug/serving.py
                #from werkzeug.debug import DebuggedApplication
                import socket
                #application = DebuggedApplication(self._app, True)

                # Set up an SSL context
                context = SSL.Context(SSL.SSLv23_METHOD)
                certs_path = os.path.normpath(
                    os.path.join(os.path.dirname(__file__), "../../..",
                                 "cert"))
                context_crt = os.path.join(certs_path, "server.crt")
                context_key = os.path.join(certs_path, "server.key")
                try:
                    context.use_certificate_file(context_crt)
                    context.use_privatekey_file(context_key)
                except Exception as e:
                    logger.critical(
                        "error starting flask server. Cert or key is missing under %s",
                        certs_path)
                    sys.exit(e)

                def inner():
                    #server = serving.make_server(host, app_port, self._app, False, 1, ClientCertHTTPRequestHandler, False, 'adhoc')
                    server = serving.make_server(host,
                                                 app_port,
                                                 self._app,
                                                 False,
                                                 1,
                                                 ClientCertHTTPRequestHandler,
                                                 False,
                                                 ssl_context=context)
                    #server = serving.make_server(host, app_port, self._app, False, 1, ClientCertHTTPRequestHandler, False, ssl_context=(context_crt, context_key))
                    # The following line is the reason why I copied all that code!
                    if must_have_client_cert:
                        # FIXME: what works with web app does not work with cli. Check this out
                        server.ssl_context.set_verify(
                            SSL.VERIFY_PEER | SSL.VERIFY_FAIL_IF_NO_PEER_CERT,
                            lambda a, b, c, d, e: True)
                    # before enter in the loop, start the supplementary services
                    for s in services:
                        s.start()
                    # That's it
                    server.serve_forever()

                address_family = serving.select_ip_version(host, app_port)
                test_socket = socket.socket(address_family, socket.SOCK_STREAM)
                test_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR,
                                       1)
                test_socket.bind((host, app_port))
                test_socket.close()
                # Disable reloader only by explicit config setting
                if use_reloader == False:
                    serving.run_simple(host,
                                       app_port,
                                       self._app,
                                       use_reloader=False)
                else:
                    serving.run_with_reloader(inner, None, 1)
            finally:
                self._app._got_first_request = False
Ejemplo n.º 38
0
    if "lft" in i:
        spd = int(i["lft"][0])
        if spd < -1020:
            G.setup(pinDlyLft1, G.OUT)
            G.setup(pinDlyLft2, G.OUT)
            s.set_servo(pinLft, abs(spd))
        else:
            G.cleanup(pinDlyLft1)
            G.cleanup(pinDlyLft2)
            s.set_servo(pinLft, abs(spd))
    if "rgt" in i:
        spd = int(i["rgt"][0])
        if spd < -1020:
            G.setup(pinDlyRgt1, G.OUT)
            G.setup(pinDlyRgt2, G.OUT)
            s.set_servo(pinRgt, abs(spd))
        else:
            G.cleanup(pinDlyRgt1)
            G.cleanup(pinDlyRgt2)
            s.set_servo(pinRgt, abs(spd))
    if "led" in i:
        if i["led"][0] == "on":
            G.setup(pinLED, G.OUT)
        else:
            G.cleanup(pinLED)


WSGIServer(app).run()

G.cleanup()
Ejemplo n.º 39
0
                    tmpLog.error(errStr)
                    # return internal server error
                    start_response('500 INTERNAL SERVER ERROR',
                                   [('Content-Type', 'text/plain')])
                    return [str(e)]
        if panda_config.entryVerbose:
            tmpLog.debug("done")
        regTime = datetime.datetime.utcnow() - regStart
        tmpLog.info(
            "exec_time=%s.%03d sec, return len=%s B" %
            (regTime.seconds, regTime.microseconds / 1000, len(str(exeRes))))
        # return
        if exeRes == taskbuffer.ErrorCode.EC_NotFound:
            start_response('404 Not Found', [('Content-Type', 'text/plain')])
            return ['not found']
        elif isinstance(exeRes, taskbuffer.ErrorCode.EC_Redirect):
            start_response('302 Redirect', [('Location', exeRes.url)])
            return ['redirect']
        else:
            if retType == 'json':
                start_response('200 OK',
                               [('Content-Type', 'application/json')])
            else:
                start_response('200 OK', [('Content-Type', 'text/plain')])
            return [exeRes]

    # start server
    if panda_config.useFastCGI:
        from flup.server.fcgi import WSGIServer
        WSGIServer(application, multithreaded=False).run()
Ejemplo n.º 40
0
def flup_adapter(host, port):
    # Experimental (Untested).
    from flup.server.fcgi import WSGIServer
    WSGIServer(handle_request, bindAddress=(host, port)).run()
Ejemplo n.º 41
0
def run():
    WSGIServer(dispatch_request, **params).run()
Ejemplo n.º 42
0
 def handle(self, app):
     _production_logging(app)
     from flup.server.fcgi import WSGIServer
     sock_path = os.path.join(app.instance_path, 'fcgi.sock')
     server = WSGIServer(app, bindAddress=sock_path, umask=0)
     server.run()
Ejemplo n.º 43
0
def run_fcgi():
    app = bottle.default_app()
    from flup.server.fcgi import WSGIServer
    WSGIServer(app).run()
Ejemplo n.º 44
0
def run_fcgi(app, args):
    from flup.server.fcgi import WSGIServer
    sock_path = args.fastcgi_socket
    wsgi_server = WSGIServer(app, bindAddress=sock_path, umask=0)
    wsgi_server.run()
Ejemplo n.º 45
0
#!/usr/bin/env python3
# -*- coding: UTF-8 -*-

import cgi
import psycopg2
import sys, os
from flup.server.fcgi import WSGIServer


def app(environ, start_response):
    form = cgi.FieldStorage(fp=environ['wsgi.input'], environ=environ)
    start_response('200 OK', [('Content-Type', 'text/html')])
    con = psycopg2.connect(database="docker",
                           user="******",
                           password='******',
                           host="db",
                           port="5432")
    cur = con.cursor()
    for item in form:
        cur.execute('INSERT INTO postdata (key, value) VALUES (%s, %s)',
                    (item, form.getvalue(item)))
    con.commit()
    yield 'OK'


bindAddress = ('0.0.0.0', int(8888))
WSGIServer(app, bindAddress=bindAddress).run()
Ejemplo n.º 46
0
def wsgi():
    """Run WSGI server for use with an external FCGI server"""
    read_env()
    WSGIServer(app).run()
Ejemplo n.º 47
0
                self.send_response (int (statusCode), statusMsg)
                for header, value in headers:
                    self.send_header (header, value)
                self.end_headers()
                self.wsgiSentHeaders = 1
            # Send the data
            self.wfile.write (data)

    class WSGIServer (SocketServer.ThreadingMixIn, BaseHTTPServer.HTTPServer):
        def __init__(self, func):
            BaseHTTPServer.HTTPServer.__init__(self, ("0.0.0.0", int(port)), WSGIHandler)
            self.app = func
            self.serverShuttingDown = 0

    print "Launching server: http://0.0.0.0:"+str(port)+"/"
    WSGIServer(func).serve_forever()
    

def runfcgi(func):
    from flup.server.fcgi import WSGIServer
    class MyServer(WSGIServer):            
        def error(self, req):
            w = req.stdout.write
            internalerror()
            w('Status: '+context.status+'\r\n')
            for (h, v) in context.headers:
                w(h+': '+v+'\r\n')
            w('\r\n'+context.output)
                
    return MyServer(func, multiplexed=True).run()
Ejemplo n.º 48
0
def get_info(lat, lon):
    return json.dumps({
        'inches': howmuchsnow.how_much_snow_gps((lat, lon), conn),
        'coords': howmuchsnow.make_coordinates(lat, lon)
    })


def application(environ, start_response):
    start_response('200 OK', [('Content-Type', 'text/html')])
    parameters = parse_qs(environ.get('QUERY_STRING', ''))
    if 'faq' in parameters:
        yield pages.faq
    elif 'geo' in parameters:
        lat = float(parameters['lat'][0])
        lon = float(parameters['lon'][0])
        # inches = howmuchsnow.how_much_snow_gps((lat, lon), conn)
        # yield inches
        yield get_info(lat, lon)
    elif 'ip' in parameters:
        ip_addr = environ['REMOTE_ADDR']
        lat, lon = ipv4_to_gps(ip_addr)
        # inches = howmuchsnow.how_much_snow_ipv4(ip_addr, conn)
        # yield inches
        yield get_info(lat, lon)
    else:
        yield pages.homepage


if __name__ == '__main__':
    WSGIServer(application).run()
Ejemplo n.º 49
0
from flup.server.fcgi import WSGIServer
from weeklypedia.labs import wsgi_app

wsgi_server = WSGIServer(wsgi_app)

if __name__ == '__main__':
    wsgi_server.run()
Ejemplo n.º 50
0
 # And start the application
 app.start()
 # NOTE: Maybe we should always print it
 #print app.config()
 # We start the WSGI stack
 stack = app._dispatcher
 stack = processStack(stack)
 # == FCGI (Flup-provided)
 #
 if method == FCGI:
     if not has(FLUP):
         raise ImportError("Flup is required to run FCGI")
     fcgi_address = address or config.get("address")
     fcgi_port = port or config.get("port")
     if fcgi_port and fcgi_address:
         server = FLUP_FCGIServer(stack,
                                  bindAddress=(fcgi_address, fcgi_port))
     elif fcgi_address:
         server = FLUP_FCGIServer(stack, bindAddress=fcgi_address)
     else:
         server = FLUP_FCGIServer(stack)
     server.run()
 #
 # == SCGI (Flup-provided)
 #
 elif method == SCGI:
     if not has(FLUP):
         raise ImportError("Flup is required to run SCGI")
     fcgi_address = address or config.get("address")
     fcgi_port = port or config.get("port")
     if fcgi_port and fcgi_address:
         server = FLUP_SCGIServer(stack,
Ejemplo n.º 51
0
	# And start the application
	app.start()
	# NOTE: Maybe we should always print it
	#print app.config()
	# We start the WSGI stack
	stack = app._dispatcher
	stack = processStack(stack)
	# == FCGI (Flup-provided)
	#
	if method == FCGI:
		if not has(FLUP):
			raise ImportError("Flup is required to run FCGI")
		fcgi_address = address or config.get("address")
		fcgi_port    = port or config.get("port")
		if fcgi_port and fcgi_address:
			server = FLUP_FCGIServer(stack, bindAddress=(fcgi_address, fcgi_port))
		elif fcgi_address:
			server = FLUP_FCGIServer(stack, bindAddress=fcgi_address)
		else:
			server = FLUP_FCGIServer(stack)
		server.run()
	#
	# == SCGI (Flup-provided)
	#
	elif method == SCGI:
		if not has(FLUP):
			raise ImportError("Flup is required to run SCGI")
		fcgi_address = address or config.get("address")
		fcgi_port    = port or config.get("port")
		if fcgi_port and fcgi_address:
			server = FLUP_SCGIServer(stack, bindAddress=(fcgi_address, fcgi_port))
Ejemplo n.º 52
0
 def handle(self, app):
     from flup.server.fcgi import WSGIServer
     sock_path = os.path.join(app.instance_path, 'fcgi.sock')
     server = WSGIServer(app, bindAddress=sock_path, umask=0, maxThreads=5)
     server.run()