試驗thrift做后端rpc,nginx做web服務器, python后端php前端


因為后端的服務很負責,訓練的模型都是基於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 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";
}

?>

最后是我用的服務器程序,很簡單的一個返回:

#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>

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM