def main(): options = parser.parse_args() logging.basicConfig( level=getattr(logging, options.log_level.upper(), logging.INFO), format="[%(asctime)s] %(filename)s:%(lineno)d %(levelname)s %(message)s" ) app.config['DATABASE'] = options.db init_db() app.template_folder = TEMPLATES_PATH app.static_folder = STATIC_PATH log.info("Starting service on http://%s:%d/", options.listen, options.port) if options.debug: log.warning("Running on debug mode not for production.") app.run(host=options.listen, port=options.port, debug=True) else: http_server = WSGIServer((options.listen, options.port), app) with suppress(KeyboardInterrupt): http_server.serve_forever()
def run(interface='0.0.0.0', port=5000): print u" * Server is running at %s:%s" % (interface, port) wsgi = DebuggedApplication(app) http_server = WSGIServer((interface, port), wsgi) http_server.serve_forever()
class DjangoApp(DirtApp): log = logging.getLogger(__name__) def setup(self): self.application = DjangoWSGIApp() if self.settings.DEBUG: from werkzeug import DebuggedApplication self.application = DebuggedApplication(self.application, evalex=True) settings.get_api = self.settings.get_api self.server = WSGIServer(self.settings.http_bind, self.application, log=None) def serve_dirt_rpc(self): """ Calls ``DirtApp.serve`` to start the RPC server, which lets callers use the debug API. """ if getattr(self.settings, "bind_url", None) is None: self.log.info("no `bind_url` specified; RPC server not starting.") return DirtApp.serve(self) def serve(self): self.api_thread = gevent.spawn(self.serve_dirt_rpc) self.log.info("Starting server on http://%s:%s...", *self.settings.http_bind) self.server.serve_forever() def get_api(self, *args, **kwargs): """ The DjangoApp returns an empty API object by default so that tab completion of the API will work. Feel free to override this method. """ return object()
def main(argv): global port, log, pidfile, interface try: opts, args = getopt.getopt(argv, "p:l:i:h", ["pidfile="]) except getopt.GetoptError: usage() sys.exit(2) for opt, arg in opts: if opt == '-h': usage() sys.exit() elif opt == '-p': port = int(arg) elif opt == '-l': try: log = open(arg, 'w') except: sys.stderr.write("Can not open log file.\n") sys.exit(1) elif opt == '-i': interface = arg elif opt == '--pidfile': pidfile = arg if pidfile: with open(pidfile, 'w') as f: f.write(str(os.getpid())) signal.signal(signal.SIGTERM, shutdown_handler) signal.signal(signal.SIGINT, shutdown_handler) http_server = WSGIServer((interface, port), application=app, log=log) try: http_server.serve_forever() except: clean_pidfile() sys.exit() # Don't print backtrace for KeyboardInterrupt
def start_server(): WSGIServer.handler_class = ErrorHandler server = WSGIServer(("", PORT), app) print "Please open a web browser to http://127.0.0.1:", PORT ferr = open('out.log', 'w') server.log = ferr #redirect the server log server.serve_forever()
def gevent(): from gevent.wsgi import WSGIServer bipbalance_client.logger.info("Running Gevent on port %s", config.port) http_server = WSGIServer(('', config.port), bipbalance_client) http_server.serve_forever()
def serve(self, port, app, block=False): server = WSGIServer(("", port), app) server.handler_class = CustomHandler if not block: self.greenlets.append(gevent.spawn(server.serve_forever)) else: server.serve_forever()
def main(): if config["ENV"] == "local": app.debug = True print "Explainer listening on http://%s" % config["EXPLAINER"] sys.stdout.flush() http_server = WSGIServer((config["EXPLAINER"].split(":")[0], int(config["EXPLAINER"].split(":")[1])), app) http_server.serve_forever()
def execute_from_cli(hostname, cluster, with_ui, peers): polar_client = PolarClient(hosts=peers, handler=GeventHandler()) polar_client.start() crow = CrowContext(polar_client, hostname, cluster) actor_name = "%s-%s" % (hostname, cluster) actor_system = ActorSystem( polar_client=polar_client, name=actor_name ) actor_system.actor_of(KeepRpcActor.props( crow=crow, polar_client=polar_client )) crow.announce() if with_ui == True: from keep.ui import app app.config["actor_flask"] = actor_system app.config["polar_client"] = polar_client # adapt polar client wo work with the WSGI adapter http_server = WSGIServer(('', 5000), app) print "Stared UI on port 5000" http_server.serve_forever() gevent.wait()
class GeventWSGIServer(object): """Adapter for a gevent.wsgi.WSGIServer.""" def __init__(self, *args, **kwargs): from eden.web.patch import patch_cherrypy patch_cherrypy() self.args = args self.kwargs = kwargs self.ready = False def start(self): """Start the GeventWSGIServer.""" # We have to instantiate the server class here because its __init__ from gevent.wsgi import WSGIServer self.ready = True LOGGER.debug('Starting Gevent WSGI Server...') self.httpd = WSGIServer(*self.args, **self.kwargs) self.httpd.serve_forever() def stop(self): """Stop the HTTP server.""" LOGGER.debug('Stoping Gevent WSGI Server...') self.ready = False self.httpd.stop()
def serve_forever(self,*args,**kw): from handlers_base import APIHandler from process_reader import ProcessReader from u2py.config import reader_path try: APIHandler.readers = [ProcessReader(**reader_kw) for reader_kw in reader_path] [reader.open() for reader in APIHandler.readers] def signal_handler(sgn,frame): logging.debug('Stop signal catched[%i].' % (sgn)) self.stop() logging.debug('Web-server stopped.') try: if hasattr(signal,'SIGBREAK'): signal.signal(signal.SIGBREAK, signal_handler) #maps to CTRL_BREAK_EVENT on windows signal.signal(signal.SIGINT, signal_handler) #maps to CTRL_C_EVENT for windows signal.signal(signal.SIGTERM, signal_handler) except ValueError: print 'Signals only works in main thread' WSGIServer.serve_forever(self,*args,**kw) except KeyboardInterrupt: pass finally: [reader.close() for reader in APIHandler.readers]
def run_server(port=5000, debug=False): app = twidder.app if debug: app = werkzeug.debug.DebuggedApplication(app) http_server = WSGIServer(('', port), app, handler_class=WebSocketHandler) http_server.serve_forever()
def gevent_run(app, port=5000, log=None, error_log=None, address='', monkey_patch=True, start=True, **kwargs): # pragma: no cover """Run your app in gevent.wsgi.WSGIServer :param app: wsgi application, ex. Microservice instance :param port: int, listen port, default 5000 :param address: str, listen address, default: "" :param log: logger instance, default app.logger :param error_log: logger instance, default app.logger :param monkey_patch: boolean, use gevent.monkey.patch_all() for patching standard modules, default: True :param start: boolean, if True, server will be start (server.serve_forever()) :param kwargs: other params for WSGIServer(**kwargs) :return: server """ if log is None: log = app.logger if error_log is None: error_log = app.logger if monkey_patch: from gevent import monkey monkey.patch_all() from gevent.wsgi import WSGIServer http_server = WSGIServer((address, port), app, log=log, error_log=error_log, **kwargs) if start: http_server.serve_forever() return http_server
def main(): parser = argparse.ArgumentParser() parser.add_argument('-p', '--port', help='server port', type=int, default=9000) args = parser.parse_args() http_server = WSGIServer(('', args.port), app) http_server.serve_forever()
def start_servers(upstream_dns, ifname): dns_queue = Queue() dnsserver = PACDNSServer(upstream_dns, queue=dns_queue) dnsserver.start() gevent.spawn(handle_subscriptions, dns_queue) server = WSGIServer(('0.0.0.0', 8081), app) server.serve_forever()
def run_server(host=None, port=None, workers=None, debug=None, logfile=None, stdout=None, loglevel=None): if not host: host = settings.server_host if not port: port = settings.server_port if workers is not None: settings.workers = workers if debug: settings.debug = True try: proctitle = settings.proctitle except AttributeError: proctitle = 'geweb' setproctitle(proctitle) log.info('Starting HTTP server at %s:%d' % (host, port)) pool = Pool(10000) server = WSGIServer("%s:%s" % (host, port), handle, spawn=pool) server.init_socket() for i in xrange(settings.workers - 1): pid = gevent.fork() if pid == 0: break server.serve_forever()
def start_service(self): """ Starts the web server. """ if self.http_server is not None: self.stop_service() if self.server_socket_io: self.http_server = SocketIOServer((self.server_hostname, self.server_port), app.wsgi_app, resource='socket.io', log=None) self.http_server._gl = gevent.spawn(self.http_server.serve_forever) log.info("UI Server: Providing web sockets (socket.io) server") else: self.http_server = WSGIServer((self.server_hostname, self.server_port), app, log=None) self.http_server.start() if self.service_gateway: self.service_gateway.start() log.info("UI Server: Service Gateway started on %s", self.gateway_base_url) for ext_obj in self.extension_objs: ext_obj.on_start() return True
def serve(self, port): """ Serve status over HTTP forever. """ flaskapp._status = self._status http_server = WSGIServer(('', port), flaskapp) http_server.serve_forever()
def run(): """Run gevent server""" http_server = WSGIServer((core_settings.SERVER_ADDRESS, core_settings.SERVER_PORT), app) try: http_server.serve_forever() except KeyboardInterrupt: http_server.stop()
def main(argv=None): args = parse_paasta_api_args() if args.debug: logging.basicConfig(level=logging.DEBUG) else: logging.basicConfig(level=logging.WARNING) if args.soa_dir: settings.soa_dir = args.soa_dir # Exit on exceptions while loading settings settings.cluster = load_system_paasta_config().get_cluster() marathon_config = marathon_tools.load_marathon_config() settings.marathon_client = marathon_tools.get_marathon_client( marathon_config.get_url(), marathon_config.get_username(), marathon_config.get_password() ) # Set up transparent cache for http API calls. With expire_after, responses # are removed only when the same request is made. Expired storage is not a # concern here. Thus remove_expired_responses is not needed. requests_cache.install_cache("paasta-api", backend="memory", expire_after=30) server = WSGIServer(('', int(args.port)), make_app()) log.info("paasta-api started on port %d with soa_dir %s" % (args.port, settings.soa_dir)) try: server.serve_forever() except KeyboardInterrupt: sys.exit(0)
def run(): skipped_components = [] LOGGER.info('environment: %s' % os.environ.items()) if not config.read().getboolean('fqrouter', 'BypassDirectlyEnabled'): LOGGER.info('scrambler component disabled by config') COMPONENTS.remove(comp_scrambler) for comp in COMPONENTS: try: shutdown_hook.add(comp.stop) handlers = comp.start() for method, url, handler in handlers or []: HANDLERS[(method, url)] = handler LOGGER.info('started component: %s' % comp.__name__) except: LOGGER.exception('failed to start component: %s' % comp.__name__) comp.stop() if getattr(comp, '__MANDATORY__', False): raise skipped_components.append(comp.__name__) LOGGER.info('all components started except: %s' % skipped_components) try: httpd = WSGIServer(('127.0.0.1', 8318), handle_request) LOGGER.info('serving HTTP on port 8318...') except: LOGGER.exception('failed to start HTTP server on port 8318') sys.exit(1) httpd.serve_forever()
def main(): if args.action == 'run': host = ''.join(args.bind.split(':')[:-1]) port = int(args.bind.split(':')[-1]) if args.name != PROC_TITLE_DEFAULT: try: import setproctitle proc_title = 'Spray Server: ' + args.name setproctitle.setproctitle(proc_title) logging.debug('Using custom process title ' + proc_title) except ImportError: logging.debug('Could not set process title as specified. Python module "setproctitle" required') if args.mode == 'development': app = create_app(args) logging.debug('Launching server in development mode') app.run(debug=args.debug, host=host, port=port) elif args.mode == 'production': args.cache = True cache_path = os.path.abspath(os.path.join(args.path, 'cache')) logging.debug('Clearing cache directory {path}'.format(path=cache_path)) if os.path.exists(cache_path): shutil.rmtree(cache_path) create_directory(cache_path) app = create_app(args) try: from gevent.wsgi import WSGIServer logging.debug('Launching server in production mode with gevent') server = WSGIServer((host, port), app, log=None) server.serve_forever() except ImportError: logging.debug('Launching server in production mode without gevent') app.run(host=host, port=port) elif args.action == 'create': create_project()
def run(self): #while True: self.logger = logging.getLogger("sms_khomp_api") self.logger.info("Creating sms_khomp_api") #Run WSGIServer http = WSGIServer(('', PORT), app.wsgi_app) http.serve_forever() self.logger.info("Done.")
def start_vaurien_httpserver(port): """Start a vaurien httpserver, controlling a fake proxy""" config = get_config() config.registry['proxy'] = FakeProxy() server = WSGIServer(('localhost', int(port)), config.make_wsgi_app(), log=None) server.serve_forever()
def serve_forever(): try: httpd = WSGIServer(('127.0.0.1', 8318), handle_request) LOGGER.info('serving HTTP on port 8318...') except: LOGGER.exception('failed to start HTTP server on port 8318') sys.exit(1) httpd.serve_forever()
def gevent_main(): """ Gevent coroutine WDGI standalone server """ from gevent.wsgi import WSGIServer http_server = WSGIServer(("", PORT), app) http_server.serve_forever()
def run_server(): options = get_options() configure_app(flatdb_app, options) from gevent.wsgi import WSGIServer server = WSGIServer((options.host, options.port), flatdb_app) server.serve_forever()
def serve_forever(): try: server = WSGIServer((LISTEN_IP, LISTEN_PORT), handle_request) LOGGER.info('serving HTTP on port %s:%s...' % (LISTEN_IP, LISTEN_PORT)) except: LOGGER.exception('failed to start HTTP server on port %s:%s' % (LISTEN_IP, LISTEN_PORT)) os._exit(1) server.serve_forever()
def main(args): from gevent.wsgi import WSGIServer if args.debug: app.run(debug=True, port=config.app.TESTING_FRONTEND_TCP_PORT) else: http_server = WSGIServer(("0.0.0.0", config.app.APP_TCP_PORT), app) http_server.serve_forever() return 0
def start(server_port, app): server = WSGIServer(("", server_port), app) try: server.serve_forever() except KeyboardInterrupt: pass finally: # Clean-up server (close socket, etc.) server.close()
padding: 0.5em; } </style> </head> <body> <div class="box"> <h1>Python(Anaconda) + Nginx</h1> <h2>Your application environment</h2> %s </div> </body> </html> """ def application(env, start_response): start_response('200 OK', [('Content-Type', 'text/html')]) lines = [] for k, v in os.environ.items(): if "PASSW" not in k: # don't show passwords lines.append("<div><b>{0}</b> = {1}</div>".format(k, v)) vals = ''.join(lines) return html % vals if __name__ == "__main__": from gevent.wsgi import WSGIServer http_server = WSGIServer((os.environ['OPENSHIFT_DIY_IP'], 15321), application) http_server.serve_forever()
#logger.info("status code:%s"%str(response.status_code)) if response.status_code == 200: logger.info("Got data ok") return response.json() logger.error("Failed to get data " + response.content) return None except Exception as e: logger.error("Post for data failed \n" + str(e)) return None if __name__ == '__main__': print "Service Started" # Enable logging logger = logging.getLogger("HX-Stats") logger.setLevel(logging.DEBUG) handler = logging.handlers.RotatingFileHandler(logFile, maxBytes=logBytes, backupCount=logCount) formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s') handler.setFormatter(formatter) logger.addHandler(handler) logger.info("-" * 25) logger.info("HX Stats script started") http_server = WSGIServer((server_IP, int(server_port)), app, log=logger) http_server.serve_forever()
def run_server(): log.info(' * Running on http://%s:%d/' % (options.hostname, options.port)) http_server = WSGIServer((options.hostname, options.port), get_app(), **ctx) http_server.serve_forever()
# Lancement du serveur if "tornado" in sys.argv : # Serveur Tornado # Installation préalable : "pip install tornado" from tornado.wsgi import WSGIContainer from tornado.httpserver import HTTPServer from tornado.ioloop import IOLoop http_server = HTTPServer(WSGIContainer(app)) http_server.listen(port) IOLoop.instance().start() elif "gevent" in sys.argv : # Serveur Gevent # Installation préalable : "pip install gevent" from gevent.wsgi import WSGIServer http_server = WSGIServer(('', port), app) http_server.serve_forever() else : # Serveur intégré à Flask app.run(host=host, port=port, debug=False)
from app import app from gevent.wsgi import WSGIServer http = WSGIServer(('0.0.0.0', 443), app , keyfile='cert/langchain_io.key' , certfile='cert/langchain_io.crt' ) http.serve_forever()
def main(): port = int(os.getenv('FLASK_PROXY_PORT', 8080)) server = WSGIServer(('', port), proxy, log=None) server.serve_forever()
class APIServer: """ Runs the API-server that routes the endpoint to the resources. The API is wrapped in multiple layers, and the Server should be invoked this way:: # instance of the raiden-api raiden_api = RaidenAPI(...) # wrap the raiden-api with rest-logic and encoding rest_api = RestAPI(raiden_api) # create the server and link the api-endpoints with flask / flask-restful middleware api_server = APIServer(rest_api) # run the server api_server.run('127.0.0.1', 5001, debug=True) """ _api_prefix = '/api/1' def __init__(self, rest_api, cors_domain_list=None, web_ui=False, eth_rpc_endpoint=None): if rest_api.version != 1: raise ValueError('Invalid api version: {}'.format( rest_api.version)) flask_app = Flask(__name__) if cors_domain_list: CORS(flask_app, origins=cors_domain_list) if eth_rpc_endpoint: if not eth_rpc_endpoint.startswith('http'): eth_rpc_endpoint = 'http://{}'.format(eth_rpc_endpoint) flask_app.config['WEB3_ENDPOINT'] = eth_rpc_endpoint blueprint = create_blueprint() flask_api_context = Api(blueprint, prefix=self._api_prefix) restapi_setup_type_converters( flask_app, {'hexaddress': HexAddressConverter}, ) restapi_setup_urls( flask_api_context, rest_api, URLS_V1, ) self.rest_api = rest_api self.flask_app = flask_app self.blueprint = blueprint self.flask_api_context = flask_api_context self.wsgiserver = None self.flask_app.register_blueprint(self.blueprint) self.flask_app.config['WEBUI_PATH'] = '../ui/web/dist/' if is_frozen(): # Inside frozen pyinstaller image self.flask_app.config[ 'WEBUI_PATH'] = '{}/raiden/ui/web/dist/'.format(sys.prefix) if web_ui: for route in ('/ui/<path:file_name>', '/ui', '/ui/', '/index.html', '/'): self.flask_app.add_url_rule( route, route, view_func=self._serve_webui, methods=('GET', ), ) def _serve_webui(self, file_name='index.html'): # pylint: disable=redefined-builtin try: assert file_name web3 = self.flask_app.config.get('WEB3_ENDPOINT') if web3 and 'config.' in file_name and file_name.endswith('.json'): host = request.headers.get('Host') if any(h in web3 for h in ('localhost', '127.0.0.1')) and host: _, _port = split_endpoint(web3) _host, _ = split_endpoint(host) web3 = 'http://{}:{}'.format(_host, _port) response = jsonify({'raiden': self._api_prefix, 'web3': web3}) else: response = send_from_directory( self.flask_app.config['WEBUI_PATH'], file_name) except (NotFound, AssertionError): response = send_from_directory(self.flask_app.config['WEBUI_PATH'], 'index.html') return response def run(self, host='127.0.0.1', port=5001, **kwargs): self.flask_app.run(host=host, port=port, **kwargs) def start(self, host='127.0.0.1', port=5001): self.wsgiserver = WSGIServer((host, port), self.flask_app, log=log, error_log=log) self.wsgiserver.start() def stop(self, timeout=5): if getattr(self, 'wsgiserver', None): self.wsgiserver.stop(timeout) self.wsgiserver = None
def run_production_webserver(app): http_webserver = WSGIServer(('', 5000), app, log=None) http_webserver.serve_forever()
def run(): print('Start server at: {0}:{1}'.format(host, port)) http_server = WSGIServer((host, port), wsgi, **self.server_options) http_server.serve_forever()
#!/usr/bin/env python """Web server start.""" from gevent.wsgi import WSGIServer from app import app http_server = WSGIServer(('', 80), app) http_server.serve_forever()
feedback_string+="above " if minimumprice/10000000 >= 1: feedback_string+=str(remove_exponent(Decimal(str(minimumprice/10000000))))+" Cr " else: feedback_string+=str(remove_exponent(Decimal(str(minimumprice/100000))))+" Lac " print feedback_string,string try: logString = logString + starttime + " ; " + str(todo_id) + " ; " + string + " ; " with open(fileName,"a") as myFile: myFile.write(logString) myFile.close() except: pass return string,feedback_string if __name__ == '__main__': #app.run(host='0.0.0.0',port=6020) http_server = WSGIServer(('0.0.0.0', 5000), app) http_server.serve_forever()
@app.route("/hintMeBabyOneMoreTime/<int:team_num>") def hintMeBabyOneMoreTime(team_num): print('adding hint to team {}'.format(team_num)) team_states[(team_num * 2) - 1] += 1 team_states[(team_num * 2)] += 1 return ','.join(map(str, team_states)) @app.route("/advance_state/<int:team_num>") def advance_state(team_num): print('advancing state for team {}'.format(team_num)) varx = team_states[(team_num * 2) - 1] if (varx % 3 == 0): team_states[(team_num * 2) - 1] += 1 elif (varx % 3 == 1): team_states[(team_num * 2) - 1] += 3 else: #(varx%3==2): team_states[(team_num * 2) - 1] += 2 return ','.join(map(str, team_states)) @app.route('/<path:path>') def static_file(path): return app.send_static_file(path) if __name__ == "__main__": app.debug = True server = WSGIServer(("0.0.0.0", 80), app) server.serve_forever()
def main(): route_list = [(Hello, '/hello')] init_route(route_list) http_server = WSGIServer(('0.0.0.0', int(5000)), app) http_server.serve_forever()
from gevent.wsgi import WSGIServer from geventwebsocket.handler import WebSocketHandler from twidder import app http_server = WSGIServer(("", 5000), app, handler_class=WebSocketHandler) app.debug = True http_server.serve_forever()
def start(self, host='127.0.0.1', port=5001): self.wsgiserver = WSGIServer((host, port), self.flask_app, log=log, error_log=log) self.wsgiserver.start()
yield c else: break except Exception, e: print e yield 'Error' finally: if f: f.close() if __name__ == '__main__': urls = ( '/command/not_realtime/(.*)/(.*)', 'Command_not_realtime', '/command/realtime/vmi/(.*)/(.*)', 'Command_realtime_vmi', '/command/realtime/image/(.*)/(.*)', 'Command_realtime_image', '/filedownload/(.*)', 'FileDownload', '/registrydownload/(.*)/(.*)', 'RegistryDownload', ) try: application = web.application(urls, globals()).wsgifunc() WSGIServer(('', api_server_port), application).serve_forever() except KeyboardInterrupt: pass
def runwsgi(): sys.path.append('/var/app/weibonews/enabled/wechat/') sys.path.append('/var/app/weibonews/enabled/wechat/wechat') os.environ['DJANGO_SETTINGS_MODULE'] = 'wechat.settings' got_request_exception.connect(exception_printer) WSGIServer(('', 8088), WSGIHandler()).serve_forever()
def notify(): msg = str(time.time()) for sub in subscriptions[:]: sub.put(payload) gevent.spawn(notify) return "OK" @app.route("/subscribe/epoch/end/") def subscribe(): def gen(): q = Queue() subscriptions.append(q) try: while True: result = q.get() event = ServerSentEvent(str(result)) yield event.encode() except GeneratorExit: subscriptions.remove(q) return Response(gen(), mimetype="text/event-stream") if __name__ == "__main__": app.debug = True server = WSGIServer(("", 9000), app) server.serve_forever()
msg = traceback.format_exception(e[0], e[1], e[2]) logging.warn(''.join(msg)) return Response('400 ERROR', status=400) @app.route('/place_order', methods = ['POST']) def api_place_order(): try: if request.headers['Content-Type'] == 'application/json': logging.debug(request.json) if check_appkey(request.json['appkey']): order = request.json['order'] data = json.dumps({ 'appkey': get_appkey(), 'order': order, 'result': place_order(order), }) return Response(data, status=200, mimetype='application/json') else: return Response('500 Permission denied', status=500) else: return Response("415 Unsupported Media Type!", status=415) except: e = sys.exc_info() msg = traceback.format_exception(e[0], e[1], e[2]) logging.warn(''.join(msg)) return Response('400 ERROR', status=400) http_server = WSGIServer((HOST, PORT), app) http_server.serve_forever()
def run(self): self.logger.info('Rss transmission is running.') server = WSGIServer(('0.0.0.0', 9092), app) t = Thread(target=self.work) t.start() server.serve_forever()
user_agent = request.headers.get('User-Agent', '').lower() html_needed = is_html_needed(user_agent) options = parse_args(request.args) hostname = request.headers['Host'] if request.headers.getlist("X-Forwarded-For"): ip = request.headers.getlist("X-Forwarded-For")[0] if ip.startswith('::ffff:'): ip = ip[7:] else: ip = request.remote_addr if request.headers.getlist("X-Forwarded-For"): ip = request.headers.getlist("X-Forwarded-For")[0] if ip.startswith('::ffff:'): ip = ip[7:] else: ip = request.remote_addr if topic is None: topic = ":firstpage" answer = cmd_wrapper(topic, hostname=hostname, request_options=options, html=is_html_needed(user_agent)) log_query(ip, hostname, topic, user_agent) return answer server = WSGIServer(("", 8004), app) # log=None) server.serve_forever()
def startserver(adduser, api, auth, dburl, hydradoc, port, serverurl, serve): """Python Hydrus CLI""" # The database connection URL # See http://docs.sqlalchemy.org/en/rel_1_0/core/engines.html#sqlalchemy.create_engine for more info # DB_URL = 'sqlite:///database.db' DB_URL = dburl # Define the server URL, this is what will be displayed on the Doc HYDRUS_SERVER_URL = serverurl + ":" + str(port) + "/" # The name of the API or the EntryPoint, the api will be at http://localhost/<API_NAME> API_NAME = api click.echo("Setting up the database") # Create a connection to the database you want to use engine = create_engine(DB_URL) click.echo("Creating models") # Add the required Models to the database Base.metadata.create_all(engine) # Define the Hydra API Documentation # NOTE: You can use your own API Documentation and create a HydraDoc object using doc_maker # Or you may create your own HydraDoc Documentation using doc_writer [see hydrus/hydraspec/doc_writer_sample] click.echo("Creating the API Documentation") apidoc = doc_maker.create_doc(json.loads(hydradoc.read()), HYDRUS_SERVER_URL, API_NAME) # Start a session with the DB and create all classes needed by the APIDoc session = scoped_session(sessionmaker(bind=engine)) click.echo("Adding Classes and Properties") # Get all the classes from the doc classes = doc_parse.get_classes( apidoc.generate() ) # You can also pass dictionary defined in hydrus/hydraspec/doc_writer_sample_output.py # Get all the properties from the classes properties = doc_parse.get_all_properties(classes) # Insert them into the database doc_parse.insert_classes(classes, session) doc_parse.insert_properties(properties, session) click.echo("Adding authorized users") add_user(id_=adduser[0], paraphrase=adduser[1], session=session) # Insert them into the database doc_parse.insert_classes(classes, session) doc_parse.insert_properties(properties, session) click.echo("Creating the application") # Create a Hydrus app with the API name you want, default will be "api" app = app_factory(API_NAME) # Set the name of the API click.echo("Starting the application") with set_authentication(app, auth): # Use authentication for all requests with set_api_name(app, api): # Set the API Documentation with set_doc(app, apidoc): # Set HYDRUS_SERVER_URL with set_hydrus_server_url(app, HYDRUS_SERVER_URL): # Set the Database session with set_session(app, session): # Start the Hydrus app http_server = WSGIServer(('', port), app) click.echo("Server running at:") click.echo(HYDRUS_SERVER_URL + API_NAME) try: http_server.serve_forever() except KeyboardInterrupt: pass
<body> <div id="test"> <h1>EventSource testing</h1> <p>Go to the URL below to update this, as well as all other working screens.</p> </div> <a href="/update" target="_blank">Update</a> <script> window.onload=function() { var source = new EventSource("/subscribe"); source.onmessage = function(e) { document.getElementById("test").innerHTML = e.data; }; }; </script> </body> </html>""" @app.route("/subscribe") def subscribe(): return sse.eventsource() @app.route("/update") def update(): sse.publish("<h1>EventSource testing!</h1><p>The time is: {!s}</p>".format(time.time())) return "Updated" if __name__=="__main__": app.debug=True server = WSGIServer(("0.0.0.0",1045),app) server.serve_forever()
import sys, os import getopt try: from gevent.wsgi import WSGIServer except: from gevent.pywsgi import WSGIServer from gevent import monkey monkey.patch_all() hostname = '127.0.0.1' port = 80 opts, args = getopt.getopt(sys.argv[1:], "h:p:", []) for o, a in opts: if o == '-h': hostname = a elif o == '-p': port = int(a) path = os.path.dirname(os.path.abspath(__file__)) if path not in sys.path: sys.path.insert(0, path) from uliweb.manage import make_simple_application application = make_simple_application(project_dir=path) http_server = WSGIServer((hostname, port), application) http_server.serve_forever()
#!/usr/bin/env python import sys from gevent.wsgi import WSGIServer from app import app if __name__ == '__main__': server = WSGIServer( (app.config['LISTEN_ADDRESS'], app.config['LISTEN_PORT']), app) server.serve_forever()
def file_list(path=None): if not path: path = "" full_path = os.path.join(BASE_DIR, path) g.path = os.path.join(g.path, path) if not os.path.isdir(full_path): download_path = os.path.split(full_path) return send_from_directory(download_path[0], download_path[1], as_attachment=True) dir_info = get_directory(full_path) return render_template("file.html", file_names=dir_info[0], error=dir_info[1]) def get_directory(full_path): try: _file_list = os.listdir(full_path) except os.error: return (None, "Permission 123") if not _file_list: return (("", ""), "No file here") _file_list.sort(key=lambda file: file.lower()) file_list = [] for name in _file_list: display = name + '/' if os.path.isdir(os.path.join(g.path, name)) else name file_list.append((urllib.parse.quote(name), cgi.escape(display))) return (file_list, None) if __name__ == '__main__': server = WSGIServer(('', 9999), app) server.serve_forever()
from gevent import monkey; monkey.patch_all() import env; env.setup() import logger; logger.setup() import logging log = logging.getLogger() # An example gevent/flask app import flask app = flask.Flask(__name__) @app.route('/get', methods=['GET']) def get(): # flask.request.args for GET # flask.request.form for POST return "Hello World %s" % flask.request.args if __name__ == '__main__': from gevent.wsgi import WSGIServer http_server = WSGIServer(('127.0.0.1', 5000), app) http_server.serve_forever()
return jsonify(status) @app.route( '/dns/update/record/<name>/<id>/<master>/<last_check>/<type>/<notified_serial>/<account>' ) def dnsupdaterecord(name, id, master, last_check, type, notified_serial, account): kwargs = { 'name': name, 'id': id, 'master': master, 'last_check': last_check, 'type': type, 'notified_serial': notified_serial, 'account': account } status = c.cmd(user, 'soy_pdns.updateRecord', **kwargs) return jsonify(status) @app.route('/dns/delete/record/<id>') def dnsdeleterecord(id): status = c.cmd(user, 'soy_pdns.deleteRecord', [id]) return jsonify(status) if __name__ == '__main__': server = WSGIServer(('', 80), app) server.serve_forever()
def run_app(app, port=5000): http_server = WSGIServer(('', port), app) webbrowser.open_new('http://localhost:' + str(port)) http_server.serve_forever()
class APIServer(object): """ Runs the API-server that routes the endpoint to the resources. The API is wrapped in multiple layers, and the Server should be invoked this way:: # instance of the raiden-api raiden_api = RaidenAPI(...) # wrap the raiden-api with rest-logic and encoding rest_api = RestAPI(raiden_api) # create the server and link the api-endpoints with flask / flask-restful middleware api_server = APIServer(rest_api) # run the server api_server.run('127.0.0.1', 5001, debug=True) """ # flask TypeConverter # links argument-placeholder in route (e.g. '/<hexaddress: channel_address>') to the Converter _type_converter_mapping = {'hexaddress': HexAddressConverter} _api_prefix = '/api/1' def __init__(self, rest_api, cors_domain_list=None, web_ui=False, eth_rpc_endpoint=None): self.rest_api = rest_api self.blueprint = create_blueprint() if self.rest_api.version == 1: self.flask_api_context = Api( self.blueprint, prefix=self._api_prefix, ) else: raise ValueError('Invalid api version: {}'.format( self.rest_api.version)) self.flask_app = Flask(__name__) if cors_domain_list: CORS(self.flask_app, origins=cors_domain_list) self._add_default_resources() self._register_type_converters() self.flask_app.register_blueprint(self.blueprint) self.flask_app.config['WEBUI_PATH'] = '../ui/web/dist/' if eth_rpc_endpoint: if not eth_rpc_endpoint.startswith('http'): eth_rpc_endpoint = 'http://' + eth_rpc_endpoint self.flask_app.config['WEB3_ENDPOINT'] = eth_rpc_endpoint if web_ui: for route in [ '/ui/<path:file>', '/ui', '/ui/', '/index.html', '/' ]: self.flask_app.add_url_rule( route, route, view_func=self._serve_webui, methods=['GET'], ) def _add_default_resources(self): self.add_resource(AddressResource, '/address') self.add_resource(ChannelsResource, '/channels') self.add_resource(ChannelsResourceByChannelAddress, '/channels/<hexaddress:channel_address>') self.add_resource(TokensResource, '/tokens') self.add_resource(PartnersResourceByTokenAddress, '/tokens/<hexaddress:token_address>/partners') self.add_resource(RegisterTokenResource, '/tokens/<hexaddress:token_address>') self.add_resource(NetworkEventsResource, '/events/network') self.add_resource(TokenEventsResource, '/events/tokens/<hexaddress:token_address>') self.add_resource(ChannelEventsResource, '/events/channels/<hexaddress:channel_address>') self.add_resource( TokenSwapsResource, '/token_swaps/<hexaddress:target_address>/<int:identifier>') self.add_resource( TransferToTargetResource, '/transfers/<hexaddress:token_address>/<hexaddress:target_address>' ) self.add_resource(ConnectionsResource, '/connection/<hexaddress:token_address>') def _serve_webui(self, file='index.html'): try: assert file web3 = self.flask_app.config.get('WEB3_ENDPOINT') if web3 and 'config.' in file and file.endswith('.json'): response = jsonify({'raiden': self._api_prefix, 'web3': web3}) else: response = send_from_directory( self.flask_app.config['WEBUI_PATH'], file) except (NotFound, AssertionError): response = send_from_directory(self.flask_app.config['WEBUI_PATH'], 'index.html') return response def _register_type_converters(self, additional_mapping=None): # an additional mapping concats to class-mapping and will overwrite existing keys if additional_mapping: mapping = dict(self._type_converter_mapping, **additional_mapping) else: mapping = self._type_converter_mapping for key, value in mapping.items(): self.flask_app.url_map.converters[key] = value def add_resource(self, resource_cls, route): self.flask_api_context.add_resource( resource_cls, route, resource_class_kwargs={'rest_api_object': self.rest_api}) def run(self, host='127.0.0.1', port=5001, **kwargs): self.flask_app.run(host=host, port=port, **kwargs) def start(self, host='127.0.0.1', port=5001): self.wsgiserver = WSGIServer((host, port), self.flask_app) self.wsgiserver.start() def stop(self, timeout=5): if getattr(self, 'wsgiserver', None): self.wsgiserver.stop(timeout) self.wsgiserver = None