• python如何为php写后端?


    听到这样一种说法:PHP做前端,python做后端。
    感觉是PHP写控制器,python写Model层。
    在google上搜了半天也没有个答案。
    有人说用python写接口,PHP调用。怎么个实现法呢?还望高手指点一下。

     
    评论 (1) • 链接2011-08-30 
    • 1
      是否是PHP访问Python写的Service? – 黄新颖 2011-09-09
    5个答案

    PHP做前端,PYTHON做后端,为啥要这么做呢,没感觉有什么优点。

    以下是找来的一段示例,原作者为:http://www.quou.cn/archives/673,用socket连接。

    PYTHON代码:

    1. import time
    2. import json
    3. import socket
    4. import traceback
    5. import threading
    6. importSocketServer
    7. classToo:
    8. def __init__(self):
    9. print'Welcome!'
    10. def test(self, args):
    11. return'xxx:%s'% args;
    12. def error(self, args):
    13. return'not function!'
    14. classThreadedTCPRequestHandler(SocketServer.BaseRequestHandler):
    15. def handle(self):
    16. whileTrue:
    17. try:
    18. data =self.request.recv(1024)
    19. ifnot data:
    20. print'end'
    21. break
    22. data = json.read(data)
    23. res =  getattr(self._object, data['func'],'error')(data['args'])
    24. ifnot res:
    25. res =''
    26. res = str(len(res)).rjust(8,'0')+str(res)
    27. self.request.send(res)
    28. except:
    29. print'error in ThreadedTCPRequestHandler :%s, res:%s'%(traceback.format_exc(), data)
    30. classThreadedTCPServer(SocketServer.ThreadingMixIn,SocketServer.TCPServer):
    31. pass
    32. classServer:
    33. def __init__(self, host, port):
    34. self.host = host
    35. self.port = port
    36. ThreadedTCPServer.allow_reuse_address =True
    37. def open(self,object):
    38. ThreadedTCPRequestHandler._object =object
    39. server =ThreadedTCPServer((self.host,self.port),ThreadedTCPRequestHandler)
    40. server.serve_forever()
    41. if __name__ =='__main__':
    42. Server('0.0.0.0',10009).open(Too())

    PHP代码:

    1. <?php
    2. class server{
    3. private $_host;
    4. private $_port;
    5. private $_error;
    6. private $_socket;
    7. private $_class;
    8. function __construct($host, $port){
    9. $this->_host = $host;
    10. $this->_port = $port;
    11. $this->_class ='';
    12. $this->_connect();
    13. }
    14. privatefunction _connect(){
    15. $sock = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
    16. if($sock===false){
    17. $this->_error('error socket_create'.socket_strerror(socket_last_error()));
    18. }
    19. $ret = socket_connect($sock, $this->_host, $this->_port);
    20. if($ret===false){
    21. $this->_error('error socket_connect'.socket_strerror(socket_last_error()));
    22. }
    23. $this->_socket = $sock;
    24. }
    25. publicfunctionobject($class){
    26. $this->_class = $class;
    27. return $this;
    28. }
    29. publicfunction __call($func, $args){
    30. $data = array('class'=> $this->_class,'func'=> $func,'args'=> $args);
    31. $data = json_encode($data);
    32. $socket = $this->_socket;
    33. $res = socket_write($socket, $data, strlen($data));
    34. if($res===false){
    35. $this->_error('error socket_write'.socket_strerror(socket_last_error()));
    36. }
    37. $res = socket_read($socket,1024, PHP_BINARY_READ);
    38. $result = substr($res,8);
    39. $len = intval(substr($res,0,8));
    40. while(true){
    41. if($len != strlen($result)){
    42. $result .= socket_read($socket,1024, PHP_BINARY_READ);
    43. }else{
    44. break;
    45. }
    46. }
    47. return $result;
    48. }
    49. privatefunction _error($errMsg =''){
    50. $this->_error = $errMsg;
    51. echo $errMsg;
    52. exit();
    53. }
    54. publicfunction __destruct(){
    55. $socket = $this->_socket;
    56. socket_write($socket,'',0);//结束
    57. socket_close($socket);
    58. }
    59. }
    60. function microtime_float(){
    61. list($usec, $sec)= explode(" ", microtime());
    62. return((float)$usec +(float)$sec);
    63. }
    64. $start = microtime_float();
    65. $s =new server('127.0.0.1',10009);
    66. $res1 = $s->object('Too')->test('a','b');
    67. $res2 = $s->object('Too')->test('a','b');
    68. $end = microtime_float();
    69. echo $res1.$res2.'<br />';
    70. echo 'cost:'.($end-$start);
    71. ?>
    评论 (0) • 链接 • 2011-09-16

    个人感觉没有必要这么复杂,你可以写个HTTP的API就能实 现对应的功能,当然可以考虑使用远程调用的样子,但是没有你想的那么复杂,你去看下PHPRPC这个开源工程【别被名称迷惑了,也包含 Python,Ruby,Java等多个版本】,是一个简化的远程调用项目,比XML方便多了,我一直在用这个工程做“C/S“结构的站点:
    官方地址: http://www.phprpc.org

    服务器端可以使用任意语言,比如这里的Python

    1. from phprpc import PHPRPC_Server # 引入 PHPRPC Server
    2. import datetime
    3. def helloworld():
    4.     return'helloworld'
    5. def hi(name):
    6.     return'hi %s'% name
    7. server = PHPRPC_Server()
    8. server.add(helloworld)
    9. server.add('hi')
    10. server.add(hi,'hello')
    11. server.add(datetime.datetime.now)
    12. server.debug =True
    13. server.start()

    客户端可以使用任意语言,比如Python和你说的PHP的

    1. from flup.middleware.session importMemorySessionStore,SessionMiddleware
    2. from flup.middleware.gzip importGzipMiddleware
    3. from phprpc import PHPRPC_WSGIApplication,UrlMapMiddleware, PHPRPC_Server
    4. import datetime
    5. def helloworld():
    6.     return'helloworld'
    7. def hi(name):
    8.     return'hi %s'% name
    9. app = PHPRPC_WSGIApplication()
    10. app.add(helloworld)
    11. app.add('hi')
    12. app.add(hi,'hello')
    13. app.add(datetime.datetime.now)
    14. app.debug =True
    15. app =UrlMapMiddleware([('/', app)])
    16. sessionStore =MemorySessionStore()
    17. app =SessionMiddleware(sessionStore, app)
    18. app =GzipMiddleware(app)
    19. PHPRPC_Server(app = app).start()

    下面的是PHP的内容:

    1. <?php
    2. include ("php/phprpc_client.php");
    3. $client =new PHPRPC_Client();
    4. $client->setProxy(NULL);
    5. $client->useService('http://127.0.0.1/server.php');
    6. $client->setKeyLength(1000);
    7. $client->setEncryptMode(3);
    8. $client->setCharset('UTF-8');
    9. $client->setTimeout(10);
    10. echo $client->hi('PHPRPC'),"\r\n";
    11. echo $client->getKeyLength(),"\r\n";
    12. echo $client->getEncryptMode(),"\r\n";
    13. echo $client->getCharset(),"\r\n";
    14. echo $client->getTimeout(),"\r\n";
    15. ?>

    试试这个工程吧,还支持默认的自动对称加密协商,保证在不安全的HTTP方式上安全的传输调用的内容

  • 相关阅读:
    js验证表单大全
    JavaScript验证表单大全
    ASP.NET(c#)操作cookie、session、cache工具类
    AIX查看硬件配置
    SAP* DDIC密码丢失如何处理
    如何学好SAP BASIS
    SAP STMS 传输系统配置
    BOM展开实例
    免安装Oracle客户端使用PL/SQL连接Oracle
    入门培训SAP操作手册 之前台操作
  • 原文地址:https://www.cnblogs.com/xingmeng/p/2890394.html
Copyright © 2020-2023  润新知