Error occurred while reading wsgi handler traceback most recent call last

Very related to this post but I don't have the priviledge to comment there so I had to make a new post. Deploy a simple VS2017 Django app to Azure - server error I followed Silencer's tutorial the...

Very related to this post but I don’t have the priviledge to comment there so I had to make a new post. Deploy a simple VS2017 Django app to Azure — server error

I followed Silencer’s tutorial there and I am getting this error from LogFileswfastcgi.log:

2017-07-28 08:28:57.746719: Activating virtualenv with D:homesitewwwrootenvScriptspython.exe
2017-07-28 08:28:57.777987: Error occurred while reading WSGI handler:

Traceback (most recent call last):
  File "D:homepython360x64wfastcgi.py", line 791, in main
    env, handler = read_wsgi_handler(response.physical_path)
  File "D:homepython360x64wfastcgi.py", line 633, in read_wsgi_handler
    handler = get_wsgi_handler(os.getenv("WSGI_HANDLER"))
  File "D:homepython360x64wfastcgi.py", line 605, in get_wsgi_handler
    handler = handler()
  File ".ptvs_virtualenv_proxy.py", line 99, in get_virtualenv_handler
    execfile(activate_this, dict(__file__=activate_this))
  File ".ptvs_virtualenv_proxy.py", line 27, in execfile
    code = f.read()
  File "D:Reposazure-python-siteextensionssource_packagespython.3.6.0toolsLibencodingscp1252.py", line 23, in decode
UnicodeDecodeError: 'charmap' codec can't decode byte 0x90 in position 2: character maps to <undefined>

I have installed python360x64 as an extension in azure portal, I am using this https://github.com/Azure/azure-sdk-for-python/blob/master/examples/AzureResourceViewer/ptvs_virtualenv_proxy.py
And my web.config:

<configuration>
  <system.diagnostics>
    <trace>
      <listeners>
        <add type="Microsoft.WindowsAzure.Diagnostics.DiagnosticMonitorTraceListener, Microsoft.WindowsAzure.Diagnostics, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" name="AzureDiagnostics">
          <filter type="" />
        </add>
      </listeners>
    </trace>
  </system.diagnostics>
  <appSettings>
    <add key="WSGI_ALT_VIRTUALENV_HANDLER" value="django.core.wsgi.get_wsgi_application()" />
    <add key="WSGI_ALT_VIRTUALENV_ACTIVATE_THIS" value="D:homesitewwwrootenvScriptspython.exe" />
    <add key="WSGI_HANDLER" value="ptvs_virtualenv_proxy.get_virtualenv_handler()" />
    <add key="PYTHONPATH" value="D:homesitewwwroot" />
    <add key="DJANGO_SETTINGS_MODULE" value="DjangoWebProject.settings" />
    <add key="WSGI_LOG" value="D:homeLogFileswfastcgi.log"/>
  </appSettings>
  <system.web>
    <compilation debug="true" targetFramework="4.0" />
  </system.web>
  <system.webServer>
    <modules runAllManagedModulesForAllRequests="true" />
    <handlers>
      <add name="Python FastCGI" path="handler.fcgi" verb="*" modules="FastCgiModule" scriptProcessor="D:homepython360x64python.exe|D:homepython360x64wfastcgi.py" resourceType="Unspecified" requireAccess="Script" />
    </handlers>
    <rewrite>
      <rules>
        <rule name="Static Files" stopProcessing="true">
          <conditions>
            <add input="true" pattern="false" />
          </conditions>
        </rule>
        <rule name="Configure Python" stopProcessing="true">
          <match url="(.*)" ignoreCase="false" />
          <conditions>
            <add input="{REQUEST_URI}" pattern="^/static/.*" ignoreCase="true" negate="true" />
          </conditions>
          <action type="Rewrite" url="handler.fcgi/{R:1}" appendQueryString="true" />
        </rule>
      </rules>
    </rewrite>
  </system.webServer>
</configuration>

My /env/ python version is python360x64.
Any help appreciated!

Я настраивал все пути в файле web.config и настраивал все в IIS (на Windows Server 2012 R2). Когда я закончил, я запустил сервер и получил доступ к веб-сайту. Но при этом я получил следующее сообщение об ошибке:

Error occurred while reading WSGI handler:

Traceback (most recent call last):
  File "C:inetpubwwwrootdjangoappwfastcgi.py", line 711, in main
    env, handler = read_wsgi_handler(response.physical_path)
  File "C:inetpubwwwrootdjangoappwfastcgi.py", line 568, in read_wsgi_handler
    return env, get_wsgi_handler(handler_name)
  File "C:inetpubwwwrootdjangoappwfastcgi.py", line 551, in get_wsgi_handler
    raise ValueError('"%s" could not be imported' % handler_name)
ValueError: "django.core.wsgi.get_wsgi_application()" could not be imported


StdOut: 

StdErr:

Web.config (файл):

 <?xml version="1.0" encoding="UTF-8"?>
<configuration>
<system.webServer>
<handlers>
<add name="Python FastCGI"
path="*"
verb="*"
modules="FastCgiModule"
scriptProcessor="C:Python34python.exe|C:inetpubwwwrootdjangoappwfastcgi.py"
resourceType="Unspecified"
requireAccess="Script" />
</handlers>
</system.webServer>

<appSettings>
<add key="WSGI_HANDLER" value="django.core.wsgi.get_wsgi_application()" />
<add key="PYTHONPATH" value="C:Python34python.exe" />
<add key="WSGI_RESTART_FILE_REGEX" value=".*((.py)|(.config))$" />
<add key="DJANGO_SETTINGS_MODULE" value="djangoapp.settings" />
</appSettings>
</configuration>

Я не понимаю, почему эта ошибка возникает. Кто-нибудь знает, как это решить или помочь.

Спасибо за прочтение.

02 май 2017, в 22:02

Поделиться

Источник

2 ответа

Я вижу эту проблему много в Интернете. Проблема в том, что у вас есть две версии Python на вашем компьютере. Убедитесь, что у вас все установлено для обеих версий. Например, Python версии 3.4: py -m pip install django и для Python версии 3.6: просто выберите pip install django соответствии с вашими переменными среды, конечно. Убедитесь, что все загружено в порядке. Также обратите внимание, что для обеих версий вам необходимо также ввести эти команды, чтобы они работали: для версии 3.6 (в моем случае):

pip install --upgrade wheel
pip install wfastcgi
wfastcgi-enable

А для версии 3.4 (в моем случае):

py -m pip install --upgrade wheel
py -m pip install wfastcgi
wfastcgi-enable

Обратите внимание, что обе версии имеют свой собственный wfastcgi.

Надеюсь, это поможет, он решил мою проблему.

Bedirhan
02 май 2017, в 19:48

Поделиться

Вот разница между нами. Надеюсь это поможет.

<add key="WSGI_HANDLER" value="django.core.handlers.wsgi.WSGIHandler()" />
<add key="PYTHONPATH" value="[PATH_OF_DJANGOAPP]" />

Boyi
21 июнь 2017, в 09:27

Поделиться

Ещё вопросы

  • 1Как отформатировать код Java в редакторе Ace
  • 0CSS-контент / боковые панели следуют фону
  • 1Почему я не могу получить доступ к дочерним объектам в моем BindingSource в диалоге Advanced Binding
  • 1Пользовательский тег не работает должным образом
  • 0HTML выбор тега по умолчанию показывает пустым на IE10
  • 0Как посеять большие наборы данных быстрее в Laravel, используя фейкер
  • 0PHP добавить уникальный идентификатор в SQL
  • 1Установите вызов Moq для защищенного виртуального метода, который ожидает Func и возвращает IEnumerable
  • 0загрузить JQuery во внешний файл JavaScript
  • 1Можно ли повторно использовать токен Facebook OAuth для открытия страницы Facebook в браузере?
  • 0Серые блоки на фоновом изображении [дубликаты]
  • 0Recaptcha больше не работает после обновления до версии стиля флажка
  • 1com.google.gson.JsonParseException: Не удалось проанализировать JSON-источник: java.io.BufferedReader to Json — озадачен этой проблемой
  • 1Прослушивание, когда жест происходит на конкретном объекте на экране
  • 0Как скрыть / показать числовые идентификаторы от простого вызова функции (js / jQuery)
  • 1VueJs 2 скрыть и показать DIV на одной HTML-странице
  • 1Ошибка построения панд TypeError: Пусто ‘DataFrame’: нет числовых данных для построения графика
  • 0Должен ли я использовать JRE или JDK в Eclipse для разработки PHP?
  • 1LINQ OrderBy с несколькими слоями
  • 0Разработка конвертера Word в PDF с нуля без использования сторонних инструментов
  • 0Как связать файлы в приложении?
  • 0цвет шрифта на панели инструментов
  • 1Избегайте выполнения блоков встроенного кода в ASP.NET
  • 1Получение ConnectionProvider из SessionFactory
  • 1Моя страница JSP не перенаправляет на Myservlet, используя форму
  • 0Шаблоны Meteor AngularJS (модульное тестирование)
  • 1Почему приложение C # не создает файл при запуске из планировщика задач Windows?
  • 0Получить несколько строк в MySQL одного запроса в PHP с другим идентификатором
  • 1Android Несколько анимаций
  • 0Foreach возвращает один элемент многим
  • 0Почему деструктор не вызывается для массива объектов?
  • 1SAX разбор в андроиде
  • 0Данные формы не отправляются для последующей обработки PHP
  • 1Делаем конкретный текст жирным шрифтом в строке в C # Windows Forms
  • 1прекратить следующее действие, если нажата домашняя клавиша или нажатие назад — Android
  • 0ng-show, переключение правого элемента при нажатии [Angularjs]
  • 0Как написать шаблон электронной почты в angularjs для определенного списка доменов
  • 0Очистка хеш-таблицы в C ++
  • 0Какова цель helper.basepath в угловом интерфейсе?
  • 0Нужна помощь в отладке исключений bad_alloc и out_of_range
  • 1Google API Uncaught исключение при использовании gapi.load
  • 1Android ==> Разработка приложений?
  • 0Ввод ключа пропускает проверки angularJS
  • 0Возможность перетаскивания в области прокрутки с помощью jQueryUI
  • 1Python: преобразование необработанной строки в строку байтов без добавления escape-символов
  • 1Android — нужен ли элемент <using-feature>?
  • 0CArray: невозможно назначить переменную, возвращаемую CArray, нереферентной переменной
  • 0Как заставить Windows Bluetooth Connect () вызвать тайм-аут
  • 0Прочитать файл JSCON с помощью PHP
  • 0Выровняйте ячейки таблицы слева

Сообщество Overcoder

  • Remove From My Forums
  • Question

  • I have a created an out of the box Python application using Flask from the Visual Tools for Python.

    When I deploy the application to my Azure website I got errors like this.

    Error occurred while reading WSGI handler: Traceback (most recent call last):
    File «D:Python27Scriptswfastcgi.py», line 711, in main env, handler =

    read_wsgi_handler(response.physical_path) File
    «D:Python27Scriptswfastcgi.py», line 568, in read_wsgi_handler return env,

    get_wsgi_handler(handler_name) File «D:Python27Scriptswfastcgi.py», line 551,

    in get_wsgi_handler raise ValueError(‘»%s» could not be imported’ %
    handler_name) ValueError: «TestFlask.app» could not be imported StdOut: StdErr:

    How should I deploy the application and it work?

    Thanks,

    Joshua

Answers

  • I don’t think that permissions locally affect what is deployed. I found a working around using the web role and installing Python with Web Platform Installer.

    Please look at fixing the Flask website and Flask web role so those work out of the box.

    Thanks,

    Joshua

    • Marked as answer by

      Tuesday, December 2, 2014 11:44 AM

    • Marked as answer by
      Will ShaoMicrosoft employee
      Monday, December 8, 2014 8:41 AM

There are already a lot of resources dealing with how to setup Django with IIS, or configure IIS to support WSGI with various tools such as Helicon Zoo, isapi-wsgi, and FastCGI.

FastCGI looked good among others because I wanted to go with least 3rd party stack and the Microsoft distribute the wfastcgi.py through PTVS. However, there’s a still one problem. I couldn’t find the document explains how to set up a local IIS to work with FastCGI and Flask.

Thanks to PTVS, it’s already well implemented and provided. The PTVS contains the wfastcgi.py, and web.config which set required environments to run. Here’s more detailed step:

1. Install wfastcgi.py. The PTVS official homepage has the link to download wfastcgi.py MSI installer.

http://pytools.codeplex.com/downloads/get/920481

wfastcgi

The wfastcgi MSI installer creates local copies of wfastcgi.py to python installed directory as below:

wfastcgi-installed

2. Install FastCGI to IIS and add wfastcgi.py handler to it. The official PTVS page has the required command to ease the steps here:

http://pytools.codeplex.com/wikipage?title=wfastcgi

start /wait %windir%System32\PkgMgr.exe /iu:IIS-CGI

%windir%system32inetsrvappcmd set config /section:system.webServer/fastCGI “/+[fullPath=’c:Python27python.exe’, arguments=’C:Python27Scriptswfastcgi.py’]”

The wfastcgi.py MSI installer also seems to add the handlers above automatically if FastCGI is already configured, but it’s not sure. You can now see the FastCGI listed installed Python paths.

fastcgi

3. Now it’s time to edit the web.config for Flask/IIS. If you created the Flask project with PTVS addon, it already contains the required web.config to support deploy to Azure. However, in order to run it on local IIS, it needs a little modification. Let’s see the original web.config first PTVS generated.

<?xml version=”1.0″?>
<!– Generated web.config for Microsoft Azure. Remove this comment to prevent
modifications being overwritten when publishing the project.
–>
<configuration>
<system.diagnostics>
<trace>
<listeners>
<add type=”Microsoft.WindowsAzure.Diagnostics.DiagnosticMonitorTraceListener, Microsoft.WindowsAzure.Diagnostics, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35″ name=”AzureDiagnostics”>
<filter type=”” />
</add>
</listeners>
</trace>
</system.diagnostics>
<appSettings>
<add key=”WSGI_ALT_VIRTUALENV_HANDLER” value=”FlaskWebProject1.app” />
<add key=”WSGI_ALT_VIRTUALENV_ACTIVATE_THIS” value=”%ROOTDIR%envScriptsactivate_this.py” />
<add key=”WSGI_HANDLER” value=”ptvs_virtualenv_proxy.get_virtualenv_handler()” />
<add key=”PYTHONPATH” value=”%ROOTDIR%” />
</appSettings>
<system.web>
<compilation debug=”true” targetFramework=”4.0″ />
</system.web>
<system.webServer>
<modules runAllManagedModulesForAllRequests=”true” />
<handlers>
<add name=”Python FastCGI” path=”handler.fcgi” verb=”*” modules=”FastCgiModule” scriptProcessor=”%INTERPRETERPATH%|%WFASTCGIPATH%” resourceType=”Unspecified” requireAccess=”Script” />
</handlers>
<rewrite>
<rules>
<rule name=”Static Files” stopProcessing=”true”>
<match url=”^/static/.*” ignoreCase=”true” />
<action type=”Rewrite” url=”^/FlaskWebProject1/static/.*” appendQueryString=”true” />
</rule>
<rule name=”Configure Python” stopProcessing=”true”>
<match url=”(.*)” ignoreCase=”false” />
<conditions>
</conditions>
<action type=”Rewrite” url=”handler.fcgi/{R:1}” appendQueryString=”true” />
</rule>
</rules>
</rewrite>
</system.webServer>
</configuration>

Few things. First, I removed the <system.diagnostics> section which installs Azure diags listener. Second, the IIS cannot understand the %ROOTDIR% variable so you should convert it all absolute path for that server you about to run.

So it’ll look like this:

<appSettings>
<add key=”WSGI_ALT_VIRTUALENV_HANDLER” value=”FlaskWebProject1.app” />
<add key=”WSGI_ALT_VIRTUALENV_ACTIVATE_THIS” value=”D:repowebFlaskWebProject1FlaskWebProject1envScriptsactivate_this.py” />
<add key=”WSGI_HANDLER” value=”ptvs_virtualenv_proxy.get_virtualenv_handler()” />
<add key=”PYTHONPATH” value=”D:repowebFlaskWebProject1FlaskWebProject1” />
</appSettings>

The generated web.config has a python handler mapped, but the path also needs to be updated to point the direct wfastcgi.py path as follows:

<handlers>
<add name=”Python FastCGI” path=”handler.fcgi” verb=”*” modules=”FastCgiModule” scriptProcessor=”C:Python34python.exe|C:Python34Scriptswfastcgi.py” resourceType=”Unspecified” requireAccess=”Script” />
</handlers>

It’s enough to edit a web.config. However, if you still encounter a strange 500 internal error, please make sure the local IIS has the URL Rewrite 2.0 module installed. In my case, whenever I tried to open the edited web.config from IIS manager, it gives me that “There was an error while performing this operation. … web.config” error so that I couldn’t open a web.config nor edit mapping handlers. Fortunately, I found those answers from SO and solved it by installing URL Rewrite 2.0 through the ‘Web Platform Installer’. Microsoft Download site also provides a standalone exe.

urlrewrite2

http://stackoverflow.com/questions/3701562/iis-7-5-cant-open-handler-mappings

http://stackoverflow.com/questions/22199424/asp-net-iis-web-config-there-was-an-error-while-performing-this-operation

Done. If the IIS successfully loaded web.config, then it’ll show the correctly mapped Python wfastcgi handler at ‘Handler Mappings’ as follows:

handler1 handler2

If you have any questions, please leave a comment. Thanks for reading.

Published by Heejune


View all posts by Heejune

Published
April 22, 2015May 17, 2015

Even if you already have IIS installed, you may need to go through these steps to install the CGI feature if it wasn’t installed as part of the original IIS installation.

Python virtual environments are used to isolate application-specific Python environments from the system-wide Python environment. Even if you will only be running one application on a server, it’s good practice to create a virtual environment for your application to keep the virtual environment free from any unanticipated side effects of system updates.

With the virtual environment created, the next steps are to activate the virtual environment and update pip, Python’s package installer.

Typically, you’ll be installing requirements from a requirements.txt file that is part of the codebase for your application, but for the purposes of this installation guide we’ll install Django in our virtual environment, both to illustrate the steps involved as well as to ensure the virtual environment is working properly. Then we’ll create a sample Django application that we’ll use later to configure with IIS.

  1. In the same Command Prompt you opened above, with the virtual environment activated, install Django:
    pip install django [then press Enter]
  2. As outlined in the prerequisites section at the beginning of this document, you’ll also need to install wfastcgi in order for IIS to be able to pass requests off to Django:
    pip install wfastcgi [then press Enter]
  3. Navigate to the root of the C: drive:
    cd C: [then press Enter]
  4. Create a new directory in which we’ll put our application:
    mkdir apps [then press Enter]
  5. Navigate to the newly created apps directory:
    cd apps [then press Enter]
  6. Create a new Django project called foo:
    django-admin.py startproject foo [then press Enter]
  7. Navigate to the newly created foo project directory:
    cd foo [then press Enter]
  8. Start the Django development server:
    python manage.py runserver [then press Enter]
    1. You should see the following output:
  9. In a browser on the server, go to http://localhost:8000
    You should see the following:
  10. Go back to the Command Prompt and press Ctrl-C to stop the Django development server.

Configure IIS to Serve Django Applications

Thus far we’ve accomplished the following:

  1. Installed Python
  2. Installed IIS with CGI
  3. Created and activated a Python virtual environment
  4. Installed Django and wfastcgi in a Python virtual environment
  5. Created a new Django project
  6. Ran the Django project using the Django development server

With all the underlying infrastructure in place, the last step is to configure IIS to serve Django applications. The Django development server is not designed for production use, so using a production-quality web server such as IIS is mandatory for production applications.

As with previous steps you’ll need to adjust accordingly for the actual application you want to deploy, but for the purposes of this documentation we’ll configure IIS to serve the test Django application we created in the previous steps.

Configure FastCGI in IIS

  1. Open the IIS Manager by clicking the Windows button, clicking on Administrative Tools, and double-clicking Internet Information Services (IIS) Manager
  2. Click on the name of the server in the list on the left. If you see the following dialog box, check the box “Do not show this message” and click “No.” (You can always get to this later if necessary by clicking “Get New Web Platform Components” under “Actions” on the right-hand side of IIS Manager.)
  3. Double-click the “FastCGI Settings” icon
  4. Under “Actions” on the right-hand side click “Add application …”
  5. In the Add FastCGI Application dialog, in the “Full Path” box, type the path to the Python executable for the application’s virtual environment:
    C:virtualenvsfooScriptspython.exe
  6. In the Arguments input box, type the path to the wfastcgi.py file in the application’s virtual environment:
    C:virtualenvsfooLibsite-packageswfastcgi.py
  7. At this point your settings in the Add FastCGI Application dialog should look like this:
  8. With the Add FastCGI Application dialog box still open, under the “General” section, click on the “Environment Variables” line, then click the gray “…” button that appears next to (Collection) on the right-hand side of the line. This opens the EnvironmentVariables Collection Editor dialog.
  9. In the EnvironmentVariables Collection Editor dialog, click “Add”
  10. In the “Name properties” section on the right, click the input box to the right of “Name,” remove the “Name” text that is already in the input box, and enter DJANGO_SETTINGS_MODULE (note that this MUST be entered in ALL CAPS)
  11. Click the input box to the right of “Value” and enter foo.settings
  12. Click “Add” again and enter the following:
    Name: PYTHONPATH
    Value: C:appsfoo
  13. Click “Add” again and enter the following:
    Name: WSGI_HANDLER
    Value: django.core.wsgi.get_wsgi_application()
  14. At this point you will have three environment variables:
    1. NOTE: All of these settings are CASE-SENSITIVE. They must be entered with exactly the case indicated here in order to work.
  15. Click “OK” to close the EnviromentVariables Collection Editor
  16. Click “OK” to close the Add FastCGI Application dialog

Create and Configure a New IIS Web Site

Next we need to create a new web site in IIS for the Django application, and add a Handler Mapping to the newly created web site so that requests coming to the IIS web site are passed off to the Django application for processing.

  1. Open IIS Manager
  2. On the left-hand side under Connections, expand the tree under the server name by clicking on the arrow to the left of the server name
  3. Right-click on the Sites folder and click “Add Website …”
  4. For the site name enter foo
  5. For the physical path, type the following:
    C:appsfoo
  6. For the purposes of this example configuration, change the Port to 81, since the Default site is running on port 80. For a real-world application you’ll likely want to use name-based virtual hosting by adding bindings and run the site on port 80.
  7. You may leave the “Host name” blank. At this point the Add Website dialog should look like this:
  8. Click “OK”

Next, we’ll add a FastCGI handler mapping to this site so the requests coming into the site will be processed by the Django application.

  1. In IIS Manager, expand the Sites folder on the left-hand side and click on the foo site
  2. On the right, double-click “Handler Mappings”
  3. On the right, under “Actions,” click “Add Module Mapping”
  4. In the “Request path” box enter an asterisk: *
  5. Click the arrow on the right-hand side of the “Module” box and select “FastCgi Module”
    1. NOTE: Make sure to select FastCgi Module, NOT CgiModule
  6. In the “Executable” box, enter the following:
    C:virtualenvsfooScriptspython.exe|C:virtualenvsfooLibsite-packageswfastcgi.py
    1. Note that the character after python.exe is a pipe (|), which is entered by pressing Shift- on your keyboard
  7. In the “Name” box, enter Django Handler (you can call this whatever you want; it’s merely a friendly name for the module mapping)
  8. The Add Module Mapping dialog should now look like this:
  9. Click the “Request Restrictions” button and uncheck the “Invoke handler only if request is mapped to:” checkbox
  10. Click “OK” to close the Request Restrictions dialog
  11. Click “OK” to close the Add Module Mapping dialog
  12. When prompted “Do you want to create a FastCGI application for this executable?” click “No” since we created the application earlier.
    1. Note that you CAN have it create the FastCGI application for you from the module mapping, but the settings seem to be different and the end result isn’t fully editable. I also detailed how to create the FastCGI application to be as thorough as possible with all the various pieces involved.
  13. You will now see the Django Handler listed in the Handler Mappings for the foo website:

At this point everything should be working, so verify by loading the application in a browser.

  1. Open a browser on the server
  2. Browse to http://localhost:81
  3. You should see the following:

This is the same result as when we ran the Django test server earlier, but now the requests are being handled by IIS.

Configure Django and IIS to Serve Static Files

Now we have things more or less working but we aren’t quite done. If you browse to the Django admin page (http://localhost:81/admin), you’ll see something like this:

The reason things look a little strange is because IIS doesn’t know where things like the CSS and image files for the Django application are located. In the Django world these assets are referred to as “static files,” and we need to perform a couple of additional steps for IIS to be able to serve these files. This isn’t an issue during development since Django has a static file server built into it, but in production we’ll want IIS to handle serving these files.

How Django handles static files is a bit of a topic in and of itself, so for further information please consult the Django documentation (https://docs.djangoproject.com/en/1.9/howto/static-files/). In this guide we’ll focus on a specific set of steps to get things working without getting into too many of the behind-the-scenes technical details, the different philosophies on where static files can or should be placed, or the various and sundry ways in which this aspect of Django applications can be addressed.

Add a STATIC_ROOT Setting to the Django Settings File

First, your Django application’s settings file needs to include a STATIC_ROOT setting, and this setting is not in Django applications by default. The STATIC_ROOT setting is used when Django’s collectstatic management command is run to determine where to place the collected static files.

In our sample foo application, we’ll tell Django to collect the static files in a static directory located in the same directory as the settings.py file. (You can ultimately put your static directory wherever you wish, but this is where we’ll be putting it for the purposes of this example.)

To accomplish this, do the following:

  1. Using a plain text editor such as Notepad, or Idle if that was installed when you installed Python, open the file C:appsfoofoosettings.py
  2. Scroll to the bottom of the file, or use the find feature of your text editor, and find the STATIC_URL setting
  3. Above the STATIC_URL setting, add the following setting:
    STATIC_ROOT = os.path.abspath(os.path.join(BASE_DIR, ‘foo’, ‘static’))
    1. The placement of the STATIC_ROOT setting in the settings.py file doesn’t matter, but putting it right next to the STATIC_URL setting is typical and keeps all the settings related to static files in one place.
    2. The STATIC_ROOT setting we’re using as our example will put the static files in C:appsfoofoostatic
  4. Save the settings.py file

Run the collectstatic Management Command

Now that Django knows where to put the static files, we can run the collectstatic management command. This command takes all the static files for your project, including the static files used by the Django admin and other packages in your virtual environment, and puts them under one static directory, the location of which is the STATIC_ROOT setting we added above, so they can be served by the web server.

Now we have all our static files in one place, but we still haven’t told IIS where they’re located. We’ll accomplish this by adding a static virtual directory to the IIS web site for our application.

Note that the name of the virtual directory in IIS must match the value of the STATIC_URL setting in the Django application’s settings.py file, absent the beginning and trailing slashes. For our sample application we’re using a value of /static/ for the STATIC_URL setting, so the name of the virtual directory in IIS will be static.

Create a virtual directory in IIS as follows:

The last step is to tell IIS which handler to use to serve files out of the static virtual directory. Since at this point our Django Handler is set to serve all files for our application, even with the static virtual directory in place the Django Handler will still be attempting to serve these files.

IIS already has a static file handler active in the web site, but it’s down further in the list of handlers than the global Django Handler we configured, so to get IIS to serve the static files under the static virtual directory we’ll move the static file handler to the top of the handler list on the static virtual directory.

Confirm that everything is working by going to http://localhost:81/admin in a browser. You should now see the CSS being applied to the page.

Additional Concerns with Static Files

  1. Don’t include the directory to which the STATIC_ROOT setting is pointing in your application’s code repository; these files should not be tracked and versioned from that location, and the Django development server handles static files for you by serving them directly from their various locations. The collectstatic management command should be run as a normal part of the deployment process for production instances of your application.
  2. For complete information about Django’s handling of static files, and production deployment of static files, please refer to the following section of the Django documentation:
    1. https://docs.djangoproject.com/en/1.9/howto/static-files/
    2. https://docs.djangoproject.com/en/1.9/howto/static-files/deployment/

At this point your Django application should be playing nicely with IIS.

Additional Information

The information in this section is merely for reference, and to retain some of the research that was performed in the preparation of this guide even though it ultimately may not have been used as part of the final configuration steps.

Resources/Further Reading

Interesting things I came across while preparing this guide, in no particular order:

  • http://mrtn.me/blog/2012/06/27/running-django-under-windows-with-iis-using-fcgi/
  • https://www.toptal.com/django/installing-django-on-iis-a-step-by-step-tutorial
  • https://www.youtube.com/watch?v=kXbfHtAvubc
  • https://www.youtube.com/watch?v=cgTFrAwXeoI
  • http://kiahosseini.github.io/server/2016/01/05/running-multiple-django-python-3-projects-in-windows-server-2012-on-iis.html
  • http://www.wahyu.org/running-django-1-8-1-on-iis-7-with-python-2-7-9/
  • http://serverfault.com/questions/366348/how-to-set-up-django-with-iis-8
  • http://stackoverflow.com/questions/34840354/django-on-iis-django-core-exceptions-appregistrynotready-apps-arent-loaded-ye (where I discovered that most of the examples of running Django on IIS had an older reference to the WSGI handler)
  • http://netdot.co/2015/03/09/flask-on-iis/
  • https://pypi.python.org/pypi/wfastcgi
  • https://pip.pypa.io/en/latest/user_guide/#installing-from-local-packages (good information about how to package up applications for deployment on an server without internet access)
  • https://groups.google.com/forum/#!topic/web2py/0jUZmhWjaxY
  • https://heejune.me/2015/04/22/running-python-flask-on-a-local-iis-not-azure-with-wfastcgi-py/
  • http://www.pyinstaller.org/ (another option for packaging up Django applications for automated deployment)
  • http://stackoverflow.com/questions/32312590/how-to-fetch-static-css-files-with-django-on-iis

Additional Avenues of Exploration

  • It is possible to use a web.config file at the web site level instead of the GUI IIS configuration for FastCGI and the site-specific handlers; see http://stackoverflow.com/questions/9794985/iis-this-configuration-section-cannot-be-used-at-this-path-configuration-lock for details about what needs to be enabled to support this. While it’d be handy to include these as part of the application’s codebase, it does involve installing and enabling a bunch of additional IIS add-ons at the root level of IIS, none of which are necessary for the purposes of running a Django app.

Install WFastCGI Gateway for IIS and Python 3.4

Installing WFastCGI for IIS through the IIS Manager is completely optional. It’s simply an alternate way of installing Python (in this case Python 3.4 specifically), and also provides the wfastcgi.py file that is required to configure a handler in IIS for Python applications.

If you perform these steps, Python 3.4 will be installed at the root of the C: drive, and this distribution of Python 3.4 will also place the wfastcgi.py file in the C:Python34 directory. You can then leverage this file or copy it into your application’s directory to configure the IIS handler.

  1. Open IIS Manager
  2. Click on the server in the list under “Connections” on the left-hand side
  3. At this point you may see a dialog box prompting you to install Microsoft Web Platform:
    1. If you see this dialog box, click “Yes.” This will open the download page in a web browser.
    2. If you do not see this box, under “Actions” on the right-hand side of IIS Manager, click on “Get New Web Platform Components.” This will open the download page in a web browser.
    3. You will be prompted to launch the Microsoft Web Platform application every time you launch IIS Manager, so if you see this dialog box after you have already installed the Web Platform Installer, feel free to check “Do not show this message” and then click “No.”
  4. On the Microsoft Web Platform web page, click the “Free Download” button.
  5. After the download completes, located the downloaded file and double-click to run it. As of the time of this writing the file is called wpilauncher.exe
  6. If you see a Security Warning dialog, click “Run” to run the installer.
  7. After the installation completes, the Web Platform Installer 5.0 application will launch.
  8. In the Web Platform Installer 5.0 application, in the search box on the top right, type “fastcgi” (without the quotes) and press Enter.
  9. In the search results, locate “WFastCGI 2.1 Gateway for IIS and Python 3.4” and click the “Add” button.
  10. At the bottom of the Web Platform Installer application, click “Install.”
  11. In the Prerequisites dialog that appears, click “I Accept” to accept the terms of the license.
  12. The WFastCGI extension will be downloaded and installed. When the installation completes, click “Finish” to close the installation dialog, and then click “Exit” to close the Web Platform Installer.

Note that doing installing the WFastCGI Gateway and Python 3.4 in this way does not automatically configure the FastCGI and Handler Mappings in IIS for you. It does install a default Python FastCGI application, but this will not necessarily automatically work with your application, and at a minimum you would still need to add a Handler Mapping for your application.

    Понравилась статья? Поделить с друзьями:
  1. Error occurred while fetching token from xbox secure token service
  2. Error for site owner invalid domain for site key как исправить
  3. Error object response
  4. Error number 1021 mysql
  5. Error not implemented navigation except hash changes