使用IIS部署Django项目
1. 系统及软件版本: Windows Server 2008 Standard, IIS 7.0, Python3.6+Django 2.0.4
2 . python安装wfastcgi模块:pip install wfastcgi
3. 安装成功后,打开python目录—>Lib—>site-packages目录,将wfastcgi.py文件拷贝到Django项目根目录下;
4. 因为用户权限等问题,建议将Django项目文件夹拷贝到C:\inetpub\wwwroot下;
5. IIS中添加网站,设置物理路径和端口号;
6. 选择新建站点,选择处理程序映射—>添加模块映射
请求路径:*
模块:FastCgiModule
可执行文件:xxxxxxxx|xxxxxxxxx
注意: 前半部分为python.exe路径,如果配置虚拟环境,则为虚拟环境的python.exe路径。
后半部分为inetpub\wwwroot下,待发布的Django项目里wfastcgi.py文件的路径。
请求限制中,勾选仅当请求映射至以下内容时才调用处理程序,选择文件。
7. 配置完成后,选择IIS根节点,选择FastCGI设置,选择上一步添加的模块映射,配置环境变量
需要添加的变量有3个:
(1)get_wsgi_application()方法的位置,C:\administrator\Lib\site-packages\django\core\wsgi.py
Name: WSGI_HANDLER
Value: django.core.wsgi.get_wsgi_application()
(2) Django项目目录
Name: PYTHONPATH
Value: C:\inetpub\wwwroot\项目名
(3)项目settings.py文件的位置
Name: DJANGO_SETTINGS_MODULE
Value: 项目名.settings
在项目文件夹中web.config文件内容:
<?xml version="1.0" encoding="UTF-8"?>
<configuration> <system.webServer> <handlers> <add name="Python FastCGI" path="*" verb="*" modules="FastCgiModule" scriptProcessor="<Path to Python>\python.exe|<Path to file>\wfastcgi.py" resourceType="Unspecified" requireAccess="Script"/> </handlers> </system.webServer> <appSettings> <add key="WSGI_HANDLER" value="django.core.wsgi.get_wsgi_application()" /> <add key="PYTHONPATH" value="<Path to Django App>" /> <add key="DJANGO_SETTINGS_MODULE" value="<Django App>.settings" /> </appSettings> </configuration>
8. 配置静态文件:在IIS部署站点上,右键点击新建虚拟目录,路径为静态文件夹
在静态文件夹中建立web.config文件,并设置:
<?xml version="1.0" encoding="UTF-8"?>
<configuration> <system.webServer> <!-- this configuration overrides the FastCGI handler to let IIS serve the static files --> <handlers> <clear/> <add name="StaticFile" path="*" verb="*" modules="StaticFileModule" resourceType="File" requireAccess="Read" /> </handlers> </system.webServer> </configuration>
9. 以上配置后应该可以运行了。重点是两个web.config文件,尤其是在静态文件夹中的web.config文件,一般没有介绍的。
10. 一些注意事项:
- 在实际部署中出现admin模块丢失样式的问题。解决办法是,在static文件夹中把python文件中的关于admin的样式目录拷贝过来。
- 使用django auth进行登录,当验证登陆成功后,页面会自动跳转到/account/profile,报找不到页面的错误,需要在project的setting.py中设定LOGIN_REDIRECT_URL = ‘/index’,指定登陆成功后跳转的index页面。
- 注意文件夹、文件的只读、权限问题,一般都会碰到。
- 报HTTP 400 错误 - 请求无效 (Bad request),或者本机能够访问,用IP地址不能访问,原因是settings.py中的ALLOWED_HOSTS的设定问题,先设为ALLOWED_HOSTS=['*']测试,再添加IP地址或域名。