因为后端的服务很负责,训练的模型都是基于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:
<?php namespace examplephp; error_reporting(E_ALL); require_once './thrift/thrift-0.10.0/lib/php/lib/Thrift/ClassLoader/ThriftClassLoader.php'; use ThriftClassLoaderThriftClassLoader; $GEN_DIR = './thrift/test/gen-php'; $loader = new ThriftClassLoader(); $loader->registerNamespace('Thrift', '/home/yanjianfeng/nginx/thrift/thrift-0.10.0/lib/php/lib'); $loader->registerDefinition('example', $GEN_DIR); $loader->register(); use ThriftProtocolTBinaryProtocol; use ThriftTransportTSocket; use ThriftTransportTHttpClient; use ThriftTransportTBufferedTransport; use ThriftExceptionTException; try { $socket = new TSocket('localhost', 30303); $transport = new TBufferedTransport($socket, 1024, 1024); $protocol = new TBinaryProtocol($transport); $client = new exampleAliceClient($protocol); $transport->open(); $ques = $_POST["ques"]; $sum = $client->ask($ques); echo $sum; } catch (TException $tx) { print 'TException: '.$tx->getMessage()." "; } ?>
最后是我用的服务器程序,很简单的一个返回:
#encoding=utf-8 import sys sys.path.append('./gen-py') from example import Alice from example.ttypes import * from thrift.transport import TSocket from thrift.transport import TTransport from thrift.protocol import TBinaryProtocol from thrift.server import TServer class chat: def __init__(self): print 'initializat' def ask(self, ques): return ques + '猪 ' 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!"
<html> <center> DEMO </center> <br> <form name="form" action="test.php" method="post"> <center>ques <input type="text" name="ques" size="12" maxlength="20"></center> </form> </html>