def run_server(HandlerClass=SimpleHTTPRequestHandler, port=8000): print('http server is starting...') #ip and port of servr #by default http server port is 80 server_address = ('', port) HandlerClass.protocol_version = "HTTP/1.0" httpd = HTTPServer(server_address, SimpleHTTPRequestHandler) print('http server is running...') httpd.serve_forever() print('Should not be printed')
def run(root, host, port): logging.info("Starting server") server = HTTPServer(root, host, port) server.bind() try: server.wait() except KeyboardInterrupt: logging.info("SERVER\tstop") server.close()
#!/usr/bin/python from server import HTTPServer server = HTTPServer() server.main()
def main(): port = 4321 root_dir = '/home' # be careful of the relative path, since it depends on this file's execution path http_server = HTTPServer(port, root_dir) http_server.start()
channel = '/' def _text_html(self, client): tpl = templates.get_template('index.html') return tpl.render(**client.data) @method def GET(self, client): return {"message": "Hello World!"} GET.codec('application/json', 0.9) GET.codec('text/html', 1.0, charset='utf-8')(_text_html) @method def POST(self, client): data = dict(client.request.body.data) message = 'Hello %s %s' % (data.get('firstName'), data.get('lastName')) return {'message': cgi.escape(message, True)} POST.codec('application/json', 0.9) POST.codec('text/html', 1.0, charset='utf-8')(_text_html) POST.accept('application/x-www-form-urlencoded') if __name__ == '__main__': server = HTTPServer() server.localhost += MakoTemplated() server += Debugger(events=True) server.run()
import machine import time import ujson from i2c import I2CBus from server import HTTPServer from tmp102 import TMP102 from wlan import MyWLAN rtc = machine.RTC() rtc.datetime((2019, 8, 30, 2, 7, 33, 0, 0)) wlan = MyWLAN() i2c = I2CBus() tmp = TMP102(i2c) http = HTTPServer() __ts1970_2000 = 946684800 def temperature(): t = tmp.read_temperature() return ujson.dumps({"t": t, "ts": time.time() + __ts1970_2000}) while True: wlan.connect() while wlan.is_connected(): print(temperature()) time.sleep(1) time.sleep(10)
"""Simple running exmample""" import json from server import Request from server import Response from server import HTTPServer from server import Application Request.register_body_handler("text/json", json.loads) httpd = HTTPServer(("0.0.0.0", 15014)) application = Application(__name__) httpd.serve(application) @application.route("/hello", methods=["GET"]) def test_get_function(request): """Hello World!""" # __import__("time").sleep(10) return \ """ <html> <body style="background: #dfe6e9; text-align:center;"> <h1 style="margin-top:30vh;">Hello World</h1> <h3>From: Simple-Python-HTTP-Server</h3> <h4 style="font-style: italic;">Your UA info: {UA}</h4> </body> </html> """.format(UA=request.headers.get("User-Agent", ''))
if url == path: return handler(env, start_response) status = '404 Not Found' headers = [('Connection', 'keep-alive')] start_response(status, headers) return 'page not found' def show_time(env, start_response): status = '200 ok' headers = [('Connection', 'keep-alive')] start_response(status, headers) return time.ctime() def say_hello(env, start_response): status = '200 ok' headers = [('Connection', 'keep-alive')] start_response(status, headers) return 'Hi, I am gougou' if __name__ == '__main__': urls = [('/ctime', show_time), ('/say_hello', say_hello), ('/', show_time)] app = Application(urls) http_server = HTTPServer(app) http_server.bind('127.0.0.1', 7788) http_server.start()
#!/usr/bin/python import os, sys from server import Config, HTTPServer, WSServer from server.build import BuildEventHandler from server.io import IOEventHandler from server.project import Project, ProjectEventHandler, AssetFolderWatcher from server.components import DefaultComponentManager try: os.chdir(os.path.dirname(os.path.realpath(sys.argv[0]))+'/editor') Project.initialize() WSServer.serve(blocking = False) HTTPServer.serve() except KeyboardInterrupt: exit() pass
#!/usr/bin/python import os, sys from server import Config, HTTPServer, WSServer from server.build import BuildEventHandler from server.io import IOEventHandler from server.project import Project, ProjectEventHandler, AssetFolderWatcher from server.components import DefaultComponentManager try: os.chdir(os.path.dirname(os.path.realpath(sys.argv[0])) + '/editor') Project.initialize() WSServer.serve(blocking=False) HTTPServer.serve() except KeyboardInterrupt: exit() pass
def show_ctime(env, start_response): status = "200 OK" headers = [("Content-Type", "text/plain")] return time.ctime() def say_hello(env, start_response): status = "200 OK" headers = [("Content-Type", "text/plain")] return "hello web" def say_haha(env, start_response): status = "200 OK" headers = [("Content-Type", "text/plain")] return "hello haha" if __name__ == "__main__": # url+handler urls = [("/", show_ctime), ("/ctime", show_ctime), ("/sayhello", say_hello), ("/sayhaha", say_haha)] # 创建app app = Application(urls) # 把app传给web服务器主体 http_server = HTTPServer(app) http_server.bind(8000) http_server.start()
from loop import Loop looper = Loop(config) # importing the handler from handlers import Handler # initializing the handler # includes all callbacks handler = Handler(looper.com, users) # importing the server implmentation from server import HTTPServer # Starting the webserver, passing in all # route definitions http_server = HTTPServer(config, handler.routes) try: # start the processes looper.start() loop, tasks = http_server.run() loop.run_until_complete(tasks) loop.run_forever() except KeyboardInterrupt: looper.stop() exit('=================== Server Shutting Down... ====================') except Exception as e:
from server import HTTPServer if __name__ == "__main__": host = "127.0.0.1" port = 8000 server = HTTPServer(host, port) try: server.run_forever() except KeyboardInterrupt: pass
if crypt(password, salt) == passwd: print 'authentication was successful' client.authenticated = True return print 'authentication failed' raise UNAUTHORIZED() @handler('routing', priority=2) def _on_request(self, client): client.authenticated = False yield self.wait(self.fire(authentication(client)).event) class Protected(Resource): channel = '/' @method def GET(self, client): return {"message": "Top secret!"} GET.codec('application/json') GET.conditions(lambda client: client.authenticated) # TODO: raise 401 Unauthorized if __name__ == '__main__': server = HTTPServer() server.localhost += Protected() server += ShadowAuth(channel=server.channel) server += Debugger(events=True) server.run()
def __init__(self, *args, **kwargs): HTTPServer.__init__(self, *args, **kwargs) self.graph = graph.GraphDrawer()
@time: 2019/11/9 10:41 """ import datetime from base import HTTPResponse, HTTPHeader from server import HTTPServer from web import RequestHandler class Hello(RequestHandler): def get(self): res = HTTPResponse(status_code=200, status_msg='OK') res.content = "<h1>Hello World!</h1>" res.header = HTTPHeader({ 'Date': datetime.datetime.now().strftime("%a, %d %b %Y %H:%M:%S GMT"), 'Server': 'mars', 'Content-Type': 'text/html', 'Content-Length': len(res.content) }) self.write(res) if __name__ == '__main__': server = HTTPServer(host='127.0.0.1', port=8085) server.register_handler({'/hello': Hello}) server.run()
return parser.parse_args() def create_logger(logpath): fmt, dfmt = '[%(asctime)s] %(levelname).1s %(message)s', '%Y.%m.%d %H:%M:%S' logging.basicConfig(filename=logpath, format=fmt, datefmt=dfmt, level=logging.INFO) if __name__ == '__main__': args = parse_args() create_logger(args.log) try: server = HTTPServer(args.host, args.port, args.document_root, args.workers, args.max_connections) server.start() except Exception as e: logging.error(f'Unable to launch the server: {e}') sys.exit() try: server.run_workers() except KeyboardInterrupt: server.terminate_workers() except Exception as e: server.terminate_workers() logging.error(f'Unknown error: {e}') finally: server.shutdown()