def command(): parser = OptionParser(usage="%prog DIR [HOST][:][PORT]", version="static 0.3.6") options, args = parser.parse_args() if len(args) in (1, 2): if len(args) == 2: parts = args[1].split(":") if len(parts) == 1: host = parts[0] port = None elif len(parts) == 2: host, port = parts else: sys.exit("Invalid host:port specification.") elif len(args) == 1: host, port = None, None if not host: host = '0.0.0.0' if not port: port = 9999 try: port = int(port) except: sys.exit("Invalid host:port specification.") app = Cling(args[0]) try: make_server(host, port, app).serve_forever() except KeyboardInterrupt: print("Cio, baby!") except: sys.exit("Problem initializing server.") else: parser.print_help(sys.stderr) sys.exit(1)
def main(): import wsgiref from wsgiref.simple_server import make_server from StringIO import StringIO if len(sys.argv)<2: print 'usage: frameless.py module_name [ip port]' return module_name = sys.argv[1] if len(sys.argv)>=4: ip = sys.argv[2] port = int(sys.argv[3]) else: ip = 'localhost' port = 8000 wsgi_app = functools.partial(app, module_name) ''' test_env = {} wsgiref.util.setup_testing_defaults(test_env) test_env['QUERY_STRING'] = 'helloworld' test_env['wsgi.input'] = StringIO('xxx\nddd\nyyy\n') print wsgi_app(test_env, lambda a,b:None) ''' print 'listening on %s:%d'%(ip, port) make_server(ip, port, wsgi_app).serve_forever()
def run(): here = os.path.abspath(os.path.join(os.path.dirname(__file__), "..")) sys.path.insert(0, here) from fluxbin import app import controller simple_server.make_server("", 8080, app).serve_forever()
def main(argv): datafiles = '' datanames = '' port = 8071 try: opts, args = getopt.getopt(argv, "hp:f:d:", ["port=", "datafiles=", "datanames="]) except getopt.GetoptError: print 'search.py -p <port> -d <datanames> -f <datafiles>' sys.exit(2) for opt, arg in opts: if opt == '-h': print 'search.py -p <port> -d <datanames> -f <datafiles>' sys.exit() elif opt in ("-d", "--datanames"): datanames = arg elif opt in ("-f", "--datafiles"): datafiles = arg elif opt in ("-p", "--port"): port = arg init(datanames, datafiles) from wsgiref.simple_server import make_server try: print('Server started on port ' + str(port)) make_server('', port, web).serve_forever() except KeyboardInterrupt: pass print('\nThanks!')
def debugserver(host, port): """ Run the webservice with the Python built-in HTTP server. """ sys.stderr.write('Listening on http://%s:%d/\n' % (host, port)) sys.stderr.write('WDSL file is at http://%s:%d/?wsdl\n' % (host, port)) make_server(host, port, application).serve_forever()
def main(): cwd = os.getcwd() cfg = load_settings(cwd) handlers = [] handlers.append(ConnectHandler(cfg)) handlers.append(PermissionHandler(cfg)) handlers.append(GrepHandler(cwd)) handlers.append(FileListing(cwd, cfg)) handlers.append(SaveHandler(cwd)) handlers.append(ProjectFilesServer(cwd)) handlers.append(NotFoundHandler()) i = 0 for handler in handlers: i += 1 if i < len(handlers): handler.next_handler = handlers[i] try: print "Serving " + cwd + " to http://localhost:8888" make_server('localhost', 8888, handlers[0]).serve_forever() except KeyboardInterrupt, ki: print "\nBye bye"
def command(): parser = OptionParser(usage='%prog DIR [HOST][:][PORT]', version='static 0.3.6') options, args = parser.parse_args() if len(args) in (1, 2): if len(args) == 2: parts = args[1].split(':') if len(parts) == 1: host = parts[0] port = None elif len(parts) == 2: host, port = parts else: sys.exit('Invalid host:port specification.') elif len(args) == 1: host, port = None, None if not host: host = '0.0.0.0' if not port: port = 9999 try: port = int(port) except: sys.exit('Invalid host:port specification.') app = Cling(args[0]) try: make_server(host, port, app).serve_forever() except KeyboardInterrupt, ki: print 'Cio, baby!' except:
def StartWebServer(self, port, application=None): """Start web server. Args: port: Port to start application on. application: Optional WSGI function. If none provided will use tests CreateWsgiApplication method. Returns: A tuple (server, application): server: An instance of ServerThread. application: Application that web server responds with. """ if not application: application = self.CreateWsgiApplication() validated_application = validate.validator(application) try: server = simple_server.make_server( 'localhost', port, validated_application) except socket.error: # Try IPv6 server = simple_server.make_server( 'localhost', port, validated_application, server_class=WSGIServerIPv6) server = ServerThread(server) server.start() return server, application
def start_server(debug=False): message = 'Starting server at http://%s:%s' % (HOST, PORT) if debug: variables = settings.theme.get('vars', {}) variables.update({'debug': True}) settings.theme['vars'] = variables if RequestHandler is object: logging.info(message) make_server(HOST, int(PORT), wsgi_app).serve_forever() else: import tornado.web if g.output_directory == ROOT: #: if this is a liquidluck project, build the site load_posts(settings.config['source']) write_posts() logging.info('Theme directory: %s' % g.theme_directory) handlers = [ (r'/livereload', LiveReloadHandler), (r'/livereload.js', LiveReloadJSHandler), (r'/theme/(.*)', ThemeStaticHandler), (r'(.*)', IndexHandler), ] app = tornado.web.Application(handlers=handlers, default_host=HOST) app.listen(int(PORT)) logging.info(message) tornado.ioloop.IOLoop.instance().start()
def main(): # Command line options parser = ArgumentParser(prog='mrpypi') parser.add_argument('-p', dest='port', type=int, default=8080, help='server port number (default is 8080)') parser.add_argument('--index', dest='index_url', default=DEFAULT_PIP_INDEX, metavar='URL', help='upstream pypi index URL (default is "{0}")'.format(DEFAULT_PIP_INDEX)) parser.add_argument('--no-index', dest='index_url', action='store_const', const=None, help='disable upstream pypi index') parser.add_argument('--mongo', dest='mongo', action='store_true', help='use MongoDB index') parser.add_argument('--mongo-uri', dest='mongo_uri', type=str, default=DEFAULT_MONGO_URI, metavar='URI', help='MongoDB URI (default is "{0}")'.format(DEFAULT_MONGO_URI)) args = parser.parse_args() # Create the index print('Upstream pypi index URL: {0}'.format(args.index_url)) if args.mongo: print('Mongo index with URI: {0}'.format(args.mongo_uri)) index = MongoIndex(index_url=args.index_url, mongo_uri=args.mongo_uri) else: print('Using memory index') index = MemoryIndex(index_url=args.index_url) # Start the application application = MrPyPi(index) print('Serving on port {0}...'.format(args.port)) make_server('', args.port, application).serve_forever()
def run(self, runtime): from wsgiref.simple_server import make_server from mesh.transport.http import WsgiServer application = WsgiServer([self["bundle"]]) hostname, port = self["hostname"].split(":") make_server(hostname, int(port), application).server_forever()
def _start_server(app, host, port): if pywsgi: logger.info("Server is running; using gevent server") pywsgi.WSGIServer((host, port), app).serve_forever() else: logger.info("Server is running; using wsgiref server") make_server(host, port, app).serve_forever()
def main(argv=sys.argv): """ Run the WSGI application using :mod:`wsgiref`. """ args = docopt.docopt(__doc__, argv[1:], version=__version__) if args['--print-template']: six.print_(DEFAULT_FRONTPAGE) return 0 host = args['--host'] port = int(args['--port']) store = os.path.realpath(os.path.expanduser(args['--store'])) template = args['--template'] if 0 > port > 65535: six.print_('Bad port: {0}'.format(port), file=sys.stderr) return 1 try: app = create_application(None, store=store, template=template) except BadPath as exc: six.print_(exc.message, file=sys.stderr) return 1 logging.basicConfig(level=logging.INFO, stream=sys.stderr) from wsgiref.util import guess_scheme scheme = guess_scheme(os.environ) six.print_("Serving on {0}://{1}:{2}/".format(scheme, host, port), file=sys.stderr) from wsgiref.simple_server import make_server make_server(host, port, app).serve_forever() return 0
def main(): logging.basicConfig(stream=sys.stdout, level=logging.DEBUG) url_map = SessionMiddleware(urlmap, session_class=InMemorySession) print 'Serving on port: 8080' make_server('localhost', 8080, url_map).serve_forever()
def test(): from wsgiref.validate import validator magics = StringMagic(title="String Test"), KidMagic(title="Kid Test") app = Shock('testdata/pub', magics=magics) try: make_server('localhost', 9999, validator(app)).serve_forever() except KeyboardInterrupt, ki: print "Ciao, baby!"
def run(): host, port, directory = sys.argv[1:4] app = Cling(directory) try: from wsgiref.simple_server import make_server make_server(host, int(port), app).serve_forever() except KeyboardInterrupt: print("Cio, baby!")
def serve(self, app=None): """Creates a http server""" if app is None: httpd = make_server('', 8000, self) else: httpd = make_server('', 8000, app) print "Webby: port 8000..." httpd.serve_forever()
def run(self): while(1): #NOTE: we take no action if the local port is changed dynamically local_port = settings.get('local_port') if not local_port: time.sleep(1) continue logger.info("Starting web server at http://localhost:%d" % local_port) make_server('', local_port, self, handler_class=RCIWSGIRequestHandler).serve_forever()
def get_new_token(): authorize_url = client.authorization_url( client_id=CLIENT_ID, redirect_uri=('%s:%s' % (config.SERVER_HOST, CALLBACK_PORT)) ) webbrowser.open(authorize_url) print('Click here to authorize me to access your Strava activities: %s' % authorize_url) make_server('localhost', CALLBACK_PORT, auth_listener).handle_request()
def test(): from wsgiref.validate import validator app = Cling(getcwd()) try: print "Serving " + getcwd() + " to http://localhost:9999" make_server('localhost', 9999, validator(app)).serve_forever() except KeyboardInterrupt, ki: print "" print "Ciao, baby!"
def make_server(self,serverIp='',port=8000,test=False): from wsgiref.simple_server import make_server from wsgiref.simple_server import httpd = make_server(serverIp, port, self.make_app(), server_class=WSGIServer) if test: httpd.handle_request() else: httpd.serve_forever() return True
def main(socketmodule=None): if socketmodule is None: socketmodule = socket app, port = get_args() if app == 'myapp': s = socketmodule.socket() host = socketmodule.getfqdn() if port == 0: port = random.randint(8000, 9999) s.bind((host, port)) print 'Starting server on', host, port print 'The Web server URL for this would be http://%s:%d/' % (host, port) s.listen(5) print 'Entering infinite loop; hit CTRL-C to exit' while True: c, (client_host, client_port) = s.accept() print 'Got connection from', client_host, client_port handle_connection(c, client_port) elif app == 'image': imageapp.setup() p = imageapp.create_publisher() wsgi_app = quixote.get_wsgi_app() from wsgiref.simple_server import make_server host = socketmodule.getfqdn() if port == 0: port = random.randint(8000, 9999) httpd = make_server('', port, wsgi_app) print 'Starting server on', host, port print 'The Web server URL for this would be http://%s:%d/' % (host, port) try: httpd.serve_forever() finally: imageapp.teardown() elif app == 'altdemo': p = create_publisher() wsgi_app = quixote.get_wsgi_app() from wsgiref.simple_server import make_server host = socketmodule.getfqdn() if port == 0: port = random.randint(8000, 9999) p.is_thread_safe = True httpd = make_server('', port, wsgi_app) print 'Starting server on', host, port print 'The Web server URL for this would be http://%s:%d/' % (host, port) httpd.serve_forever() elif app in ('quotes', 'chat'): if port == 0: port = random.randint(8000, 9999) os.chdir(app) os.system("python2.7 %s-server %d" % (app, port))
def run(self, host=None, port=None, debug=False): if host is None: host = '127.0.0.1' if port is None: port = 8000 if debug: from exts.serving import run_server run_server(host, port, self) else: from wsgiref.simple_server import make_server make_server(host, port, self).serve_forever()
def runserver(app, port): """Runs a WSGI server that serves a given app on the specified port :param app: an app to be served :param port: a port that will be used to serve the app """ from wsgiref.simple_server import make_server print "Running on port {0}".format(port) make_server('', port, app).serve_forever()
def _test(): import sys logging.basicConfig(level=logging.DEBUG) args = sys.argv[1:] if args: Configuration.load_kw(componentRoot=args[0]) from wsgiref.simple_server import make_server from skunk.web.context import ContextMiddleware make_server("localhost", 7777, ContextMiddleware(DispatchingFileServer())).serve_forever()
def main(): from wsgiref import simple_server from sakuya.model import session session.initialize('sqlite:///data.db') app = app_factory() simple_server.make_server('', 8888, app).serve_forever()
def run_server(): """ Running wsgi server """ config = configparser.ConfigParser() config_path = os.path.abspath(os.path.join( os.path.dirname(__file__), '..', 'config.ini') ) config.read(config_path) host = config['server:main']['host'] port = int(config['server:main']['port']) print("Serving on http://%s:%s..." % (host, port)) make_server(host, port, application).serve_forever()
def main(): from wsgiref.simple_server import make_server from bricks import Settings settings = Settings() app = application debug = settings['debug'] if debug: from werkzeug.debug import DebuggedApplication app = DebuggedApplication(application, evalex=True) port = settings['port'] logging.info("Serving on port %s" % port) make_server('', port, app).serve_forever()
def run_server(args): """ Launch the development server. """ content_types = { '.js': ('Content-Type', 'application/javascript'), '.html': ('Content-Type', 'text/html') } if args.path_to_conf is not None: os.environ[config.ENVIRON_VAR_NAME] = args.path_to_conf else: os.environ.setdefault(config.ENVIRON_VAR_NAME, os.path.join(args.project_dir, config.DEFAULT_FILE_NAME)) sys.path.insert(0, args.project_dir) wsgi = importlib.import_module('wsgi') def static_server_wrapper(environ, start_response): if environ['PATH_INFO'].startswith(args.static_url): path = environ['PATH_INFO'][len(args.static_url):].lstrip('/') if not path: path = 'index.html' path_to_page = args.static_dir / Path(path) try: with Path(path_to_page).open('rb') as page_file: page = page_file.read() except FileNotFoundError: yield from wsgi.application(environ, start_response) else: start_response('200 OK', [ ('Content-Length', str(len(page))), content_types.get(path_to_page.suffix, ('Content-Type', 'text/plain')) ]) yield page else: yield from wsgi.application(environ, start_response) if args.static_dir is None: server = make_server('', args.port, wsgi.application) else: server = make_server('', args.port, static_server_wrapper) server.serve_forever()
def cmd_server(omni_config, http_port=None, http_host=None, debugger=False): """ Usage: omni server [--http-port=PORT] [--http-host=HOST] [--debugger] Options: -p, --http-port=PORT Port in which to serve HTTP requests. --http-host=HOST Host name of IP address to bind to. --debugger Enable the debugger [default: False]. -h, --help Show this help message. """ from aiowsgi.compat import asyncio import aiowsgi import logging logging.basicConfig() # Apply command line overrides. if http_host is None or http_port is None: http_config = { "port": 8080, "host": "localhost" } if "http" in omni_config: conf = config_http_schema.validate(omni_config["http"]) http_config.update(conf) if http_host is None: http_host = http_config["host"] if http_port is None: http_port = http_config["port"] omni = app.make_application(omni_config) wsgi_app = app.make_wsgi_application(omni) if debugger: from backlash import DebuggedApplication from webob import Request from wsgiref.simple_server import make_server def getctx(e=None): req = None if e is None else Request(e) return { "env": e, "omni": omni, "req": req, "app": wsgi_app } wsgi_app = DebuggedApplication(wsgi_app, context_injectors=[getctx], console_init_func=getctx) make_server(http_host, http_port, wsgi_app).serve_forever() else: loop = asyncio.get_event_loop() aiowsgi.create_server(wsgi_app, loop=loop, host=http_host, port=http_port) try: loop.run_forever() except KeyboardInterrupt: pass
# 定义文件请求的类型和当前请求成功的code start_response('200 OK', [('Content-Type', 'text/html')]) # environ是当前请求的所有数据,包括Header和URL,body,这里只涉及到get # 获取当前get请求的所有数据,返回是string类型 params = parse_qs(environ['QUERY_STRING']) # 获取get中key为name的值 name = params.get('name', [''])[0] no = params.get('no', [''])[0] # 组成一个数组,数组中只有一个字典 dic = {'name': name, 'no': no} return [json.dumps(dic)] if __name__ == "__main__": port = 5088 httpd = make_server("0.0.0.0", port, application) print "serving http on port {0}...".format(str(port)) httpd.serve_forever()
# 値を変更するための画面を生成 elif (filepath == "./change"): html = change(form) # localhostに直接アクセスした場合の処理 else: html = default() html = html.encode('utf-8') # レスポンス start_response('200 OK', [('Content-Type', 'text/html; charset=utf-8'), ('Content-Length', str(len(html)))]) return [html] # リファレンスWEBサーバを起動 # ファイルを直接実行する(python3 test_wsgi.py)と, # リファレンスWEBサーバが起動し,http://localhost:8080 にアクセスすると # このサンプルの動作が確認できる. # コマンドライン引数にポート番号を指定(python3 test_wsgi.py ポート番号)した場合は, # http://localhost:ポート番号 にアクセスする. from wsgiref import simple_server if __name__ == '__main__': port = 8080 if len(sys.argv) == 2: port = int(sys.argv[1]) server = simple_server.make_server('', port, application) server.serve_forever()
#!/usr/bin/env python from wsgiref.simple_server import make_server from saiyans import saiyans # Every WSGI application must have an application object - a callable # object that accepts two arguments. For that purpose, we're going to # use a function (note that you're not limited to a function, you can # use a class for example). The first argument passed to the function # is a dictionary containing CGI-style environment variables and the # second variable is the callable object (see PEP 333). def hello_world_app(environ, start_response): status = '200 OK' # HTTP Status headers = [('Content-type', 'text/plain; charset=utf-8')] # HTTP Headers start_response(status, headers) goku = saiyans() b = bytes(goku.kamehameha_method(environ["PATH_INFO"])) # The returned object is going to be printed return [b] httpd = make_server('', 8000, hello_world_app) print("Serving on port 8000...") # Serve until process is killed httpd.serve_forever()
image_type = imghdr.what(None, data['image']) return '<img src="data:image/' + image_type + ';base64,' + base64_image_data + '" alt="テストデータ">' def response(start_response, body): status = '200 OK' headers = [('Content-Type', 'text/html; charset=utf-8'), ('Content-Length', str(len(body)))] start_response(status, headers) return [body] def simple_app(environ, start_response): request_method = environ.get('REQUEST_METHOD') if 'POST' == request_method: # postの処理 body = post_image(environ=environ).encode('utf-8') return response(start_response=start_response, body=body) elif 'GET' == request_method: # getの処理 body = html return response(start_response=start_response, body=body) else: pass httpd = make_server('', 8000, simple_app) print('Serving on port 8000...') httpd.serve_forever()
def start(self): class MqttWebSocket(WebSocket): topic_prefix = self.topic_prefix mqtt_client = self.mqtt_client def received_message(self, message): try: json_message = json.loads(message.data.decode("utf-8")) json_message = { "topic": f"{self.topic_prefix}/{json_message['topic']}", "payload": json_message.get("payload"), "retain": json_message.get("retain", False), } except Exception as e: logger.warning( "Unable to parse websocket message as valid json.") return logger.debug( f"Publishing mqtt message from websockets at {json_message['topic']}." ) self.mqtt_client.publish( json_message["topic"], json_message["payload"], retain=json_message["retain"], ) # start a websocket server on 5002 WebSocketWSGIHandler.http_version = "1.1" self.websocket_server = make_server( "127.0.0.1", 5002, server_class=WSGIServer, handler_class=WebSocketWSGIRequestHandler, app=WebSocketWSGIApplication(handler_cls=MqttWebSocket), ) self.websocket_server.initialize_websockets_manager() self.websocket_thread = threading.Thread( target=self.websocket_server.serve_forever) def send(client, userdata, message): """Sends mqtt messages to clients.""" try: logger.debug(f"Received mqtt message on {message.topic}.") ws_message = json.dumps({ "topic": message.topic.replace(f"{self.topic_prefix}/", ""), "payload": message.payload.decode(), }) except Exception as e: # if the payload can't be decoded don't relay to clients logger.debug( f"MQTT payload for {message.topic} wasn't text. Skipping..." ) return self.websocket_server.manager.broadcast(ws_message) self.mqtt_client.message_callback_add(f"{self.topic_prefix}/#", send) self.websocket_thread.start()
def hello(request, name): return Response("<h1>Hello, {name}</h1>".format(name=name)) @routers(r'/goodbye/(.*)/$') def goodbye(request, name): return Response("<h1>Goodbye, {name}</h1>".format(name=name)) class Application(object): def __init__(self, routers, **kwargs): self.routers = routers def __call__(self, environ, start_response): try: request = Request(environ) callback, args = routers.match(request.path) response = callback(request, *args) except NotFoundError: response = Response("<h1>Not found</h1>", status=404) start_response(response.status, response.headers.items()) return iter(response) application = Application(routers) if __name__ == '__main__': from wsgiref.simple_server import make_server httpd = make_server('127.0.0.1', 8000, application) httpd.serve_forever()
def run(self): self.http_server = make_server('', self.port, self.app) self.http_server.serve_forever()
resp.location = '/%s/things/%s' % (user_id, proper_thing['id']) # Configure your WSGI server to load "things.app" (app is a WSGI callable) app = falcon.API(middleware=[ AuthMiddleware(), RequireJSON(), JSONTranslator(), ]) db = StorageEngine() things = ThingsResource(db) app.add_route('/{user_id}/things', things) # If a responder ever raised an instance of StorageError, pass control to # the given handler. app.add_error_handler(StorageError, StorageError.handle) # Proxy some things to another service; this example shows how you might # send parts of an API off to a legacy system that hasn't been upgraded # yet, or perhaps is a single cluster that all data centers have to share. sink = SinkAdapter() app.add_sink(sink, r'/search/(?P<engine>ddg|y)\Z') # Useful for debugging problems in your API; works with pdb.set_trace(). You # can also use Gunicorn to host your app. Gunicorn can be configured to # auto-restart workers when it detects a code change, and it also works # with pdb. if __name__ == '__main__': httpd = simple_server.make_server('127.0.0.1', 8000, app) httpd.serve_forever()
rows = "" counter = 0 for team in self.get_data(): counter += 1 rows += Template(RESULT_ROW).substitute(a=str(counter), b=team[0], c=team[1], d=team[2], e=team[3], f=team[4], g=team[5], h=team[6], i=team[7]) params["rows"] = rows html = "templates/full_results.html" # http://127.0.0.1:8000/<будь-який інший запит> else: status = "404 NOT FOUND" html = "templates/error_404.html" start_response(status, headers) with open(html, encoding="utf-8") as f: page = Template(f.read()).substitute(params) return [bytes(page, encoding="utf-8")] HOST = "" PORT = 8000 if __name__ == '__main__': app = MatchResults("data/names.xml", "data/results.xml") from wsgiref.simple_server import make_server print(" === Local webserver === ") make_server(HOST, PORT, app).serve_forever()
) raise falcon.HTTPUnauthorized("Authentication required", description, challenges) def get_app(): middleware = [HandleCORS()] if config.get("common", "api_key"): middleware.append(AuthMiddleware()) api = falcon.API(middleware=middleware) model_type = config.get("common", "model_type") if model_type == ModelType.INSTANCE_SEGMENTATION: from telesto.instance_segmentation.app import add_routes elif model_type == ModelType.CLASSIFICATION: from telesto.classification.app import add_routes else: raise Exception(f"Wrong model type: {model_type}") add_routes(api) return api if __name__ == "__main__": logger.info("Starting dev API server...") from wsgiref import simple_server httpd = simple_server.make_server("0.0.0.0", 9876, get_app()) logger.info("Dev API server started") httpd.serve_forever()
from wsgiref.simple_server import make_server from pyramid.config import Configurator from pyramid.response import Response def hello_world(request): # return "Hello" return Response("Hello World!") def hello_friend(request): return Response("Hello Friend!") if __name__ == "__main__": with Configurator() as config: config.add_route("hello", "/") config.add_route("friend", "/friend") config.add_view(hello_world, route_name="hello") config.add_view(hello_friend, route_name="friend") app = config.make_wsgi_app() server = make_server("0.0.0.0", 6543, app) server.serve_forever()
Path where pycsw expects to find its own configuration file """ # scan from config= or PYCSW_CONFIG environment variable query_string = request_environment.get("QUERY_STRING", "").lower() for kvp in query_string.split('&'): if "config" in kvp: configuration_path = unquote(kvp.split('=')[1]) break else: # did not find any `config` parameter in the request # lets try the process env, request env and fallback to # <pycsw_root>/default.cfg configuration_path = process_environment.get( config_path_key, request_environment.get(config_path_key, os.path.join(pycsw_root, "default.cfg"))) return configuration_path if __name__ == '__main__': # run inline using WSGI reference implementation from wsgiref.simple_server import make_server port = 8000 if len(sys.argv) > 1: port = int(sys.argv[1]) httpd = make_server('', port, application) print('Serving on port {}...'.format(port)) httpd.serve_forever()
def json_view(request): return {'content': 'Hello World'} def html_view(request): return FileResponse('./base.html', content_type='text/html') if __name__ == '__main__': # Set up a config object to work with config = Configurator() # Define Routes config.add_route('basic', '/') config.add_route('json', '/json') config.add_route('html', '/html') # Define Views config.add_view(basic_view, route_name='basic') config.add_view(json_view, route_name='json', renderer='json') config.add_view(html_view, route_name='html') # Create an WSGI instance app = config.make_wsgi_app() # Configure our Server instance server = make_server('0.0.0.0', 6543, app) # Tell the server to start and run forever server.serve_forever()
def run(self, host='localhost', port=8000): server = make_server(host, port, self.app) print "now serving on %s:%s" % (str(host), str(port)) server.serve_forever()
"""Запуск обработчика ака веб сервер""" from wsgiref.simple_server import make_server from framework.main import BestFramework, DebugApp, FakeResponse from urls import fronts from views import routes application = BestFramework(routes, fronts) #application = DebugApp(routes, fronts) #application = FakeResponse(routes, fronts) with make_server("", 8080, application) as httpd: print("Обработка, порт 8080") httpd.serve_forever()
#!/usr/bin/env python # -*- coding: utf-8 -*- __author__ = 'Michael Liao' ''' A WSGI app for DEV ONLY. ''' import logging logging.basicConfig(level=logging.DEBUG) from wsgiref.simple_server import make_server import wsgi if __name__ == '__main__': logging.info('application will start...') server = make_server('127.0.0.1', 8080, wsgi.create_app(debug=True)) server.serve_forever()
train_valObj = train_validation(path) #object initialization train_valObj.train_validation( ) #calling the training_validation function trainModelObj = trainModel() #object initialization trainModelObj.trainingModel( ) #training the model for the files in the table except ValueError: return Response("Error Occurred! %s" % ValueError) except KeyError: return Response("Error Occurred! %s" % KeyError) except Exception as e: return Response("Error Occurred! %s" % e) return Response("Training successfull!!") port = int(os.getenv("PORT", 5000)) if __name__ == "__main__": host = '0.0.0.0' port = 5000 httpd = simple_server.make_server(host, port, app) print("Serving on %s %d" % (host, port)) httpd.serve_forever()
@view_config(header="X-Github-Event:push") def payload_push(self): """This method is a continuation of PayloadView process, triggered if header HTTP-X-Github-Event type is Push""" # {u'name': u'marioidival', u'email': u'*****@*****.**'} print(self.payload['pusher']) # do busy work... return "nothing to push payload" # or simple {} @view_config(header="X-Github-Event:pull_request") def payload_pull_request(self): """This method is a continuation of PayloadView process, triggered if header HTTP-X-Github-Event type is Pull Request""" # {u'name': u'marioidival', u'email': u'*****@*****.**'} print(self.payload['pusher']) # do busy work... return "nothing to pull request payload" # or simple {} if __name__ == "__main__": config = Configurator() config.add_route("github_payload", "/github_payload/") config.scan() app = config.make_wsgi_app() server = make_server("0.0.0.0", 8888, app) server.serve_forever()
from wsgiref.simple_server import make_server def RunServer(envuron, start_response): start_response('200 ok', [('Content-Tyep', 'text/html')]) return ['<h1>hello,web</h1>'.encode('utf-8')] if __name__ == "__main__": httpd = make_server('', 8001, RunServer) print('server on 8001') httpd.serve_forever()
def application(environ, start_response): # resolve QUERY_STRING d = parse_qs(environ['QUERY_STRING']) print(d) age = d.get('age', [''])[0] hobbies = d.get('hobbies', []) age = escape(age) hobbies = [escape(hobby) for hobby in hobbies] response_body = html.format( checked_software=('', 'checked')['software' in hobbies], checked_tunning=('', 'checked')['tunning' in hobbies], age=age or 'Empty', hobbies=','.join(hobbies) or 'No hobbies?') send_msg = response_body.encode() status = '200 OK' content_len = len(response_body) response_headers = [ ('Content-Type', 'text/html'), ('Content-Length', str(content_len)), ('Server', 'NOmansky'), ] start_response(status, response_headers) return [send_msg] httpd = make_server('localhost', 8051, application) httpd.serve_forever() print('Ended...')
except Exception: resp.body = str(error) resp.status = falcon.HTTP_400 error = True if not error: if "value" not in data: resp.body = str(error) resp.status = falcon.HTTP_400 error = True else: hello_mongo.post(data["value"]) resp.status = falcon.HTTP_200 resp.body = "" def on_delete(self, req, resp): resp.status = falcon.HTTP_200 resp.body = hello_redis.delete() render_index = RenderIndex() render_redis = RenderRedis() render_mongo = RenderMongo() app.add_route("/", render_index) app.add_route("/api/v1/redis/helloworld", render_redis) app.add_route("/api/v1/mongo/helloworld", render_mongo) if __name__ == "__main__": httpd = simple_server.make_server("0.0.0.0", 8000, app) httpd.serve_forever()
green_y = round(center[max_index][1]) # 青色抽出 hsv_min_blue = np.array([100,140,140]) # 色相・彩度・明度 hsv_max_blue = np.array([120,255,255]) mask_blue = cv2.inRange(hsv_image, hsv_min_blue, hsv_max_blue) label = cv2.connectedComponentsWithStats(mask_blue) if(label[0] == 1): blue_x = 0 blue_y = 0 else: n = label[0] - 1 data = np.delete(label[2], 0, 0) center = np.delete(label[3], 0, 0) max_index = np.argmax(data[:,4]) blue_x = round(center[max_index][0]) blue_y = round(center[max_index][1]) # return [json.dumps({'x' : return_x_value_of_red()}).encode("utf-8")] return [json.dumps({ 'color_list' : ['red', 'yellow', 'green', 'blue'], 'x_axis' : [red_x, yellow_x, green_x , blue_x], 'y_axis' : [red_y, yellow_y, green_y , blue_y] }).encode("utf-8")] with make_server('', 8080, app) as httpd: print("Serving on port 8080...") httpd.serve_forever()
def main(): rest = Application([MultiProtService], tns=tns, in_protocol=HttpRpc(), out_protocol=HttpRpc()) xml = Application([MultiProtService], tns=tns, in_protocol=HttpRpc(), out_protocol=XmlDocument()) soap = Application([MultiProtService], tns=tns, in_protocol=HttpRpc(), out_protocol=Soap11()) html = Application([MultiProtService], tns=tns, in_protocol=HttpRpc(), out_protocol=HtmlMicroFormat()) png = Application([MultiProtService], tns=tns, in_protocol=HttpRpc(), out_protocol=PngClock()) svg = Application([MultiProtService], tns=tns, in_protocol=HttpRpc(), out_protocol=SvgClock()) json = Application([MultiProtService], tns=tns, in_protocol=HttpRpc(), out_protocol=JsonDocument()) jsoni = Application([MultiProtService], tns=tns, in_protocol=HttpRpc(), out_protocol=JsonDocument(ignore_wrappers=False)) jsonl = Application([MultiProtService], tns=tns, in_protocol=HttpRpc(), out_protocol=JsonDocument(complex_as=list)) jsonil = Application([MultiProtService], tns=tns, in_protocol=HttpRpc(), out_protocol=JsonDocument(ignore_wrappers=False, complex_as=list)) msgpack_obj = Application([MultiProtService], tns=tns, in_protocol=HttpRpc(), out_protocol=MessagePackDocument()) msgpack_rpc = Application([MultiProtService], tns=tns, in_protocol=HttpRpc(), out_protocol=MessagePackRpc()) yaml = Application([MultiProtService], tns=tns, in_protocol=HttpRpc(), out_protocol=YamlDocument()) dyn = Application([DynProtService], tns=tns, in_protocol=HttpRpc(validator='soft'), out_protocol=HttpRpc()) DynProtService.protocols = { 'json': Tsetprot(JsonDocument(dyn)), 'xml': Tsetprot(XmlDocument(dyn)), 'yaml': Tsetprot(YamlDocument(dyn)), 'soap': Tsetprot(Soap11(dyn)), 'html': Tsetprot(HtmlMicroFormat(dyn)), 'png': Tsetprot(PngClock(dyn)), 'svg': Tsetprot(SvgClock(dyn)), 'msgpack': Tsetprot(MessagePackDocument(dyn)), } root = WsgiMounter({ 'rest': rest, 'xml': xml, 'soap': soap, 'html': html, 'png': png, 'svg': svg, 'json': json, 'jsoni': jsoni, 'jsonl': jsonl, 'jsonil': jsonil, 'mpo': msgpack_obj, 'mpr': msgpack_rpc, 'yaml': yaml, 'dyn': dyn, }) from wsgiref.simple_server import make_server server = make_server(host, port, root) logging.basicConfig(level=logging.DEBUG) logging.info("listening to http://%s:%d" % (host, port)) logging.info("navigate to e.g. http://%s:%d/json/get_utc_time" % (host, port)) logging.info(" or: http://%s:%d/xml/get_utc_time" % (host, port)) return server.serve_forever()
def start_server(): httpd = make_server(HOST, PORT, Server()) httpd.serve_forever()
os.system('clear') W.printWelcome() print('*' * 40) print( W.printLibsVersion([ 'pyramid', 'numpy', 'openpyxl', 'pandas', 'matplotlib', 'fbprophet', 'datetime', 'setuptools', 'py-common-fetch', 'argparse', 'pyqrcode' ])) with Configurator() as config: config.include('pyramid_jinja2') config.add_route('entry', '/') config.add_route('hello', '/app/welcome') config.add_route('dataset', '/app/dataset') config.add_route('forecast', '/app/forecast') config.add_route('charts', '/app/charts') config.add_route('qrbuilder', '/app/qrbuilder') config.add_static_view(name='app/static/', path='static/') print(__file__) config.scan('__main__') app = config.make_wsgi_app() print('running sevrer:', port) server = make_server('0.0.0.0', port, app) server.serve_forever()
# path. func = some_func args = ['25', '32'] return func, args def application(environ, start_response): headers = [('Content-type', 'text/html')] try: path = environ.get('PATH_INFO', None) if path is None: raise NameError func, args = resolve_path(path) body = func(*args) status = "200 OK" except NameError: status = "404 Not Found" body = "<h1>Not Found</h1>" except Exception: status = "500 Internal Server Error" body = "<h1> Internal Server Error</h1>" finally: headers.append(('Content-length', str(len(body)))) start_response(status, headers) return [body.encode('utf8')] if __name__ == '__main__': from wsgiref.simple_server import make_server srv = make_server('localhost', 8080, application) srv.serve_forever()
mycollection = db_connect() cursor = mycollection.find( {'make': 'Apple MacBook'}) # Getting all the entries from the Collection list_cur = list(cursor) json_data = dumps(list_cur, indent=2) return Response(json_data) def dell_servers(request): mycollection = db_connect() cursor = mycollection.find( {'make': 'Dell'}) # Getting all the entries from the Collection list_cur = list(cursor) json_data = dumps(list_cur, indent=2) return Response(json_data) if __name__ == '__main__': with Configurator() as config: config.add_route('servers', '/') config.add_route('hpservers', '/hp') config.add_route('macbook', '/macbook') config.add_route('dellservers', '/dell') config.add_view(server_info, route_name='servers') config.add_view(hp_info, route_name='hpservers') config.add_view(mac_servers, route_name='macbook') config.add_view(dell_servers, route_name='dellservers') app = config.make_wsgi_app() server = make_server('0.0.0.0', 8080, app) server.serve_forever()
return wrapped return wrapper class UserHandler(Handler): @requires_roles("admin", "user") def get(self): return {"message": "Welcome, admin!"} @requires_roles("admin") def post(self): self.response.status_code = 201 return {"message": "New user added!"} class app(WSGI): routes = [('/user', UserHandler())] if __name__ == "__main__": from wsgiref.simple_server import make_server try: print("Serving on 0.0.0.0:8080...") make_server('0.0.0.0', 8080, app).serve_forever() except KeyboardInterrupt: pass print("Done")
#erver.py # 从wsgiref模块导入: from wsgiref.simple_server import make_server # 导入我们自己编写的application函数: from hello import application # 创建一个服务器,IP地址为空,端口是8000,处理函数是application: httpd = make_server('', 8008, application) print "Serving HTTP on port 8000..." # 开始监听HTTP请求: httpd.serve_forever()
def wsgi(self): httpd = make_server(self.wsgi_host, self.wsgi_port, self.application) print('Serving on port %d...' % self.wsgi_port) httpd.serve_forever()