在CentOS上搭建Python Web服务器可以通过多种方式实现,以下是使用Apache和mod_wsgi的常见方法:
安装必要的软件包
sudo yum update -y
sudo yum install -y httpd mod_wsgi python3
启动并启用Apache服务
sudo systemctl start httpd
sudo systemctl enable httpd
创建一个简单的Python Web应用
在/var/www/html
目录下创建一个名为app.py
的文件:
from http.server import BaseHTTPRequestHandler, HTTPServer
class SimpleHTTPRequestHandler(BaseHTTPRequestHandler):
def do_GET(self):
self.send_response(200)
self.send_header('Content-type', 'text/html')
self.end_headers()
self.wfile.write(b"Hello, World!")
def run(server_class=HTTPServer, handler_class=SimpleHTTPRequestHandler, port=8080):
server_address = ('', port)
httpd = server_class(server_address, handler_class)
print(f'Starting httpd on port {port}...')
httpd.serve_forever()
if __name__ == '__main__':
run()
创建WSGI文件
在/var/www/html
目录下创建一个名为app.wsgi
的文件:
import sys
sys.path.insert(0, '/var/www/html')
from app import run as application
配置Apache
编辑Apache配置文件/etc/httpd/conf/httpd.conf
或创建一个新的配置文件/etc/httpd/conf.d/pythonapp.conf
:
<VirtualHost *:80>
ServerAdmin webmaster@localhost
DocumentRoot /var/www/html
WSGIDaemonProcess pythonapp threads=5 python-path=/var/www/html
WSGIProcessGroup pythonapp
WSGIScriptAlias / /var/www/html/app.wsgi
<Directory /var/www/html>
Require all granted
</Directory>
ErrorLog ${APACHE_LOG_DIR}/error.log
CustomLog ${APACHE_LOG_DIR}/access.log combined
</VirtualHost>
重启Apache服务
sudo systemctl restart httpd
访问你的应用
打开浏览器并访问http://your_server_ip_or_domain
,你应该能看到"Hello, World!"的消息。
安装必要的软件包
sudo yum update -y
sudo yum install -y python3 pip nginx
创建一个简单的Python Web应用
在/var/www/html
目录下创建一个名为app.py
的文件:
def application(environ, start_response):
status = '200 OK'
headers = [('Content-type', 'text/plain')]
start_response(status, headers)
return [b"Hello, World!"]
安装Gunicorn
pip3 install gunicorn
启动Gunicorn
gunicorn -b 127.0.0.1:8000 app:application
配置Nginx
编辑Nginx配置文件/etc/nginx/nginx.conf
或创建一个新的配置文件/etc/nginx/conf.d/pythonapp.conf
:
server {
listen 80;
server_name your_server_ip_or_domain;
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 start nginx
sudo systemctl enable nginx
访问你的应用
打开浏览器并访问http://your_server_ip_or_domain
,你应该能看到"Hello, World!"的消息。
这两种方法都可以有效地在CentOS上搭建Python Web服务器,选择哪种方法取决于你的具体需求和偏好。