专栏文章 Python3 开发 API 接口给别人调用【1】

大海 · 2022年04月27日 · 2360 次阅读

一、python3 写一个 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
import json


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))

    def post(self):
        '''post请求'''
        body = self.request.body
        body_decode = body.decode()
        body_json = json.loads(body_decode)
        a = body_json.get("a")
        b = body_json.get("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()

3.  GET 接口访问:http://127.0.0.1:8868/add?a=1&b=2 
 浏览器请求结果:

4. POST 接口请求  http://127.0.0.1:8868/add

也可以使用 Django 或者 Tornado 

三、调用一个函数的

# -*- 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)
    @user1e
    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)

    @user2nous
    @user3e
    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://yongzhuo.blog.csdn.net/article/details/80474706

如果觉得我的文章对您有用,请随意打赏。您的支持将鼓励我继续创作!
暂无回复。
需要 登录 后方可回复, 如果你还没有账号请点击这里 注册