- Русские Блоги
- [Django] Опубликовать веб-сайт Django через IIS на Windows
- Проблемы, которые необходимо решить:
- Версия системы и программного обеспечения:
- 1. Работающий сайт Django
- 2. Установка и настройка ИИС
- 3. Python установить модуль wfastcgi
- 4. Обработка файлов проекта
- 4.1 Скопируйте файлы проекта в каталог C: \ inetpub \ wwwroot для удобного управления и избежания некоторых проблем с безопасностью Windows Server.
- 4.2 В каталоге Python Lib \ site-packages найдите файл wfastcgi.py и скопируйте его в корневой каталог вашего проекта django
- 5. Настроить сайт
- 5.1 Войдите в IIS Manager и добавьте веб-сайт
- 5.2 Заполните соответствующие параметры
- 5.3 Перейдите на созданный вами сайт и выберите отображение обработчика.
- 5.4 Добавить отображение модуля
- 5.5 После заполнения параметров выберите Запрос управления и установите, как показано
- 5.6 После подтверждения добавления карта программы добавлена успешно
- 5.7 Вернитесь на домашнюю страницу и войдите в настройки FastCGI.
- 5.8 Новое приложение FastCGI, измените переменные среды
- 6 Создайте файл с именем web.config в корневом каталоге веб-сайта.
- 6+. Измените ALLOWED_HOSTS в файле setting.py
- 7. Настройте статические файлы
- 7.1 Настройте STATIC_ROOT в C: \ inetpub \ wwwroot \ HelloWorld \ HelloWorld \ settings.py следующим образом:
- 7.2 Сбор статических файлов
- 7.3 Настройка статических файлов
- 7.4 Откройте диспетчер IIS, выберите элемент веб-сайта, щелкните правой кнопкой мыши и выберите «Добавить виртуальный путь».
- 7.5 Заполните псевдоним и путь виртуального пути
- Перезапустите IIS, проблем не должно быть
- Issues
- Context Navigation
- Goals
- Steps
- Install Python
- Install PyISAPIe — an ISAPI extension for IIS
- Setting up Files
- Setting up IIS
- Multiple Django Installations on IIS
- IIS 7
- IIS 6
- IIS 5
- IIS Troubleshooting
- Django
- Installing Django
- Linking Django to PyISAPIe
- Serving Django with IIS
- Known Issues
- Configure Django for SQL Server
Русские Блоги
[Django] Опубликовать веб-сайт Django через IIS на Windows
В Интернете есть много учебных пособий, ниже приведены мои личные тесты:
Проблемы, которые необходимо решить:
1. использоватьpython manage.py runserverДля запуска сервера он подходит только для использования в тестовой среде. Для официально выпущенной службы требуется стабильный и непрерывный сервер.
2. Развернуть на сервере Windows
3. Статические файлы CSS, Font, Image, js на веб-сайте Django могут быть идеально загружены с помощью команды runserver на локальном сервере.После развертывания в IIS происходит сбой CSS и статические файлы исчезают.
Версия системы и программного обеспечения:
1. Работающий сайт Django
Проект, который я создал, называется HelloWorld, а каталог выглядит следующим образом
Сначала убедитесь, что ваш сайт django может нормально работать на сервере через сервер запуска командной строки.
Сначала перейдите в корневой каталог веб-сайта в командной строке: D: \ Automation_Develop_Work \ HelloWorld
Затем выполните python manage.py runserver 0.0.0.0:8000
Поскольку и python2, и python3 установлены на моем компьютере, и я использую python3 для создания среды django, мне нужно использовать следующую команду:
py -3 manage.py runserver 0.0.0.0:8000
Затем вы можете ввести в браузереhttp://127.0.0.1:8000/admin/
(Я следовал этому уроку заранее:http://www.runoob.com/django/django-admin-manage-tool.htmlСоздан административный инструмент управления):
2. Установка и настройка ИИС
В разделе «Программы и компоненты панели управления» откройте окно «Включить или закрыть компоненты Windows».
Проверьте все подкаталоги в Internet Information Services, вы должны проверить каждый
3. Python установить модуль wfastcgi
Установить с помощью pip установить wfastcgi
Поскольку и python2, и python3 установлены на моем компьютере, и я использую python3 для создания среды django, мне нужно использовать следующую команду:
pip3 install wfastcgi
Я установил его на свой компьютер. Я не сохранил предыдущий снимок экрана. На приведенном ниже снимке экрана показано, что я установил его.
4. Обработка файлов проекта
4.1 Скопируйте файлы проекта в каталог C: \ inetpub \ wwwroot для удобного управления и избежания некоторых проблем с безопасностью Windows Server.
4.2 В каталоге Python Lib \ site-packages найдите файл wfastcgi.py и скопируйте его в корневой каталог вашего проекта django
Моя машина копирует C: \ Python37 \ Lib \ site-packages \ wfastcgi.py в C: \ inetpub \ wwwroot \ HelloWorld \ wfastcgi.py
5. Настроить сайт
5.1 Войдите в IIS Manager и добавьте веб-сайт
Мой компьютер-> Правой кнопкой мыши-> Управление-> Сервисы и приложения-> Диспетчер служб IIS
5.2 Заполните соответствующие параметры
5.3 Перейдите на созданный вами сайт и выберите отображение обработчика.
Обратите внимание, что вы должны войти на сайт, который вы указали, а затем добавить сопоставление модуля, в противном случае сопоставление будет добавлено на все ваши сайты.
5.4 Добавить отображение модуля
Выберите FastCgiModule в качестве модуля. Если модуль wfastcgi не установлен на шаге 3, сначала установите его.
Исполняемый файл фактически требуется для этого проекта.
В этом примере C: \ Python37 \ python.exe | C: \ inetpub \ wwwroot \ HelloWorld \ wfastcgi.py. Первый — это путь к python, а второй — путь к файлу wfastcgi.py. Фактически, если путь к файлу wfastcgi.py напрямую ссылается на файлы в каталоге python \ Lib \ site-packages, это возможно, но вы не можете развернуть несколько сайтов Django.
Имя можно указать самостоятельно, но позже оно будет использовано в файле web.config, так что помните, что вы вводите здесь.
5.5 После заполнения параметров выберите Запрос управления и установите, как показано
5.6 После подтверждения добавления карта программы добавлена успешно
5.7 Вернитесь на домашнюю страницу и войдите в настройки FastCGI.
5.8 Новое приложение FastCGI, измените переменные среды
Нажмите Добавить приложение справа:
Следуйте картинке ниже, чтобы установить и нажмите маленький значок справа от переменных среды
Добавьте 2 переменные среды
Расположение метода get_wsgi_application ()
- Name: WSGI_HANDLER
- Value: django.core.wsgi.get_wsgi_application()
Расположение файла settings.py проекта
Значение: HelloWorld.settings (HelloWorld — это название вашего собственного проекта)
6 Создайте файл с именем web.config в корневом каталоге веб-сайта.
Каталог файлов выглядит следующим образом:
Красные знаки должны быть сопоставлены и могут быть изменены в соответствии с вашей ситуацией.
DJANGO_SETTINGS_MODULE Значение внутри HelloWorld Название проекта
MyFastCgiModule Имя сопоставления модуля добавляется во время настройки IIS
C:\Python37\python.exe|C:\inetpub\wwwroot\HelloWorld\wfastcgi.py Первая часть — это путь к python, а вторая часть — это путь к проекту wfastcgi.py, разделенный вертикальной линией в середине.
На этом этапе сайт Django без статических файлов развернут
На чужих компьютерах вы можете получить доступ к этому веб-сайту через свой IP-адрес, но в это время статические файлы теряются. Вы не видите стили и продолжаете обрабатывать публикацию статических файлов.
6+. Измените ALLOWED_HOSTS в файле setting.py
При доступе к URL-адресу сервера через браузер возникает ошибка доступа, и ошибка
Invalid HTTP_HOST header: ‘xxx.xx.xxx.xxx:8080’. You may need to add ‘xxx.xx’ to ALLOWED_HOSTS
Решение:
Изменить файл setting.py, сгенерированный при создании проекта
Измените ALLOWED_HOSTS = [] на ALLOWED_HOSTS = [‘*’]
Запустите снова для успешного доступа.
7. Настройте статические файлы
7.1 Настройте STATIC_ROOT в C: \ inetpub \ wwwroot \ HelloWorld \ HelloWorld \ settings.py следующим образом:
STATIC_ROOT = os.path.join(BASE_DIR, ‘ static ‘)
Примечание:Здесь должно быть static , Должно соответствовать C: \ inetpub \ wwwroot \ HelloWorld \ HelloWorld \ settings.py STATIC_URL = ‘/ static / Последовательный
7.2 Сбор статических файлов
Из командной строки перейдите в каталог проекта: cd / d C: \ inetpub \ wwwroot \ HelloWorld
Выполните команду: python manage.py collectstatic
Поскольку и python2, и python3 установлены на моем компьютере, и я использую python3 для создания среды django, мне нужно использовать следующую команду:
py -3 manage.py collectstatic
Папка называется static :
Я заранее создал инструмент управления Admin, ниже будет один статический admin Дочерний файл
admin В папке есть css, шрифты, img, js
7.3 Настройка статических файлов
Создайте новый файл с именем web.config в статической папке проекта
Содержимое файла web.config выглядит следующим образом:
MyFastCgiModule Имя сопоставления модуля добавляется во время настройки IIS
7.4 Откройте диспетчер IIS, выберите элемент веб-сайта, щелкните правой кнопкой мыши и выберите «Добавить виртуальный путь».
(Только что проверил, похоже, что этот шаг не нужен)
7.5 Заполните псевдоним и путь виртуального пути
Псевдоним, который я заполнил, является staticForHelloWorld
Путь — это путь к статической папке веб-сайта, которая является только что созданной папкой web.config: C: \ inetpub \ wwwroot \ HelloWorld \ static
Перезапустите IIS, проблем не должно быть
Issues
Context Navigation
Goals
Getting Django to run on Windows, with pages served by IIS, and a SQL Server backend. Assume Windows Server 2003, IIS 6 and SQL Server 2005 where no versions are specified. You should already have Windows, IIS and SQL installed and working before following this guide.
Note: As of PyISAPIe version 1.0.4, this works with Python 2.5. The provided handler works with the current (1-11-08) CVS version of Django.
Note2: PyISAPIe also provides a WSGI adapter that may work with earlier versions of Django. Refer to the new release and docs: http://pyisapie.sourceforge.net/
Note3: This article is outdated. To install current version of Django on Windows with IIS 7 or later please read this article instead: http://www.helicontech.com/articles/running-django-on-windows-with-performance-tests/
Note4: While the site listed as part of note 3 puts forth a solution, the tutorial is missing steps and relies on a closed solution. The DJango-windows-tools project was created to not have these limitations: http://django-windows-tools.readthedocs.org/en/latest/
Steps
- Install Python
- Install PyISAPIe — an extension for IIS to connect Python with IIS
- Install Django and connect Django to PyISAPIe
- ADODB-API — the Python / SQL Server driver
- Configure Django to look at SQL Server
- Test, celebrate
Install Python
A simple download and install for this bit, so open http://www.python.org/ and look for «Quick Links» -> «Windows Installer» in the menu on the left. Download and run it, following the wizard steps until it is complete.
Install PyISAPIe — an ISAPI extension for IIS
PyISAPIe is an IIS extension that loads the Python interpreter into memory while IIS is running, and uses it to serve page requests — it avoids the CGI overhead of restarting Python for every request. It does mean that some Django files will be cached and you wont see changes while testing your Django site until you restart the Python process. With IIS 6 you have to right-click on the application pool running your services and select ‘recycle’ for changes to take. Previous versions of IIS will need the whole IIS service to be restarted.
I will assume you are using c:\python25 as the folder where Python is installed, but please change these where necessary for your setup.
If you have problems with PyISAPIe, check out the PyISAPIe Google Group for support.
Setting up Files
- Go to http://pyisapie.sourceforge.net/ and download it (look in the menu on the right, under «Links» for a download link). Unzip the archive to c:\pyisapie.
- Edit the properties -> security settings of c:\pyisapie\PyISAPIe.dll, add «Network Service» and tick «read» permission. (So IIS can use it).
- Go to c:\pyisapie\source\PyISAPIe\Python\ and copy the entire Http folder to c:\python25\lib\site-packages. Note:the Http folder is case sensitive. Saving in ‘http’ (or any other variation) will not work [SF].
Setting up IIS
You don’t have to create a virtual directory — you can do this with the root folder. If you do use a virtual directory, say /myfolder, then only urls starting with /myfolder will be handled by PyISAPIe. If you use the root folder, all URLs will be handled by PyISAPIe, and you risk anything else on the site being inaccessible afterwards if you’re not careful.
- Open the IIS Management Console, and create a new virtual directory, and allow executing ISAPI extensions when prompted by the wizard.
Multiple Django Installations on IIS
You can only run multiple instances of Django on IIS 6.0 if you use a separate instance of PyISAPIe for each Django instance. This is accomplished by setting up an IIS Application Pool for each PyISAPIe/Django instance that needs to be run. It would be great if multiple instances of Django could run under a single PyISAPIe instance. Please encourage the Django developers to work on this issue and/or contribute a fix yourself. You can find more information about this issue here:
Multiple instances of Django on IIS 5.1 is not currently possible.
IIS 7
- Add the PyISAPIe handler by selecting «Handler Mappings ==> Add Script Map» with the following settings:
- Request Path = *
- Executable = Path to the PyISAPIe.dll
- Name = PyISAPIe (name can be anything)
- Also, be sure that the PyISAPIe handler is higher than the StaticFile handler by clicking «View Ordered List» and reordering as needed.
IIS 6
- View the properties of the new folder and click on the «configuration» button (if it’s greyed out, click ‘create’ first), then add a new wildcard extension (the lower box), locate the pyisapie.dll file and untick the «check that file exists» box.
- In the IIS Manager, go to the «Web Service Extensions» section, and right click -> add new web service extension.
- Give it a name (it doesn’t matter what), add the pyisapie.dll fill as a required file and check the box to set the extension status to allowed.
IIS 5
- IIS 5.x doesn’t support wildcard application maps, at least not through the configuration interface. On IIS 5, the procedure is as follows:
- Right Click on virtual directory and choose «properties»
- Ensure «Execute Permissions» is set to «Scripts and Executables»
- Click «Configuration» (opposite «Scripts and Executables»)
- On «App Mappings» tab, select «Add»
- For Executable, browse to pyisapie.dll (needs full path if you enter manually)
- For extension enter * (this will redirect all requests to pyisapi)
- Using star DOES NOT work in IIS 5, you must specify an extension. [pjs]
- You should probably limit the verbs allowed; I left as all since it was for internal use.
- Untick the «check that file exists» box.
- ‘OK’ to close all the open dialogs.
That’s it installed. In c:\pyisapie\source\PyISAPIe\Python\examples folder is a file called Info.py. Copy this to your new virtual directory folder, and then try and view http://site/Info.py to test it. It should work. If it doesn’t, when you find out why, please come back and explain what happened and how you fixed it. 😉
If you have a 64-bit server, and you want to use 32-bit Python and PyISAPIe (otherwise you have to compile your own PyISAPIe.dll) you may need to:
- Create a new application pool, set it to 32-bit mode, create an application instead of a virtual directory, and set your application to use that pool ( http://www.timvasil.com/blog14/post/2007/11/Run-a-32-bit-ISAPI-DLL-on-64-bit-IIS-7.aspx)
- If you then get Error 500 due to (error number 2147942593) try removing all AboMapperCustom-* handlers from the applications handlers/mappings ( http://social.msdn.microsoft.com/Forums/en-US/sharepointdevelopment/thread/1131026f-7d8b-4e88-8d2c-398b12f4336d/)
IIS Troubleshooting
- «Import Error: couldn’t locate module Http.Isapi» — see Users Group: IIS 6 PyISAPIe problems
Django
Text below saved in hope of an update to PyISAPIe:
If you want to keep up with the latest Django development version, you will need to download and install a subversion client for Windows, e.g. Tortoise SVN, install it, then create a new folder somewhere. Right click on the folder, and choose «SVN Checkout». Give the URL of the repository as: http://code.djangoproject.com/svn/django/trunk/ and click OK.)
Otherwise, just download the latest Django release from the main site, and extract the archive to a folder, e.g. c:\python25\django\.
Installing Django
Drop to a command prompt (start -> run -> «cmd» -> OK), change to your Python folder and install Django. Example:
NB: You will probably need to do some messing around with paths and such to make this work neatly. I’m afraid I’m leaving that to you for now, because I don’t have clear steps. If you know any, please put them here. Without doing that you can still test the Django install, but will need a full path to django-admin.py:
Now open a web browser, and visit the site. It should serve a neat page to you.
Linking Django to PyISAPIe
Next, you must follow the readme.txt in the PyISAPIe examples\django folder, basically copy two files into specific folders. Then edit them a bit in order to fit your needs.
- Put Isapi.py in c:\python25\lib\site-packages\Http folder. According to the example given above, you’ll make the following changes to it:
- Put pyisapie.py (from the PyISAPIe folder you installed earlier) in c:\python25\lib\site-packages\django\core\handlers folder.
Serving Django with IIS
Supposed that you have successfully settled everything above, and pointed the virtual directory /myfolder to c:\test folder, we’ll now make a Hello World page in Django.
- Create a file called helloworld.py in c:\test\proj folder with the following content:
- Modify urls.py in c:\test\proj folder, so you get the url «dispatched»:
You have everything you need to have Django running from IIS. Now visit http://site/myfolder/ to take a look. Notice that you don’t need to manually start a Django server.
Known Issues
- On IIS 5, you have to use the console command «iisreset» for code changes to take effect. Just restarting the website in IIS Management Console has no use. How about IIS 6? (20070304/henrik: — same for iis6 on win2k3)
- NOT true for IIS6: right-click on the application pool your site is using and select «Recycle.» [pjs]
- For debugging purposes in IIS6 you could set «Recycle worker process (number of requests)» = 1 in your application pool properties so you don’t need to «Recycle» all the time. NOT recommended for production usage. [ta]
- I had to create a «media» virtual directory for the stylesheets, etc, at the root of my IIS directory tree (urgh) with read permissions to get the admin site to load styles. Looking at the source for the admin page in my browser, the stylesheet link is absolute (/media/. ) [rnm]
Configure Django for SQL Server
There are two external Django database backends for SQL Server:
Both of these projects are tracking the Django 1.0 release. Issues with those projects should be reported in their corresponding issue trackers.