一、python3.6写一个http接口服务,给别人调用1
首先推荐tornado,Tornado是一个Python web框架和异步网络库,最初在FriendFeed开发。通过使用无阻塞网络I/O,Tornado可以扩展到数万个开放连接,使其成为长轮询、WebSocket和其他需要与每个用户建立长时间连接的应用程序的理想选择。简易而且本地win10能够跑起来。
二、Tornado的get接口代码实现
1. pip install tornado
2. 代码调用:
import tornado.ioloop
import tornado.web
class MainHandler(tornado.web.RequestHandler):
def get(self):
"""get请求"""
a = self.get_argument('a')
b = self.get_argument('b')
c = int(a) + int(b)
self.write("c=" + str(c))
application = tornado.web.Application([(r"/add", MainHandler), ])
if __name__ == "__main__":
application.listen(8868)
tornado.ioloop.IOLoop.instance().start()
浏览器请求结果:
三、调用一个函数的
# -*- 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 = '''
Get pagea:
b:
'''
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里边去了