在AWS Beanstalk环境配置中,可以在“Software”选项卡下找到“Environment Properties”选项。添加一个名为“WSGIPath”的环境变量,将其值设置为Django项目中wsgi.py文件的路径,如“/opt/python/current/app/project/wsgi.py”。
如果在Django项目中使用虚拟环境,则也需要设置“WSGIPath”环境变量,值应该是虚拟环境下wsgi.py文件的路径,如“/opt/python/run/venv/project/lib/python3.6/site-packages/project/wsgi.py”。
此外,也需要在Django项目的配置文件(settings.py)中设置ALLOWED_HOSTS参数,确保允许访问AWS Beanstalk的域名或IP地址。
代码示例:假设我的Django项目名字为“project”,我的完整的WSGIPath路径应该是“/opt/python/current/app/project/wsgi.py”。在AWS Beanstalk环境配置中添加一个“WSGIPath”环境变量,值为“/opt/python/current/app/project/wsgi.py”。
ALLOWED_HOSTS = ['example.com', 'xxx.xxx.xxx.xxx'] #设置允许访问的域名或IP地址
# AWS 负载均衡器网关形如 xxxx-xxxxxx.elb.amazonaws.com
allowed = [host for host in ALLOWED_HOSTS if host.endswith('.amazonaws.com')]
if 'AWS_DEFAULT_REGION' in os.environ:
allowed += [f'{host}.x.amazonaws.com' for host in allowed]
ALLOWED_HOSTS += allowed
设置完毕后,重新部署AWS Beanstalk即可。