php calls python service

Keywords: PHP Python socket Javascript

php calls python service

Kan Kan: The popen of php used by the company calls python in the form of commands. First of all, it talks about the shortcomings of doing so.
The disadvantage of php executing command line call python
popen('python test.py [parameter]','r');
Disadvantage 1: windows defaults to gbk encoding. When utf-8 parameters are transmitted in php, the parameters received by python will be problematic.

Of course, there is a solution, that is, downconversion of character encoding in windows, linux does not need conversion. When python receives the parameters, it must also convert the code. Are you bothered?

The cmd command or shell command is limited in length. When the parameters passed are too long, the received parameters will not be complete.
It's dangerous to execute shell commands in case there's anything more in the parameters, you know.

This can also solve the problem of escapeshellarg in php. Hmm, give him escape first.

Then what shall I do?
python socket server
Not to mention more, the unclear Baidu "socket", the following code (written a php call Python services beautify javascript applications, server-side python):

The modules referenced in the code will be given in the attachment.

import sys, json
import traceback
import SocketServer
from daemon import Daemon
import jsbeautifier

class Todo:

def __init__(self):
    print('Welcome!')
def test(self, args):
    res = jsbeautifier.beautify(args[0].encode('utf-8'))
    return res;
def error(self, args):
    return 'not function!'

class ThreadedTCPRequestHandler(SocketServer.BaseRequestHandler):

def handle(self):
    while True:
        try:
            data = self.request.recv(2*1024*1024)
            if not data:
                print('end')
                break
            data = json.loads(data)
            res =  getattr(self._object, data['func'], 'error')(data['args'])
            if not 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))

class ThreadedTCPServer(SocketServer.ThreadingMixIn, SocketServer.TCPServer):

pass

class Server(Daemon):

def conf(self, host, port, obj):
    self.host = host
    self.port = port
    self.obj = obj
    ThreadedTCPServer.allow_reuse_address = True
def run(self):
    ThreadedTCPRequestHandler._object = self.obj
    server = ThreadedTCPServer((self.host, self.port), ThreadedTCPRequestHandler)
    server.serve_forever()

if name == '__main__':

server = Server('/tmp/daemon-tortoise.pid')
server.conf('0.0.0.0', 1990, Todo())
if len(sys.argv) == 2:
    if 'start' == sys.argv[1]:
        server.start()
    elif 'stop' == sys.argv[1]:
        server.stop()
    elif 'restart' == sys.argv[1]:
        server.restart()
    else:
        print("Unknown command")
        sys.exit(2)
    sys.exit(0)
else:
    print("usage: %s start|stop|restart" % sys.argv[0])
    sys.exit(2)

Explain that the above code creates a socket server with python and joins the system's daemon. What's the implementation strategy factory in Todo, you know. Usage method:
python sever.py [start|stop|restart]

Then set the system startup item to O.

php calls python through socket
// The files referenced in the code will be given in the attachment, which also gives the concurrent writing of php.
header("Content-type: text/html; charset=utf-8");
require 'socketapi.php';
$s = new server('192.168.1.8', 1990);
$code = <<<EOT
/ Beautify: Format code to make it easy to read/
/ Purification: Remove unnecessary comments, line breaks, spaces, etc. from the code/
/ Compression: Compressing code to a smaller size for easy transmission/
/Decompress: convert the compressed code to a human readable format/

/ If it's useful, please don't forget to recommend it to your friends:/
/ javascript online beautification, purification, compression, decompression: http://box.inote.cc/js /

/ Here is the demo code/

var getPositionLite = function(el) {        var x = 0,        y = 0;        while (el) {            x += el.offsetLeft || 0;            y += el.offsetTop || 0;            el = el.offsetParent        }        return {            x: x,            y: y        }    };

/ Update records:/

var history = {
    'v1.0':    ['2011-01-18','javascript Tool line']
};

EOT;
$res = $s->obj('Todo')->test($code);
echo '<pre>'.$res.'</pre>';

Posted by hyzdufan on Fri, 20 Sep 2019 02:14:41 -0700