由於後端的服務很負責,訓練的模型都是基於python的tensorflow的,因此用RPC(remote procedual comminication);php
接口用的是php寫的,方便http協議調用;html
過程就是http:www.../... -> nginx-> POST -> 參數傳到test.php,調用 -> 經過RPC -> server.py處理 python
server.py處理以後,經過RPC返回到test.php再嵌入到html文檔裏面,這樣一個post+RPC的過程就完成了;nginx
php+python的模式是線上服務使用的,我這裏實驗了一下,成功跑通了,分享幾個最基本的文件;後端
example.thrift:服務器
namespace py example
namespace php example
service Alice {
string ask(1:string question)
}
而後用thrift --gen php example.thrift app
thrift --gen py example.thriftsocket
下面的是客戶端的test.php:post
<?php namespace example\php; error_reporting(E_ALL); require_once './thrift/thrift-0.10.0/lib/php/lib/Thrift/ClassLoader/ThriftClassLoader.php'; use Thrift\ClassLoader\ThriftClassLoader; $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 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"; } ?>
最後是我用的服務器程序,很簡單的一個返回:ui
#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 + '豬\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!"
<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>