You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Nginx+Gunicorn+systemd部署Django时,如何通过getpass输入密钥?

解决方案

1. 调整settings.py的密钥获取逻辑

把原有的交互式getpass改为优先从环境变量读取,既保留本地开发的交互能力,又适配服务启动场景:

# settings.py
import os
from getpass import getpass

# 环境变量存在则直接读取,否则提示输入(兼容本地开发)
AES_CIPHER_KEY = os.environ.get('AES_CIPHER_KEY') or getpass("Enter AES cipher key: (leave blank if you don't need decryption)")

2. 编写gunicorn启动脚本

创建/root/samir/start_gunicorn.sh脚本,负责交互式获取密钥并传递给gunicorn进程:

#!/bin/bash
# 静默读取密钥(不回显输入内容)
read -s -p "Enter AES cipher key: (leave blank if you don't need decryption) " AES_KEY
echo
# 将密钥注入环境变量
export AES_CIPHER_KEY="$AES_KEY"
# 启动gunicorn(注意绑定路径与socket配置统一)
/root/samir/venv/bin/gunicorn --access-logfile - --workers 3 --bind unix:/run/gunicorn.sock samir.wsgi:application

给脚本添加执行权限:

chmod 700 /root/samir/start_gunicorn.sh

3. 更新gunicorn.service配置

修改/etc/systemd/system/gunicorn.service,让systemd允许服务访问终端并执行启动脚本:

[Unit]
Description=gunicorn daemon
Requires=gunicorn.socket
After=network.target

[Service]
User=root
Group=www-data
WorkingDirectory=/root/samir/src/samirpy
# 替换为启动脚本路径
ExecStart=/root/samir/start_gunicorn.sh
# 开启终端交互支持
StandardInput=tty-force
StandardOutput=journal+console
StandardError=journal+console
TTYPath=/dev/tty
# 失败时自动重启
Restart=on-failure

[Install]
WantedBy=multi-user.target

4. 生效配置并重启服务

执行以下命令让systemd加载新配置,然后重启服务:

sudo systemctl daemon-reload
sudo systemctl restart gunicorn.service

执行重启命令后,终端会弹出密钥输入提示,输入完成后服务即可正常启动。

内容的提问来源于stack exchange,提问作者AMiWR

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.10 10:52:41