python3.6寫一個http介面服務,給別人呼叫
阿新 • • 發佈:2019-02-03
# -*- coding:utf-8 -*- # -*- created by: mo -*- import tornado.ioloop import tornado.web class MainHandler(tornado.web.RequestHandler): def get(self): self.write("tornado > django") application = tornado.web.Application([(r"/", MainHandler),]) if __name__ == "__main__": application.listen(8868) tornado.ioloop.IOLoop.instance().start()
2.呼叫一個函式的
# -*- coding:utf-8 -*- # -*- created by: mo -*- from concurrent.futures import ThreadPoolExecutor from tornado.concurrent import run_on_executor import tornado.httpserver import tornado.ioloop import tornado.options import tornado.web import tornado.gen import json import traceback def add(a,b): c = int(a) + int(b) return str(c) class MainHandler(tornado.web.RequestHandler): executor = ThreadPoolExecutor(32) @tornado.gen.coroutine def get(self): '''get介面''' htmlStr = ''' <!DOCTYPE HTML><html> <meta charset="utf-8"> <head><title>Get page</title></head> <body> <form action="/post" method="post" > a:<br> <input type="text" name ="a" /><br> b:<br> <input type="text" name ="b" /><br> <input type="submit" value="add" /> </form></body> </html> ''' self.write(htmlStr) @tornado.web.asynchronous @tornado.gen.coroutine def post(self): '''post介面, 獲取引數''' a = self.get_argument("a", None) b = self.get_argument("b", None) yield self.coreOperation(a, b) @run_on_executor def coreOperation(self, a, b): '''主函式''' try: if a != '' and b != '': result = add(a, b) #可呼叫其他介面 if result: result = json.dumps({'code': 200, 'result': result, }) else: result = json.dumps({'code': 210, 'result': 'no result',}) else: result = json.dumps({'code': 211, 'result': 'wrong input a or b', }) self.write(result) except Exception: print ('traceback.format_exc():\n%s' % traceback.format_exc()) result = json.dumps({'code': 503,'result': str(a)+'+'+str(b)}) self.write(result) if __name__ == "__main__": tornado.options.parse_command_line() app = tornado.web.Application(handlers=[(r'/post', MainHandler)], autoreload=False, debug=False) http_server = tornado.httpserver.HTTPServer(app) http_server.listen(8832) tornado.ioloop.IOLoop.instance().start()
結果為:
1.
2.
.
找了好多東西,都不靠普
不過把BaseHTTPServer、CGIHTTPServer等,在便3.4.2後都整合到http.server裡邊去了