听到这样一种说法:PHP做前端,python做后端。
感觉是PHP写控制器,python写Model层。
在google上搜了半天也没有个答案。
有人说用python写接口,PHP调用。怎么个实现法呢?还望高手指点一下。
-
1是否是PHP访问Python写的Service? – 黄新颖 2011-09-09
5个答案
PHP做前端,PYTHON做后端,为啥要这么做呢,没感觉有什么优点。
以下是找来的一段示例,原作者为:http://www.quou.cn/archives/673,用socket连接。
PYTHON代码:
- import time
- import json
- import socket
- import traceback
- import threading
- importSocketServer
- classToo:
- def __init__(self):
- print'Welcome!'
- def test(self, args):
- return'xxx:%s'% args;
- def error(self, args):
- return'not function!'
- classThreadedTCPRequestHandler(SocketServer.BaseRequestHandler):
- def handle(self):
- whileTrue:
- try:
- data =self.request.recv(1024)
- ifnot data:
- print'end'
- break
- data = json.read(data)
- res = getattr(self._object, data['func'],'error')(data['args'])
- ifnot res:
- res =''
- res = str(len(res)).rjust(8,'0')+str(res)
- self.request.send(res)
- except:
- print'error in ThreadedTCPRequestHandler :%s, res:%s'%(traceback.format_exc(), data)
- classThreadedTCPServer(SocketServer.ThreadingMixIn,SocketServer.TCPServer):
- pass
- classServer:
- def __init__(self, host, port):
- self.host = host
- self.port = port
- ThreadedTCPServer.allow_reuse_address =True
- def open(self,object):
- ThreadedTCPRequestHandler._object =object
- server =ThreadedTCPServer((self.host,self.port),ThreadedTCPRequestHandler)
- server.serve_forever()
- if __name__ =='__main__':
- Server('0.0.0.0',10009).open(Too())
PHP代码:
- <?php
- class server{
- private $_host;
- private $_port;
- private $_error;
- private $_socket;
- private $_class;
- function __construct($host, $port){
- $this->_host = $host;
- $this->_port = $port;
- $this->_class ='';
- $this->_connect();
- }
- privatefunction _connect(){
- $sock = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
- if($sock===false){
- $this->_error('error socket_create'.socket_strerror(socket_last_error()));
- }
- $ret = socket_connect($sock, $this->_host, $this->_port);
- if($ret===false){
- $this->_error('error socket_connect'.socket_strerror(socket_last_error()));
- }
- $this->_socket = $sock;
- }
- publicfunctionobject($class){
- $this->_class = $class;
- return $this;
- }
- publicfunction __call($func, $args){
- $data = array('class'=> $this->_class,'func'=> $func,'args'=> $args);
- $data = json_encode($data);
- $socket = $this->_socket;
- $res = socket_write($socket, $data, strlen($data));
- if($res===false){
- $this->_error('error socket_write'.socket_strerror(socket_last_error()));
- }
- $res = socket_read($socket,1024, PHP_BINARY_READ);
- $result = substr($res,8);
- $len = intval(substr($res,0,8));
- while(true){
- if($len != strlen($result)){
- $result .= socket_read($socket,1024, PHP_BINARY_READ);
- }else{
- break;
- }
- }
- return $result;
- }
- privatefunction _error($errMsg =''){
- $this->_error = $errMsg;
- echo $errMsg;
- exit();
- }
- publicfunction __destruct(){
- $socket = $this->_socket;
- socket_write($socket,'',0);//结束
- socket_close($socket);
- }
- }
- function microtime_float(){
- list($usec, $sec)= explode(" ", microtime());
- return((float)$usec +(float)$sec);
- }
- $start = microtime_float();
- $s =new server('127.0.0.1',10009);
- $res1 = $s->object('Too')->test('a','b');
- $res2 = $s->object('Too')->test('a','b');
- $end = microtime_float();
- echo $res1.$res2.'<br />';
- echo 'cost:'.($end-$start);
- ?>
-
2 票
-
个人感觉没有必要这么复杂,你可以写个HTTP的API就能实
现对应的功能,当然可以考虑使用远程调用的样子,但是没有你想的那么复杂,你去看下PHPRPC这个开源工程【别被名称迷惑了,也包含
Python,Ruby,Java等多个版本】,是一个简化的远程调用项目,比XML方便多了,我一直在用这个工程做“C/S“结构的站点:
官方地址: http://www.phprpc.org
服务器端可以使用任意语言,比如这里的Python
- from phprpc import PHPRPC_Server # 引入 PHPRPC Server
- import datetime
- def helloworld():
- return'helloworld'
- def hi(name):
- return'hi %s'% name
- server = PHPRPC_Server()
- server.add(helloworld)
- server.add('hi')
- server.add(hi,'hello')
- server.add(datetime.datetime.now)
- server.debug =True
- server.start()
客户端可以使用任意语言,比如Python和你说的PHP的
- from flup.middleware.session importMemorySessionStore,SessionMiddleware
- from flup.middleware.gzip importGzipMiddleware
- from phprpc import PHPRPC_WSGIApplication,UrlMapMiddleware, PHPRPC_Server
- import datetime
- def helloworld():
- return'helloworld'
- def hi(name):
- return'hi %s'% name
- app = PHPRPC_WSGIApplication()
- app.add(helloworld)
- app.add('hi')
- app.add(hi,'hello')
- app.add(datetime.datetime.now)
- app.debug =True
- app =UrlMapMiddleware([('/', app)])
- sessionStore =MemorySessionStore()
- app =SessionMiddleware(sessionStore, app)
- app =GzipMiddleware(app)
- PHPRPC_Server(app = app).start()
下面的是PHP的内容:
- <?php
- include ("php/phprpc_client.php");
- $client =new PHPRPC_Client();
- $client->setProxy(NULL);
- $client->useService('http://127.0.0.1/server.php');
- $client->setKeyLength(1000);
- $client->setEncryptMode(3);
- $client->setCharset('UTF-8');
- $client->setTimeout(10);
- echo $client->hi('PHPRPC'),"\r\n";
- echo $client->getKeyLength(),"\r\n";
- echo $client->getEncryptMode(),"\r\n";
- echo $client->getCharset(),"\r\n";
- echo $client->getTimeout(),"\r\n";
- ?>
试试这个工程吧,还支持默认的自动对称加密协商,保证在不安全的HTTP方式上安全的传输调用的内容