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

如何在Django-Twilio应用启动时自动运行Python HTTP Server 80端口

当然可以,下面是几种实用的实现方式:

实现方法

方法一:通过Django AppConfig的ready()钩子

可以在Django应用的apps.py里利用ready()方法启动HTTP服务器,但要注意避免开发环境下重复启动(runserver命令会默认重启两次进程)。

步骤:

  1. 打开你应用的apps.py文件,修改AppConfig类:
import subprocess
import os
from django.apps import AppConfig

class YourAppConfig(AppConfig):
    default_auto_field = 'django.db.models.BigAutoField'
    name = 'your_app_name'  # 替换为你的应用名称

    def ready(self):
        # 仅在主进程中执行,避免runserver重复启动
        if os.environ.get('RUN_MAIN') == 'true':
            # 启动80端口的HTTP服务器,将输出重定向避免干扰Django日志
            subprocess.Popen(
                ['python', '-m', 'http.server', '80'],
                stdout=subprocess.DEVNULL,
                stderr=subprocess.DEVNULL,
                start_new_session=True
            )
  1. 在应用根目录的__init__.py中指定自定义的AppConfig:
default_app_config = 'your_app_name.apps.YourAppConfig'

注意:这种方式更适合开发环境,生产环境建议用更可靠的进程管理方案。

方法二:用启动脚本批量启动

写一个简单的脚本,同时启动Django服务和HTTP服务器,直观且不会出现重复启动问题。

Linux/macOS(bash脚本)

创建start_app.sh文件:

#!/bin/bash
# 后台启动HTTP服务器
python -m http.server 80 &
# 启动Django开发服务器
python manage.py runserver

赋予执行权限:chmod +x start_app.sh,运行时执行./start_app.sh即可。

Windows(bat脚本)

创建start_app.bat文件:

@echo off
start python -m http.server 80
python manage.py runserver

双击运行或在命令行执行start_app.bat即可。

方法三:生产环境用进程管理工具

如果是生产环境部署,推荐用supervisor或systemd来统一管理多个进程,确保服务稳定运行。以supervisor为例:

  1. 安装supervisor:pip install supervisor
  2. 创建配置文件supervisord.conf:
[supervisord]
nodaemon=true

[program:django]
command=python manage.py runserver 0.0.0.0:8000  # 生产建议用WSGI服务器如gunicorn
directory=/path/to/your/django/project
autostart=true
autorestart=true

[program:http_server]
command=python -m http.server 80
directory=/path/to/your/target/files  # 指定要暴露文件的目录
autostart=true
autorestart=true
  1. 启动supervisor:supervisord -c supervisord.conf

这样两个服务会被统一监控,异常时自动重启。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 10:25:32