简体   繁体   English

如何通过使用WSGI来执行Python脚本来避免PHP exec()?

[英]How to avoid PHP exec() by using WSGI to execute a Python script?

Right now I am launching a Python script from PHP using exec() as I have to pass some dynamic variables from the website/MySQL to the command line. 现在我正在使用exec()从PHP启动Python脚本,因为我必须将一些动态变量从网站/ MySQL传递到命令行。 However, I would like to improve both the speed and the security of this operation so I thought of using WSGI. 但是,我想提高此操作的速度和安全性,所以我想使用WSGI。 I was thinking that it might be possible to embed the Python script in a WSGI file, which would use the variables passed directly (or indirectly) from PHP...but how could I do this? 我认为可以将Python脚本嵌入到WSGI文件中,该文件将使用从PHP直接(或间接)传递的变量...但是我怎么能这样做呢? I have never used WSGI so I don't even know if this is a stupid question or not :) 我从未使用过WSGI,所以我甚至都不知道这是不是一个愚蠢的问题:)

First off, can you do it all in either Python or PHP? 首先,你能用Python或PHP做到这一切吗? Using multiple languages is normally seen as an anti-pattern. 使用多种语言通常被视为反模式。 That's not to say it's always a bad idea, but you should be questioning why first, and only then if you're convinced it's a good idea move forward. 这并不是说这总是一个坏主意,但你应该首先质疑为什么,只有这样你才能确信这是一个好主意。

As far as the specifics of what you want to do, there are a few options: 至于你想做什么的具体细节,有几个选择:

  1. If using Apache, you can use the virtual() function to issue a new request through Apache. 如果使用Apache,则可以使用virtual()函数通过Apache发出新请求。

    This is assuming that you are using mod_php and mod_wsgi. 这假设您使用的是mod_php和mod_wsgi。 Basically, you'd build up a query string for the variables you want to pass, and call it like: 基本上,您要为要传递的变量构建查询字符串,并将其称为:

     virtual('path/to/python.py?'.$query); 
  2. Write your own PHP WSGI gateway. 编写自己的PHP WSGI网关。

    Bascially, code the WSGI spec into a library, and call it explicitly from within PHP. 基本上,将WSGI规范编码到库中,并在PHP中显式调用它。

  3. Stick to calling it from exec() (which will likely be the best option for now). 坚持从exec()调用它(这可能是目前最好的选择)。

The thing that you have to consider is that there's overhead inherent to cross-including between languages. 你需要考虑的是,语言之间的交叉包含固有的开销。 You'll never get over that, it's just the nature of the beast. 你永远不会克服它,这只是野兽的本性。 So instead, I'd suggest keeping the entire request inside of one environment, and dealing with it in the entirety in that environment... 所以相反,我建议将整个请求保留在一个环境中,并在该环境中完整地处理它...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM