python - 如何在 IIS 上为 Python2.7 正确安装 isapi_wsgi?

标签 python iis iis-7 isapi-wsgi

我已经将 Python 作为 CGI 应用程序安装在 Windows 7 的 IIS 上。这非常简单,但我想使用 WSGI 的东西,以获得更好的灵 active 。

我下载了 isapi_wsgi 的存档,解压缩,然后按照 the instructions 运行安装,像这样:

\python27\python.exe setup.py install

这成功了:

enter image description here

然后我编写了一个包含 wsgi 胶水的 .py 模块,并尝试安装它。这失败了:

enter image description here

这是一个 COM Moniker 错误,我知道 IIS6 兼容的管理东西是基于 COM Monikers 的,这让我想起了 IIS6 兼容的管理东西的 isapi_wsgi 的先决条件。我跑了\windows\system32\OptionalFeatures.exe并安装它,然后重新运行 .py 模块并正确安装。

C:\dev\wsgi>\Python27\python.exe app1_wsgi.py
Configured Virtual Directory: /wsgi
Installation complete.

好的,太棒了。现在,当我查看当前目录时,我看到一个名为 _app1_wsgi.dll 的新 DLL,当我查看 IIS 管理器时,我可以看到一个新的 IIS vdir,以及该 vdir 中用于“*”的脚本映射,它映射到_app1_wsgi.DLL。都好。但!向 <a href="http://localhost/wsgi" rel="noreferrer noopener nofollow">http://localhost/wsgi</a> 提出请求给我一个 500 错误。

通过反复试验,我发现定义我的处理程序的 .py 模块必须位于站点包 目录中。我对此感到非常惊讶。

我可以避免这种情况吗?我可以简单地将 .py 模块放在与生成的 .dll 文件相同的目录中吗?或者我是否需要将我所有的 python 逻辑部署到站点包以便从 WSGI 机制运行它?

最佳答案

答案是:

  • 问题中描述的 isapi_wsgi 安装是正确的。

  • 使用 app.py 的基本样板(如 isapi_wsgi 附带的示例代码所示),网络应用程序的 python 类需要位于 site-packages 目录中。

  • 允许 python 源模块与生成的 *.dll 文件位于同一目录中是可能的,但它需要在 *wsgi.py 文件中进行一些特殊处理。

  • 为了开发目的,在 Windows 上运行 python 的更好方法是简单地下载 Google App Engine 并使用内置的专用 http 服务器。 GAE SDK 附带的框架处理重新加载并允许将 .py 模块放置在特定目录中。


如果您不想下载和安装 GAE SDK,那么您可以尝试以下操作。使用此代码,当请求到达 isapi_wsgi 时,处理程序会在主目录中查找 py 模块并加载它。如果模块已经加载,它会检查文件“最后修改时间”,如果最后修改时间晚于上次加载的时间,则重新加载模块。它适用于简单的情况,但我想当有嵌套的模块依赖关系时它会很脆弱。

import sys
import os
import win32file
from win32con import *

# dictionary of [mtime, module] tuple;  uses file path as key
loadedPages = {}

def request_handler(env, start_response):
    '''Demo app from wsgiref'''
    cr = lambda s='': s + '\n'
    if hasattr(sys, "isapidllhandle"):
        h = None
        # get the path of the ISAPI Extension DLL
        hDll = getattr(sys, "isapidllhandle", None)
        import win32api
        dllName = win32api.GetModuleFileName(hDll)
        p1 = repr(dllName).split('?\\\\')
        p2 = p1[1].split('\\\\')
        sep = '\\'
        homedir = sep.join(p2[:-1])

        # the name of the Python module is in the PATH_INFO
        moduleToImport = env['PATH_INFO'].split('/')[1]

        pyFile = homedir + sep + moduleToImport + '.py'

        fd = None
        try:
            fd = win32file.CreateFile(pyFile, GENERIC_READ, FILE_SHARE_DELETE, None, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0)
        except Exception as exc1:
            fd = None

        if fd is not None:
            # file exists, get mtime
            fd.close()
            mt = os.path.getmtime(pyFile)
        else:
            mt = None


        if mt is not None:
            h = None
            if not pyFile in loadedPages:
                # need a new import
                if homedir not in sys.path:
                    sys.path.insert(0, homedir)

                h = __import__(moduleToImport, globals(), locals(), [])
                # remember
                loadedPages[pyFile] = [mt, h]
            else:
                # retrieve handle to module
                h = loadedPages[pyFile][1]
                if mt != loadedPages[pyFile][0]:
                    # need to reload the page
                    reload(h)
                    loadedPages[pyFile][0] = mt

            if h is not None:
                if 'handler' in h.__dict__:
                    for x in h.handler(env, start_response):
                        yield x
                else:
                    start_response("400 Bad Request", [('Content-Type', 'text/html')])
            else:
                start_response("404 Not Found", [('Content-Type', 'text/html')])
                yield cr()
                yield cr("<html><head><title>Module not found</title>" \
                             "</head><body>")
                yield cr("<h3>404 Not Found</h3>")
                yield cr("<h3>No handle</h3></body></html>")

        else:
            start_response("404 Not Found", [('Content-Type', 'text/html')])
            yield cr()
            yield cr("<html><head><title>Module not found</title>" \
                 "</head><body>")
            yield cr("<h3>404 Not Found</h3>")
            yield cr("<h3>That module (" + moduleToImport + ") was not found.</h3></body></html>")


    else:
        start_response("500 Internal Server Error", [('Content-Type', 'text/html')])
        yield cr()
        yield cr("<html><head><title>Server Error</title>" \
                 "</head><body><h1>Server Error - No ISAPI Found</h1></body></html>")


# def test(environ, start_response):
#     '''Simple app as per PEP 333'''
#     status = '200 OK'
#     start_response(status, [('Content-type', 'text/plain')])
#     return ['Hello world from isapi!']


import isapi_wsgi
# The entry point(s) for the ISAPI extension.
def __ExtensionFactory__():
    return isapi_wsgi.ISAPISimpleHandler(request_handler)


def PostInstall(params, options):
    print "The Extension has been installed"


# Handler for our custom 'status' argument.
def status_handler(options, log, arg):
    "Query the status of the ISAPI?"
    print "Everything seems to be fine..."


if __name__=='__main__':
    # This logic gets invoked when the script is run from the command-line.
    # In that case, it installs this module as an ISAPI.

    #
    # The API provided by isapi_wsgi for this is a bit confusing.  There
    # is an ISAPIParameters object. Within that object there is a
    # VirtualDirs property, which itself is a list of
    # VirtualDirParameters objects, one per vdir.  Each vdir has a set
    # of scriptmaps, usually this set of script maps will be a wildcard
    # (*) so that all URLs in the vdir will be served through the ISAPI.
    #
    # To configure a single vdir to serve Python scripts through an
    # ISAPI, create a scriptmap, and stuff it into the
    # VirtualDirParameters object. Specify the vdir path and other
    # things in the VirtualDirParameters object.  Stuff that vdp object
    # into a sequence and set it into the ISAPIParameters thing, then
    # call the vaguely named "HandleCommandLine" function, passing that
    # ISAPIParameters thing.
    #
    # Clear as mud?
    #
    # Seriously, this thing could be so much simpler, if it had
    # reasonable defaults and a reasonable model, but I guess it will
    # work as is.

    from isapi.install import *

    # Setup the virtual directories -
    # To serve from root, set Name="/"
    sm = [ ScriptMapParams(Extension="*", Flags=0) ]
    vdp = VirtualDirParameters(Name="wsgi", # name of vdir/IIS app
                              Description = "ISAPI-WSGI Demo",
                              ScriptMaps = sm,
                              ScriptMapUpdate = "replace"
                              )

    params = ISAPIParameters(PostInstall = PostInstall)
    params.VirtualDirs = [vdp]
    cah = {"status": status_handler}

    # from isapi.install, part of pywin32
    HandleCommandLine(params, custom_arg_handlers = cah)

使用此模型,请求 http://foo/wsgi/bar将尝试使用 WSGI .dll 文件从主目录加载 bar.py。如果找不到 bar.py,您会收到 404。如果 bar.py 自上次运行以来已更新,则会重新加载。如果无法加载 bar,您将获得 500。

bar.py 必须公开导出一个名为 handler 的方法。该方法必须是生成器。像这样:

import time

def handler(env, start_response):
    start_response("200 OK", [('Content-Type', 'text/html')])
    cr = lambda s='': s + '\n'
    yield cr("<html><head><title>Hello world!</title></head><body>")
    yield cr("<h1>Bargle Bargle Bargle</h1>")
    yield cr("<p>From the handler...</p>")
    yield cr("<p>(bargle)</p>")
    yield cr("<p>The time is now: " + time.asctime() + " </p>")
    yield cr("</body></html>")

__all__ = ['handler']

但正如我所说,我认为 GAE 可能是使用 Windows 开发 Python 网络应用程序的更好方法。

关于python - 如何在 IIS 上为 Python2.7 正确安装 isapi_wsgi?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9754511/

相关文章:

Python - 在追加模式下打开文件。写永远不会发生

iphone - 在 iPhone、BlackBerry、Android、WP7 上访问基于 SSL 的网站

asp.net - IIS 服务器内存不足会导致 SQL 超时(SQL Server 在单独的机器上)吗?

node.js iisnode https 500 HRESULT 0x6d 子状态 1013

windows - IIS 无法访问文件,但通过同一帐户登录的用户可以

visual-studio - VS2008,IIS7 Web项目,非管理员。什么时候?

python - 重载 unittest.testcase 的 __init__

python - Jupyter 笔记本不再在外部窗口中打开 matplotlib 图?

iis-7 - WebApi 的 {"message":"an error has occurred"} 在 IIS7 上,不在 IIS Express 中

python - 从数据框中删除顶行