def mount_apps(app: Flask): app.register_blueprint(powersource) app.wsgi_app = ProxyFix(app.wsgi_app) wsgiapp = WSGILogger(app.wsgi_app, [logging.StreamHandler()], ApacheFormatter(), propagate=False) cherrypy.tree.graft(wsgiapp, "/")
def main(): os.environ.setdefault("DJANGO_SETTINGS_MODULE", "main.settings") execute_from_command_line(['manage.py', 'collectstatic', '--no-input']) application = get_wsgi_application() is_logging = True if is_logging: logging_app = WSGILogger(application, [], logger_name='wsgi', formatter=log_formatter) wsgi_app = tornado.wsgi.WSGIContainer(logging_app) else: wsgi_app = tornado.wsgi.WSGIContainer(application) STATIC_ROOT = settings.STATIC_ROOT MEDIA_ROOT = settings.MEDIA_ROOT print('static path:', STATIC_ROOT) print(' media path:', MEDIA_ROOT) handlers = [ (r'/static/(.*)', tornado.web.StaticFileHandler, { 'path': STATIC_ROOT }), (r'/media/(.*)', tornado.web.StaticFileHandler, { 'path': MEDIA_ROOT }), (r'.*', tornado.web.FallbackHandler, dict(fallback=wsgi_app)), ] tornado_app = tornado.web.Application(handlers) http_server = tornado.httpserver.HTTPServer(tornado_app) port = 8000 host = '0.0.0.0' print(' visit link: http: //{0}:{1}/'.format('127.0.0.1', port)) http_server.listen(port, address=host) tornado.ioloop.IOLoop.instance().start()
def _app(self, devel=False): self._app_logging() self.log.info("starting up") self._pw_recovery() self._setup_pools() self._setup_colls() m_lostpw = LostPW(self._mongo_colls['lostpw']) m_permissions = Permissions(self._mongo_colls['permissions']) m_roles = Roles(self._mongo_colls['roles']) m_sessions = Sessions(self._mongo_colls['sessions']) m_users = Users(self._mongo_colls['users']) m_aa = AuthenticationAuthorization(m_users, m_sessions) app.install(MetaPlugin(m_lostpw, 'm_lostpw')) app.install(MetaPlugin(m_permissions, 'm_permissions')) app.install(MetaPlugin(m_roles, 'm_roles')) app.install(MetaPlugin(m_sessions, 'm_sessions')) app.install(MetaPlugin(m_users, 'm_users')) app.install(MetaPlugin(m_aa, 'm_aa')) app.install(MetaPlugin(self.config_dict, 'm_config')) app.install(error_catcher) logapp = RequestID( WSGILogger(app, self._acc_logging(), ApacheFormatter())) self.log.info("startup done, now serving") run(app=logapp, host='0.0.0.0', port=self.config.getint('main', 'port'), debug=devel, reloader=devel, server='waitress')
def make_app(): try: os.environ['DB_URL'] except KeyError: print("You must set DB_URL environment variable") return # we don't try to import anything that relies on session until after we've # confirmed the required envvar exists from outlet import db from outlet import middleware from outlet import resources outlet = resources.TransactionResource() client = resources.ClientResource() test = resources.TestResource() app = falcon.API(middleware=[ middleware.JSONTranslator(), middleware.RequireJSON(), middleware.DBSessionManager(db.Session) ]) app.add_route('/', outlet) app.add_route('/test', test) app.add_route('/client-token', client) handlers = [StreamHandler(stream=sys.stdout)] return WSGILogger(app, handlers, formatter=ApacheFormatter(), propagate=False)
def mount_apps(app: Flask): app.wsgi_app = ProxyFix(app.wsgi_app) wsgiapp = WSGILogger(app.wsgi_app, [logging.StreamHandler()], ApacheFormatter(), propagate=False) cherrypy.tree.graft(wsgiapp, "/") cherrypy.tree.mount( None, "/favicon", { "/": { "tools.staticdir.on": True, "tools.staticdir.dir": favicon_dir, "tools.etags.on": True, "tools.etags.autotags": True } }) cherrypy.tree.mount( None, "/public/images", { "/": { "tools.staticdir.on": True, "tools.staticdir.dir": img_dir, "tools.etags.on": True, "tools.etags.autotags": True } })
def create_logged_app(): from requestlogger import WSGILogger, ApacheFormatter handler = logging.FileHandler(str(LOGFILE)) handler.setLevel(logging.INFO) logging.root.addHandler(handler) app = create_app() logged_app = WSGILogger(app, [handler], ApacheFormatter()) return logged_app
def main(port): #Beaker options session_opts = { 'session.type': 'file', 'session.cookie_expires': True, 'session.data_dir': './.cache', 'session.auto': True } #Debug mode ? if port != 80 and port != 443: #Sqlite db file #mydbfile_solarmax = os.path.join(ROOT_PATH, "Solarmax_data2.s3db") #mydbfile_teleinfo = os.path.join(ROOT_PATH, "../teleinfo/Teleinfo_data.s3db") mydbfile_solarmax = os.path.join(ROOT_PATH, "../data/Solarmax_data2.s3db") mydbfile_teleinfo = os.path.join(ROOT_PATH, "../data/Teleinfo_data.s3db") access_log_file = 'access.log' #Run http test server on given port myserver = 'wsgiref' else: #Sqlite db file mydbfile_solarmax = DB_FILE_SOLAR mydbfile_teleinfo = DB_FILE_TELEINFO #Run CherryPy http or https server if port == 80: myserver = 'cherrypy' access_log_file = VAR_LOG_ACCESS elif port == 443: myserver = SSLCherryPyServer access_log_file = VAR_LOG_ACCESS_SSL #Create default bottle application app = default_app() myapp = SessionMiddleware(app, session_opts) handlers = [ TimedRotatingFileHandler(access_log_file, 'd', 7, 90), ] loggingapp = WSGILogger(myapp, handlers, ApacheFormatter()) #Plugins : SQLitePlugin give a connection in each functions with a db parameter install(SQLitePlugin(dbfile=mydbfile_solarmax)) plugin2 = SQLitePlugin(dbfile=mydbfile_teleinfo, keyword='db2') plugin2.name = "sqlite2" install(plugin2) #Run server run(app=loggingapp, host='0.0.0.0', port=port, server=myserver, reload=True)
def _app(self, devel=False): self._setup_pools() self._setup_colls() host = self.config.get('elasticsearch', 'host') port = self.config.get('elasticsearch', 'port') scheme = self.config.get('elasticsearch', 'scheme') endpoint.endpoint = scheme + '://' + host + ':' + port + '/' permissions = Permissions(self._mongo_colls['permissions']) roles = Roles(self._mongo_colls['roles']) users = Users(self._mongo_colls['users']) aa = AuthenticationAuthorization(users=users, roles=roles, permissions=permissions) app.install(MetaPlugin(permissions, 'm_permissions')) app.install(MetaPlugin(roles, 'm_roles')) app.install(MetaPlugin(users, 'm_users')) app.install(MetaPlugin(aa, 'm_aa')) app.install(error_catcher) # access log logger acc_handlers = [] try: access_log = self.config.get('file:logging', 'acc_log') access_retention = self.config.getint('file:logging', 'acc_retention') acc_handlers.append( TimedRotatingFileHandler(access_log, 'd', access_retention)) except (configparser.NoOptionError, configparser.NoSectionError): pass logapp = WSGILogger(app, acc_handlers, ApacheFormatter()) # application logger app_handlers = [] try: access_log = self.config.get('file:logging', 'app_log') app_retention = self.config.getint('file:logging', 'app_retention') app_handlers.append( TimedRotatingFileHandler(access_log, 'd', app_retention)) except (configparser.NoOptionError, configparser.NoSectionError): pass for handler in app_handlers: app_logger.addHandler(handler) run(app=logapp, host='0.0.0.0', port=self.config.getint('main', 'port'), debug=devel, reloader=devel, server='waitress')
def serve_app(app: Flask, mount_point: str = '/', log_handler: StreamHandler = None): log_handler = log_handler or logging.StreamHandler() app.wsgi_app = ProxyFix(app.wsgi_app) wsgiapp = WSGILogger(app.wsgi_app, [log_handler], ApacheFormatter(), propagate=False) cherrypy.tree.graft(wsgiapp, mount_point)
def _app(self, devel=False): self._app_logging() self.log.info("starting up") self._setup_pools() self._setup_colls() try: host = self.config.get('elasticsearch', 'host') except (configparser.NoOptionError, configparser.NoSectionError): print('please configure the host in the elasticsearch section') sys.exit(1) try: port = self.config.get('elasticsearch', 'port') except (configparser.NoOptionError, configparser.NoSectionError): print('please configure the port in the elasticsearch section') sys.exit(1) try: scheme = self.config.get('elasticsearch', 'scheme') except (configparser.NoOptionError, configparser.NoSectionError): print('please configure the scheme in the elasticsearch section') sys.exit(1) permissions = Permissions(self._mongo_colls['permissions']) roles = Roles(self._mongo_colls['roles']) users = Users(self._mongo_colls['users']) aa = AuthenticationAuthorization(users=users, roles=roles, permissions=permissions) endpoint = scheme + '://' + host + ':' + port self.log.info("this instance is shielding {0}".format(endpoint)) elproxy = ElasticSearchProxy(endpoint) app.install(MetaPlugin(aa, 'm_aa')) app.install(MetaPlugin(elproxy, 'm_elproxy')) app.install(error_catcher) logapp = RequestID( WSGILogger(app, self._acc_logging(), ApacheFormatter())) try: port = self.config.getint('main', 'port') except (configparser.NoOptionError, configparser.NoSectionError): print('please configure the port in the port section') sys.exit(1) self.log.info("startup done, now serving") run(app=logapp, host='0.0.0.0', port=port, debug=devel, reloader=devel, server='waitress')
def main(): parser = argparse.ArgumentParser('onnxrt-server') parser.add_argument('--model', default='/models/model.onnx') parser.add_argument('--host', default='0.0.0.0') parser.add_argument('--port', type=int, default=8001) options = parser.parse_args() load_model(options.model) wrapped = WSGILogger(app, [StreamHandler(stream=sys.stdout)], ApacheFormatter()) bjoern.run(wrapped, options.host, options.port)
def serve_services(app: Flask, cache: Cache): """ Mount the application so it can served by the HTTP server. """ setup_auth(app, cache) setup_dashboard(app, cache) setup_experiment(app, cache) setup_api(app, cache) # this will log requests to stdout app.wsgi_app = ProxyFix(app.wsgi_app) wsgiapp = WSGILogger(app.wsgi_app, [logging.StreamHandler()], ApacheFormatter(), propagate=False) cherrypy.tree.graft(wsgiapp, "/")
def __init__(self, host, port): self.__host = host self.__port = port session_opts = { 'session.type': 'file', 'session.cookie_expires': 60*60*24*30, 'session.data_dir': './data', 'session.auto': True } localApp = SessionMiddleware(app(), session_opts) handlers = [ ] localApp = WSGILogger(localApp, handlers, ApacheFormatter()) run(app=localApp, server='cherrypy', host=self.__host, port=self.__port, debug=True)
def run_server(): # Enable WSGI access logging handlers = [StreamHandler(), ] app_logged = WSGILogger(app, handlers, ApacheFormatter()) cherrypy.tree.graft(app_logged, '/') cherrypy.config.update({ 'server.socket_host': settings.WSGI_SOCKET_HOST, 'server.socket_port': settings.WSGI_SOCKET_PORT, 'engine.autoreload.on': False, 'log.screen': True, 'server.ssl_module': 'builtin', 'server.ssl_certificate': settings.WSGI_SSL_CERT, 'server.ssl_private_key': settings.WSGI_SSL_PRIVKEY, }) # Start the CherryPy WSGI web server cherrypy.engine.start() cherrypy.engine.block()
def main(): global CONFIG, PVS, HISTORY, app import argparse, sys parser = argparse.ArgumentParser() parser.add_argument('--host', default='0.0.0.0', help='The host (IP address) the web server should listen on.') parser.add_argument('--port', default=4913, help='The port the web server should listen on.') parser.add_argument('--config', '-c', required=True, help='The config file with the definition of process variables and EPICS hosts.') parser.add_argument('--server', default='wsgiref', help='Server engine to run the application. Valid choices: ' + ', '.join(server_names) + '. ' 'The default is wsgiref (try bjoern or paste for high performance and read https://goo.gl/SmPFZb).') parser.add_argument('--logfile', help='If provided, the server will log requests to this file in "Apache format".') parser.add_argument('--debug', action='store_true', help='Set the debug mode of the web server.') args = parser.parse_args() with open(args.config, 'r') as f: try: CONFIG = json.load(f) except Exception as e: sys.stderr.write("Error loading --config file.\n") sys.stderr.write(str(e) + "\n") sys.exit(1) CONFIG['PV_lookup'] = {} for i, pv in enumerate(CONFIG['PVs']): pv['value'] = float('nan') pv['unit'] = None pv['precision'] = None pv['classes'] = 'disconnected' PVS[pv['name']] = epics.PV(pv['name'], auto_monitor=True, form='ctrl', callback=cb_value_update, connection_callback=cb_connection_change) CONFIG['PV_lookup'][pv['name']] = i HISTORY[pv['name']] = [] if args.logfile: handlers = [ TimedRotatingFileHandler(args.logfile, when='W0', interval=1) , ] app = WSGILogger(app, handlers, ApacheFormatter()) run(app, host=args.host, port=args.port, debug=args.debug, server=args.server)
def run_cherrypy(app): import cherrypy from requestlogger import WSGILogger, ApacheFormatter # # main app logged_app = WSGILogger(app, app.logger.handlers, ApacheFormatter()) cherrypy.tree.graft(logged_app, '/') # # serve static files cherrypy.tree.mount(None, '/static', config={ '/': { 'tools.staticdir.on': True, 'tools.staticdir.dir': app.static_folder }, }) # # run server cherrypy.server.socket_host = '0.0.0.0' cherrypy.config.update({'server.socket_port': 5000}) cherrypy.engine.start() cherrypy.engine.block()
def http_requests_logger(app: Flask, stream_handler: StreamHandler = None) -> WSGILogger: if not stream_handler: stream_handler = StreamHandler() return WSGILogger( app.wsgi_app, [stream_handler], ApacheFormatter(), propagate=False)
def check_host_http_header(): if request.headers.get('host') not in accepted_hosts: return redirect(canonical_url, code=301) def add_api_headers(resp): resp.headers['Access-Control-Allow-Origin'] = '*' resp.mimetype = 'text/plain' return resp update_status = Thread(target=trackon.update_outdated_trackers) update_status.daemon = True update_status.start() get_trackerlist_project_list = Thread(target=trackerlist_project.main) get_trackerlist_project_list.daemon = True get_trackerlist_project_list.start() handlers = [ FileHandler('access.log'), ] app = WSGILogger(app, handlers, ApacheFormatter()) server = Server(('0.0.0.0', 8080), app) if __name__ == '__main__': try: server.start() except KeyboardInterrupt: server.stop()
from requestlogger import WSGILogger, ApacheFormatter from app import app application = WSGILogger(app.wsgi_app, [], formatter=ApacheFormatter(), ip_header='HTTP_X_FORWARDED_FOR') if __name__ == "__main__": app.run()
def application(environ, start_response): response_encoder = ResponseEncoder(environ=environ, start_response=start_response) try: return handle_path(environ, start_response, response_encoder) except Exception as ex: response = handle_exception( ex, response_encoder, message="An error occurred on the server side, " "please contact technical support.") LOGGER.debug("Error response: " + str(response)) return response logging_app = WSGILogger(application, [FileHandler("access.log")], ApacheFormatter()) logging_app.logger.propagate = False if __name__ == '__main__': from beaker.middleware import SessionMiddleware from cherrypy import wsgiserver parser = argparse.ArgumentParser() parser.add_argument(dest="config") args = parser.parse_args() # global ACR_VALUES # ACR_VALUES = CONF.ACR_VALUES session_opts = { 'session.type': 'memory',
help='Listen to incoming connections via IPv6 instead of IPv4.') parser.add_argument('-d', '--debug', action='store_true', help='Start in debug mode (with verbose HTTP error pages.') parser.add_argument('-l', '--log-file', help='The file to store the server log in.') parser.add_argument('-b', '--db-file', default=DEFAULT_DB_FILE, help='The db to store the location information in.') args = parser.parse_args() if args.debug and args.ipv6: args.error('You cannot use IPv6 in debug mode, sorry.') EVENTS = filedict.FileDict(filename=args.db_file) for key in EVENTS: update_latest(EVENTS[key]) if args.log_file: try: from requestlogger import WSGILogger, ApacheFormatter from logging.handlers import TimedRotatingFileHandler handlers = [ TimedRotatingFileHandler(args.log_file, 'd', 7) , ] interface = WSGILogger(interface, handlers, ApacheFormatter()) except ImportError: print('Missing module wsgi-request-logger. Cannot enable logging.') if args.debug: run(interface, host='0.0.0.0', port=args.port, debug=True, reloader=True) else: if args.ipv6: # CherryPy is Python3 ready and has IPv6 support: run(interface, host='::', server='cherrypy', port=args.port) else: run(interface, host='0.0.0.0', server='cherrypy', port=args.port)
channel = int(myform['channel']) operator.watch_channel(channel) elif action == "watch_cbeebies": operator.watch_channel(124) elif action == "watch_tv": operator.watch_tv() elif action == "watch_bd": operator.watch_bd() elif action == "turn_off": operator.all_off() elif action == "watch_fire": operator.watch_fire() elif action == "pvr_power": operator.do_pvr_power() elif action == "pvr_on": operator.do_pvr_on() return "OK\n" if __name__ == "__main__": root = logging.getLogger() root.setLevel(logging.DEBUG) ch = logging.StreamHandler(sys.stdout) ch.setLevel(logging.DEBUG) formatter = logging.Formatter( '%(asctime)s - %(name)s - %(levelname)s - %(message)s') ch.setFormatter(formatter) root.addHandler(ch) loggingapp = WSGILogger(app, [ch], ApacheFormatter()) waitress.serve(loggingapp, host='0.0.0.0', port=1025)
def run_server(info, host, port, reload, debugger, eager_loading, debug, wsgi): """Runs a local development server for the Flask application. This local server is recommended for development purposes only but it can also be used for simple intranet deployments. By default it will not support any sort of concurrency at all to simplify debugging. The reloader and debugger are by default enabled if the debug flag of Flask is enabled and disabled otherwise. This is very similar to flask.cli.run_command; with the main addition of the --wsgi flag """ info.app_import_path = 'idb.data_api.api:app' info.debug = debug from idb import config if reload is None: reload = info.debug if debugger is None: debugger = info.debug if eager_loading is None: eager_loading = not reload if wsgi is None: if (debug or debugger or reload or config.ENV in ('dev', )): wsgi = 'werkzeug' else: wsgi = 'gevent' if wsgi == 'werkzeug': from werkzeug.serving import run_simple from flask.cli import DispatchingApp app = DispatchingApp(info.load_app, use_eager_loading=eager_loading) # Extra startup messages. This depends a but on Werkzeug internals to # not double execute when the reloader kicks in. if os.environ.get('WERKZEUG_RUN_MAIN') != 'true': # If we have an import path we can print it out now which can help # people understand what's being served. If we do not have an # import path because the app was loaded through a callback then # we won't print anything. if info.app_import_path is not None: print("Werkzeug server @ http://{0}:{1}/ ENV={2}".format( host, port, config.ENV), file=sys.stderr) if info.debug is not None: print(' * Forcing debug %s' % (info.debug and 'on' or 'off')) run_simple(host, port, app, use_reloader=reload, use_debugger=debugger, threaded=False, passthrough_errors=True) elif wsgi == 'gevent': from gevent.pool import Pool from gevent.wsgi import WSGIServer from idb.helpers.logging import idblogger from requestlogger import WSGILogger, ApacheFormatter logger = idblogger.getChild('api') from werkzeug.contrib.fixers import ProxyFix logger.info("gevent server @ http://%s:%s/ ENV=%s", host, port, config.ENV) app = info.load_app() app = WSGILogger(app, [], ApacheFormatter()) app.logger = logger.getChild('r') app = ProxyFix(app) http_server = WSGIServer(('', 19197), app, spawn=Pool(1000), log=None) http_server.serve_forever() else: raise ValueError('Unknown wsgi backend type', wsgi)
#WebApi/v1/application.wsgi import importlib import os, sys sys.path.insert(0, "home/pi/RaspDataLogger/DataloggerWebApp/WebApi/v1") import bottle from requestlogger import WSGILogger, ApacheFormatter from logging import FileHandler application = bottle.default_app() import web_api_service handlers = [ FileHandler( "/home/pi/RaspDataLogger/DataloggerWebApp/WebApi/v1/logs/v1_restapi.log" ), ] application = WSGILogger(application, handlers, ApacheFormatter()) #bottle.run(application, host='localhost', port=8080)