# -*- coding:utf-8 -*-
# -*- created by: mo -*-
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')
# print(a)
# print(type(a))
# print(b)
# print(type(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()
运行然后访问 http://127.0.0.1:8868/add?a=1&b=2 就可以了
得到的结果是:
推荐使用Django或者Tornado
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 = '''
Get page
'''
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.
找了好多东西,都不靠普
老版本的: https://www.cnblogs.com/dpf-learn/p/8028029.html
这个不错,但还是不行:https://blog.csdn.net/linux_hacher/article/details/78753805
看到这里,原来改版了:https://docs.python.org/3/library/http.server.html#http.server.SimpleHTTPRequestHandler
不过把BaseHTTPServer、CGIHTTPServer等,在便3.4.2后都集成到http.server里边去了