python3.6写一个http接口服务,给别人调用1
大家好,又见面了,我是你们的朋友全栈君。
一、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
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)
@tornado.gen.coroutine
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)
@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.
.
找了好多东西,都不靠普
老版本的: 用Python编写一个简单的Http Server – 丁培飞 – 博客园
这个不错,但还是不行:python 搭建简单的http server,可直接post文件_Ghost-CSDN博客_httpserver post python
看到这里,原来改版了:http.server — HTTP servers — Python 3.10.2 documentation
不过把BaseHTTPServer、CGIHTTPServer等,在便3.4.2后都集成到http.server里边去了
发布者:全栈程序员栈长,转载请注明出处:https://javaforall.cn/142173.html原文链接:https://javaforall.cn
相关文章
- python3.7如何安装numpy库_python升级后第三方库
- pycharm怎么安装requests模块_python3安装模块
- pycharm怎么设置编码格式_python3设置编码为utf8
- 关于Python3的import问题(pycharm可以运行,命令行import错误)
- python3 软连接_python3哪个版本好用
- python3 高斯函数
- pycharm安装dlib失败_python3.8.0安装教程
- python3获取Elasticsearch数据库数据
- python3.x默认使用UTF-8编码_pycharm怎么debug
- pycharm配置tensorflow环境_python3.6对应的tensorflow版本
- 无法安装python3的连续报错-mysql include软链接问题
- tensorflow pycharm教程_tensorflow支持python3.8吗
- 解决pycharm添加python2.7解释器出现Failed to create virtual environment和添加python3.8解释器SDK无效问题[通俗易懂]
- Python3对多股票的投资组合进行分析「建议收藏」
- 翻身了?Python3.11性能测评超3.10近64%
- pycharm中tensorflow配置环境_python3.6安装tensorflow
- pycharm如何创建新项目_Python3
- python3.4的pygame安装
- python3.8安装matplotlib_matplotlib画图
- centos安装python3详细教程[通俗易懂]