Python twisted 渲染 PHP

3 投票
1 回答
1607 浏览
提问于 2025-04-17 13:46

在用Python的Twisted框架搭建的网页服务器上,可以运行PHP页面吗?

从文档上看,好像是可以的:http://twistedmatrix.com/documents/current/api/twisted.web.twcgi.CGIScript.html

我在这一步卡住了,怎么才能渲染这些文件呢?

    class service(resource.Resource):
def getChild(self, name, request):
    self._path = request.prepath[:]
                # Is this an php
    elif request.prepath[0] == 'php':
        return _ShowPHP

    elif (len(self._path) != 1):
        _ServiceError.SetErrorMsg('Invalid path in URL: %s' % self._path)
        return _ServiceError

ShowPHP:

class ShowPHP(resource.Resource):

isLeaf = True   # This is a resource end point.
def render(self, request):
  #return "Hello, world! I am located at %r." % (request.prepath,)

  class PythScript(twcgi.FilteredScript):
    filter="/usr/bin/php"
    resource = static.File("php") # Points to the perl website
    resource.processors = {".php": ShowPHP} # Files that end with .php
    resource.indexNames = ['index.php']


############################################################
_ShowPHP = ShowPHP()

但是当我在浏览器中打开PHP页面时,出现了这个错误:请求没有返回字符串。

请求:

    <GET /php/index.php HTTP/1.1>

资源:

      <service.ShowPHP instance at 0x2943878>

值:

1 个回答

2

在我的电脑上,必须使用 php-cgi 而不是普通的 php 作为可执行文件。两者的区别在于,使用 php-cgi 时,解释器会确保它发送正确的头信息,以便形成一个合适的 CGI 响应:

from twisted.internet import reactor
from twisted.web.server import Site

from twisted.web.twcgi import FilteredScript

class PhpPage(FilteredScript):
    filter = "/usr/bin/php-cgi"
    #                  ^^^^^^^

    # deal with cgi.force_redirect parameter by setting it to nothing.
    # you could change your php.ini, too.
    def runProcess(self, env, request, qargs=[]):
        env['REDIRECT_STATUS'] = ''
        return FilteredScript.runProcess(self, env, request, qargs)

resource = PhpPage('./hello.php')
factory = Site(resource)

reactor.listenTCP(8880, factory)
reactor.run()

撰写回答