方法一:
# -*- coding:utf-8 -*-
from http.server import HTTPServer, BaseHTTPRequestHandler
import urllib
import json
'''========【http端口服务】========'''
class HttpHandler(BaseHTTPRequestHandler):
def do_GET(self):
path, args = urllib.parse.splitquery(self.path)
self._response(path, args)
def do_POST(self):
args = self.rfile.read(int(self.headers['content-length'])).decode("utf-8")
self._response(self.path, args)
def _response(self, path, args):
# 组装参数为字典
if args:
args = urllib.parse.parse_qs(args).items()
args = dict([(k, v[0]) for k, v in args])
else:
args = {}
# 设置响应结果
result = {"status":0,"msg":"操作成功","data":[{"page_id":1},{"page_id":2}]}
self.send_response(200)
self.send_header('Content-type', 'application/json')
self.end_headers()
self.wfile.write(json.dumps(result).encode())
if __name__ == '__main__':
# 开启http服务,设置监听ip和端口
httpd = HTTPServer(('', 8787), HttpHandler)
httpd.serve_forever()
# 运行后 http://localhost:8787 即可访问该接口
方法2:
import tornado.ioloop
import tornado.web
class MainHandler(tornado.web.RequestHandler):
def get(self):
self.write("c=" + str(55))
# application = tornado.web.Application([(r"/add", MainHandler), ])
application = tornado.web.Application([(r"", MainHandler), ])
if __name__ == "__main__":
application.listen(8868)
tornado.ioloop.IOLoop.instance().start()
以上代码可用来mock测试过程中返回指定的数据