通过tornado实现其他语言和python接口的衔接,进行参数的传入传出

说明:为了实现其他语言和python接口的衔接,我们通过tornado实现,在http传入参数,python接收,经过python代码处理后,再把结果写到http,其他语言对结果做一接收。

先把python部分的代码写好:example.py

#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
@author:
@contact:
@time:
@context:
"""
#引入库
import json

def exam(x,z):
    result={}
    result["z1"] = x
    result["z2"]=z
    resultJson = json.dumps(result)
    return resultJson

调用上面的代码,并且写接收http参数以及结果输出部分的代码:exampleServer.py

#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
@author:
@contact:
@time:
@context:
"""
# !/usr/bin/env python
# -*- coding:utf-8 -*-

import tornado.web,json,example
from tornado.concurrent import run_on_executor
from concurrent.futures import ThreadPoolExecutor


class MainHandler(tornado.web.RequestHandler):
    executor = ThreadPoolExecutor(5)
    
    def initialize(self, hh):
        self.qq = hh

    def get(self):
        self.write("Hello, world")

    @tornado.gen.coroutine
    def post(self):
        resDict = yield self.fun()
        self.write(resDict)

    @run_on_executor
    def fun(self):
        param = self.request.body
        param_json = json.loads(param.decode('utf-8'))
        x = param_json['x']
        z = param_json['z']
        result = self.qq.exam(x,z)
        return result
        

if __name__ == "__main__":
    qq = example
    app = tornado.web.Application(handlers=[(r"/example", MainHandler, {"hh": qq})],
                                  autoreload=False, debug=False)
    http_server = tornado.httpserver.HTTPServer(app)
    http_server.bind(1890)
    http_server.start()
    tornado.ioloop.IOLoop.instance().start()

如果上面的代码部署在本地跑,则用:http://localhost:1890/example

在这里插入图片描述
如果上面的代码部署在服务器,则:http://XXX.XXX.X.XXX:1900/example
在这里插入图片描述

当然,如果我们只是单纯调用python函数,则:

#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
@author:
@contact:
@time:
@context:
"""
import example

x=[4,1,7,6]
z=[1,1,2,3]
a=example.exam(x,z)
print(a)
©️2020 CSDN 皮肤主题: 精致技术 设计师:CSDN官方博客 返回首页