為 IIS 設定 Python Web 應用程式Configure Python web apps for IIS

在 Windows 電腦 (包括 Azure 上的 Windows 虛擬機器) 上使用 Internet Information Services (IIS) 作為網頁伺服器時,Python 應用程式必須在其 web.config 檔案中包含特定設定,IIS 才能正確地處理 Python 程式碼。When using Internet Information Services (IIS) as a web server on a Windows computer (including Windows virtual machines on Azure, Python apps must include specific settings in their web.config files so that IIS can properly process Python code. 電腦本身也必須安裝 Python,以及 Web 應用程式需要的所有套件。The computer itself must also have Python installed along with any packages the web app requires.

注意

此文章之前曾包含在 Windows 上的 Azure App Service 上設定 Python 的指導方針。This article previously contained guidance for configuring Python on Azure App Service on Windows. 但是在該案例中使用的 Python 延伸模組和 Windows 主機,已被 Linux 上的 Azure App Service 取代。The Python extensions and Windows hosts used in that scenario have been deprecated in favor of Azure App Service on Linux. 如需詳細資訊,請參閱發行 Python 應用程式至 Azure App Service (Linux)For more information, see Publishing Python Apps to Azure App Service (Linux). 不過您還是可以在使用 Python 延伸模組管理 Windows 上的 App Service找到之前的文章。The previous article, however, is still available on Managing App Service on Windows with the Python extensions.

在 Windows 上安裝 PythonInstall Python on Windows

若要執行 Web 應用程式,請先依照安裝 Python 解譯器所述,直接在 Windows 主機電腦上安裝您所需的 Python 版本。To run a web app, first install your required version of Python directly on the Windows host machine as described on Install Python interpreters.

記錄 python.exe 解譯器的位置供後續步驟使用。Record the location of the python.exe interpreter for later steps. 為了方便起見,您可以將該位置新增到您的 PATH 環境變數。For convenience, you can add that location to your PATH environment variable.

安裝套件Install packages

使用專用主機時,您可以使用全域 Python 環境而不是虛擬環境來執行您的應用程式。When using a dedicated host, you can use the global Python environment to run your app rather than a virtual environment. 因此,您可以在命令提示字元執行 pip install -r requirements.txt,將應用程式的所有需求安裝到全域環境。Accordingly, you can install all of your app's requirements into the global environment simply by running pip install -r requirements.txt at a command prompt.

將 web.config 設定為指向 Python 解譯器Set web.config to point to the Python interpreter

您應用程式的 web.config 檔案會指示在 Windows 上執行的 IIS (7+) 網頁伺服器應如何透過 HttpPlatform (建議使用) 或 FastCGI 來處理 Python 要求。Your app's web.config file instructs the IIS (7+) web server running on Windows about how it should handle Python requests through either HttpPlatform (recommended) or FastCGI. Visual Studio 2015 和更早版本會自動進行這些修改。Visual Studio versions 2015 and earlier make these modifications automatically. 使用 Visual Studio 2017 和更新版本時,您必須手動修改 web.configWhen using Visual Studio 2017 and later, you must modify web.config manually.

設定 HTTP 平台處理常式Configure the HttpPlatform handler

HTTP 平台處理常式模組會將通訊端連線直接傳遞給獨立的 Python 處理序。The HttpPlatform module passes socket connections directly to a standalone Python process. 這個傳遞可讓您執行任何喜歡的網頁伺服器,但需要執行本機網頁伺服器的啟動指令碼。This pass-through allows you to run any web server you like, but requires a startup script that runs a local web server. 您可以在 web.config<httpPlatform> 元素中指定指令碼,其中 processPath 屬性指向網站延伸模組的 Python 解譯器,而 arguments 屬性則指向您的指令碼以及您想要提供的任何引數:You specify the script in the <httpPlatform> element of web.config, where the processPath attribute points to the site extension's Python interpreter and the arguments attribute points to your script and any arguments you want to provide:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <system.webServer>
    <handlers>
      <add name="PythonHandler" path="*" verb="*" modules="httpPlatformHandler" resourceType="Unspecified"/>
    </handlers>
    <httpPlatform processPath="c:\python36-32\python.exe"
                  arguments="c:\home\site\wwwroot\runserver.py --port %HTTP_PLATFORM_PORT%"
                  stdoutLogEnabled="true"
                  stdoutLogFile="c:\home\LogFiles\python.log"
                  startupTimeLimit="60"
                  processesPerApplication="16">
      <environmentVariables>
        <environmentVariable name="SERVER_PORT" value="%HTTP_PLATFORM_PORT%" />
      </environmentVariables>
    </httpPlatform>
  </system.webServer>
</configuration>

此處所顯示的 HTTP_PLATFORM_PORT 環境變數包含本機伺服器應該接聽 localhost 連線的連接埠。The HTTP_PLATFORM_PORT environment variable shown here contains the port that your local server should listen on for connections from localhost. 此範例也會示範如何建立另一個環境變數 (如有需要),在此情況下,是 SERVER_PORTThis example also shows how to create another environment variable, if desired, in this case SERVER_PORT.

設定 FastCGI 處理常式Configure the FastCGI handler

FastCGI 是一種在要求層級運作的介面。FastCGI is an interface that works at the request level. IIS 會接收連入連線並將每個要求轉送至在一或多個持續性 Python 程序中執行的 WSGI 應用程式。IIS receives incoming connections and forwards each request to a WSGI app running in one or more persistent Python processes.

若要使用它,請先依照 pypi.org/project/wfastcgi/ 所述安裝並設定 wfastcgi 套件。To use it, first install and configure the wfastcgi package as described on pypi.org/project/wfastcgi/.

接下來,修改應用程式的 web.config 檔案放入 python.exe 的完整路徑,並在 PythonHandler 機碼中放入 wfastcgi.pyNext, modify your app's web.config file to include the full paths to python.exe and wfastcgi.py in the PythonHandler key. 下列步驟假設已在 c:\python36-32 安裝 Python,而且您的應用程式程式碼位於 c:\home\site\wwwroot 中,請相應調整您的路徑:The steps below assume that Python is installed in c:\python36-32 and that your app code is in c:\home\site\wwwroot; adjust for your paths accordingly:

  1. 修改 web.config 中的 PythonHandler 項目,使路徑符合 Python 安裝位置 (如需詳細資料,請參閱 IIS 設定參考 (英文) (iis.net))。Modify the PythonHandler entry in web.config so that the path matches the Python install location (see IIS Configuration Reference (iis.net) for exact details).

    <system.webServer>
      <handlers>
        <add name="PythonHandler" path="*" verb="*" modules="FastCgiModule"
            scriptProcessor="c:\python36-32\python.exe|c:\python36-32\wfastcgi.py"
            resourceType="Unspecified" requireAccess="Script"/>
      </handlers>
    </system.webServer>
    
  2. <appSettings> web.config的區段內,新增的索引鍵 WSGI_HANDLERWSGI_LOG (選擇性的) 以及 PYTHONPATHWithin the <appSettings> section of web.config, add keys for WSGI_HANDLER, WSGI_LOG (optional), and PYTHONPATH:

    <appSettings>
      <add key="PYTHONPATH" value="c:\home\site\wwwroot"/>
      <!-- The handler here is specific to Bottle; see the next section. -->
      <add key="WSGI_HANDLER" value="app.wsgi_app()"/>
      <add key="WSGI_LOG" value="c:\home\LogFiles\wfastcgi.log"/>
    </appSettings>
    

    這些 <appSettings> 值是以環境變數形式提供給您的應用程式:These <appSettings> values are available to your app as environment variables:

    • PYTHONPATH 的值可以自由擴充,但必須包含應用程式的根目錄。The value for PYTHONPATH may be freely extended but must include the root of your app.
    • WSGI_HANDLER 必須指向可從應用程式匯入的 WSGI 應用程式。WSGI_HANDLER must point to a WSGI app importable from your app.
    • WSGI_LOG 是選擇性的,但建議用於偵錯應用程式。WSGI_LOG is optional but recommended for debugging your app.
  3. 依據您使用的架構,妥善設定 web.config 中的 WSGI_HANDLER 項目:Set the WSGI_HANDLER entry in web.config as appropriate for the framework you're using:

    • Bottle:務必在 app.wsgi_app 後面加上括弧,如下所示。Bottle: make sure that you have parentheses after app.wsgi_app as shown below. 這是必要的步驟,因為該物件是函式 (請參閱 app.py) 而不是變數:This is necessary because that object is a function (see app.py) rather than a variable:

      <!-- Bottle apps only -->
      <add key="WSGI_HANDLER" value="app.wsgi_app()"/>
      
    • Flask:將 WSGI_HANDLER 值變更為 <project_name>.app,其中 <project_name> 應符合您的專案名稱。Flask: Change the WSGI_HANDLER value to <project_name>.app where <project_name> matches the name of your project. 您可以查看 runserver.py 中的 from <project_name> import app 陳述式,以找出確切的識別項。You can find the exact identifier by looking at the from <project_name> import app statement in the runserver.py. 比方說,如果專案的名稱為 "FlaskAzurePublishExample",項目會顯示如下:For example, if the project is named "FlaskAzurePublishExample", the entry would appear as follows:

      <!-- Flask apps only: change the project name to match your app -->
      <add key="WSGI_HANDLER" value="flask_iis_example.app"/>
      
    • Django:Django 專案需要對 web.config 進行兩個變更。Django: Two changes are needed to web.config for Django projects. 第一,將 WSGI_HANDLER 值變更為 django.core.wsgi.get_wsgi_application() (此物件位於 wsgi.py 檔案中):First, change the WSGI_HANDLER value to django.core.wsgi.get_wsgi_application() (the object is in the wsgi.py file):

      <!-- Django apps only -->
      <add key="WSGI_HANDLER" value="django.core.wsgi.get_wsgi_application()"/>
      

      第二,將下列項目新增至 WSGI_HANDLER 底下的項目,並將 DjangoAzurePublishExample 取代為您的專案名稱:Second, add the following entry below the one for WSGI_HANDLER, replacing DjangoAzurePublishExample with the name of your project:

      <add key="DJANGO_SETTINGS_MODULE" value="django_iis_example.settings" />
      
  4. 僅 Django 應用程式:在 Django 專案的 settings.py 檔案中,將您的網站 URL 網域或 IP 位址新增至 ALLOWED_HOSTS (如下所示),並使用您的 URL 或 IP 位址取代 '1.2.3.4':Django apps only: In the Django project's settings.py file, add your site URL domain or IP address to ALLOWED_HOSTS as shown below, replacing '1.2.3.4' with your URL or IP address, of course:

    # Change the URL or IP address to your specific site
    ALLOWED_HOSTS = ['1.2.3.4']
    

    若無法將 URL 新增至陣列,會導致錯誤 DisallowedHost 為/無效 HTTP_HOST 標頭: ' <site URL> '。您可能需要將 ' <site URL> ' 新增至 ALLOWED_HOSTS。Failure to add your URL to the array results in the error DisallowedHost at / Invalid HTTP_HOST header: '<site URL>'. You may need to add '<site URL>' to ALLOWED_HOSTS.

    請注意,當陣列為空時,Django 會自動允許 'localhost' 和 '127.0.0.1',但新增您的生產環境 URL 將會移除這些功能。Note that when the array is empty, Django automatically allows 'localhost' and '127.0.0.1', but adding your production URL removes those capabilities. 基於此原因,您可能會想要個別維護 settings.py 的開發和生產版本,或使用環境變數來控制執行階段值。For this reason you might want to maintain separate development and production copies of settings.py, or use environment variables to control the run time values.

部署至 IIS 或 Windows VMDeploy to IIS or a Windows VM

如果在專案中使用正確的 web.config 檔案,您就可以在 [方案總管]**** 中,使用專案操作功能表上的 [發佈]**** 命令,然後選取選項 IIS、FTP 等,發佈至執行 IIS 的電腦。With the correct web.config file in your project, you can publish to the computer running IIS by using the Publish command on the project's context menu in Solution Explorer, and selecting the option, IIS, FTP, etc.. 在此案例中,Visual Studio 只會將專案檔案複製到伺服器,您要負責所有伺服器端設定。In this case, Visual Studio simply copies the project files to the server; you're responsible for all server-side configuration.