因为后端的服务很负责,训练的模型都是基于python的tensorflow的,所以用RPC(remote procedual comminication);
接口用的是php写的,方便http协议调用;
过程就是http:www.../... -> nginx-> POST -> 参数传到test.php,调用 -> 通过RPC -> server.py处理
server.py处理之后,通过RPC返回到test.php再嵌入到html文档里面,这样一个post+RPC的过程就完成了;
php+python的模式是线上服务使用的,我这里实验了一下,成功跑通了,分享几个最基本的文件;
example.thrift:
namespace py example namespace php example service Alice { string ask(1:string question)}
然后用thrift --gen php example.thrift
thrift --gen py example.thrift
下面的是客户端的test.php:
registerNamespace('Thrift', '/home/yanjianfeng/nginx/thrift/thrift-0.10.0/lib/php/lib');$loader->registerDefinition('example', $GEN_DIR);$loader->register();use Thrift\Protocol\TBinaryProtocol;use Thrift\Transport\TSocket;use Thrift\Transport\THttpClient;use Thrift\Transport\TBufferedTransport;use Thrift\Exception\TException;try { $socket = new TSocket('localhost', 30303); $transport = new TBufferedTransport($socket, 1024, 1024); $protocol = new TBinaryProtocol($transport); $client = new \example\AliceClient($protocol); $transport->open(); $ques = $_POST["ques"]; $sum = $client->ask($ques); echo $sum;} catch (TException $tx) { print 'TException: '.$tx->getMessage()."\n";}?>
最后是我用的服务器程序,很简单的一个返回:
#encoding=utf-8import syssys.path.append('./gen-py')from example import Alice from example.ttypes import *from thrift.transport import TSocketfrom thrift.transport import TTransportfrom thrift.protocol import TBinaryProtocolfrom thrift.server import TServerclass chat: def __init__(self): print 'initializat' def ask(self, ques): return ques + '猪\n' handler = chat()processor = Alice.Processor(handler)transport = TSocket.TServerSocket('localhost',30303)tfactory = TTransport.TBufferedTransportFactory()pfactory = TBinaryProtocol.TBinaryProtocolFactory()server = TServer.TSimpleServer(processor, transport, tfactory, pfactory)print "Starting python server..."server.serve()print "done!"
DEMO