http服务提供者(python)
概述
此示例演示如何使用python_sdk编写http服务提供程序,python_sdk提供简单易用的接口给客户调用,与服务端通信/响应通告等细节sdk内部都完现了,http服务可使用常用web库实现,譬如flask,tornado,django等,这里使用简单的BaseHTTPServer.BaseHTTPRequestHandler。
示例源文件: python_sdk/sample_http_prvd.py
示例准备:先运行服务端cppcloud_serv,记下ip地址和端口。
示例代码
import threading
import cppcloud
from cppcloud.provider import ProviderBase
from http.server import HTTPServer, BaseHTTPRequestHandler
listen_port = 8000
class TestHTTPHandler(BaseHTTPRequestHandler):
#处理GET请求
def do_GET(self):
self.send_response(200)
#self.send_header("Content-Type", 'application/json; charset=utf-8')
#self.send_header("Content-Length:", len(buff))
self.end_headers()
respmsg = "request GET from " + str(self.client_address) + ": path=" + self.path
self.wfile.write(respmsg.encode())
def do_POST(self):
self.send_response(200)
datas = self.rfile.read(int(self.headers['content-length']))
#self.send_header("Content-Type", 'application/json; charset=utf-8')
#self.send_header("Content-Length", len(buff))
self.end_headers()
respmsg = "request POST from " + str(self.client_address) + ": body="
self.wfile.write(respmsg.encode())
self.wfile.write(datas)
#if exit: http_server.shutdown()
# 服务注册类,只有调用Regist()方法,消费者才能发现此服务
class HttpProvider(ProviderBase):
scheme = 'http'
port = listen_port
http_path = '/proj'
if __name__ == "__main__":
if cppcloud.init('vpc2', 4800, svrname="httpApp1"):
http_server = HTTPServer(('', int(listen_port)), TestHTTPHandler)
http_thread = threading.Thread(target=http_server.serve_forever, name="Http_server")
http_thread.setDaemon(True)
http_thread.start()
HttpProvider.Regist(True)
input('press any key to exit')
cppcloud.uninit()
else:
print('CloudApp start fail, exit')
说明
- http服务本例子是用BaseHTTPRequestHandler实现,具体使用不在本次讨论范围,本页只讲解cppcloud相关的部分;
- 主要要做的就是定义HttpProvider类,把相关信息设置到类成员,并调用Regist()方法即可; 可见用起来是相当简单的;
- 对外提供的服务名是
httpApp
启动运行
先把示例代码中的
vpc2
修改为你当前的cppcloud_serv的服务地址;python sample_http_prvd.py
演示结果
可以看到这个http服务处理了GET和POST方式,对外提供服务的url是http://192.168.228.10:8000/proj
,响应包体未打印,可以在消费端是看得到。