在CentOS上实现Python Web开发,你需要遵循以下步骤:
首先,确保你的CentOS系统已经安装了EPEL和Remi仓库。这些仓库包含了Python和其他必要的开发工具。
sudo yum install epel-release
sudo yum install https://rpms.remirepo.net/enterprise/remi-release-7.rpm
使用Remi仓库安装Python 3.x(推荐使用最新的稳定版本):
sudo yum-config-manager --enable remi-php74
sudo yum install python3
你可以选择安装Apache或Nginx作为Web服务器。这里以Nginx为例:
sudo yum install nginx
启动Nginx并设置开机启动:
sudo systemctl start nginx
sudo systemctl enable nginx
WSGI(Web Server Gateway Interface)是Python Web应用程序与Web服务器之间的接口。这里以Gunicorn为例:
sudo pip3 install gunicorn
为了避免不同项目之间的依赖关系冲突,建议使用虚拟环境。安装virtualenv
和virtualenvwrapper
:
sudo pip3 install virtualenv virtualenvwrapper
配置virtualenvwrapper
:
echo "source /usr/local/bin/virtualenvwrapper.sh" >> ~/.bashrc
source ~/.bashrc
创建一个新的虚拟环境:
mkvirtualenv myproject
激活虚拟环境:
workon myproject
在虚拟环境中安装项目所需的Python库,例如Django或Flask:
pip install django
现在你可以开始开发你的Python Web应用程序了。编写代码、配置URL路由、创建视图函数等。
在项目目录中创建一个gunicorn.conf.py
文件,配置Gunicorn:
bind = '127.0.0.1:8000'
workers = 3
在虚拟环境中启动Gunicorn:
gunicorn -c gunicorn.conf.py myproject.wsgi:application
编辑Nginx配置文件(通常位于/etc/nginx/conf.d/default.conf
),添加以下内容:
location / {
proxy_pass http://127.0.0.1:8000;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
重启Nginx以应用更改:
sudo systemctl restart nginx
现在,你的Python Web应用程序应该可以通过浏览器访问了。