首页 > 解决方案 > 在 Windows 上使用 Python/Django 运行服务器时,是否可以使用自定义测试 url 进行测试?

问题描述

我习惯了 PHP / Apache,因为我可以在 Windows Hosts 文件中添加一个条目并访问它,而不是使用 localhost url。例如,

Windows > hosts file > 127.0.0.1 testsite.test

然后我也将它添加testsite.test到 Apache VirtualHost 指令中。

我是 Python 和 Django 的新手,并且一直在学习一个教程,它向我展示了如何设置 Python 和 Django,并设置虚拟环境。设置完成后,它运行在http://127.0.0.1:8000python manage.py runserver上启动默认页面

是否可以像上面的 Apache 一样访问这个 url?

标签: pythondjango

解决方案


您有 2 种不同的选择。第一个是在端口 80 上运行 Django runserver,通过执行python manage.py runserver 80. 这可能需要某些系统的管理权限,在这种情况下应该避免,因为授予您的开发代码权限可能是一个安全问题(您可能会错误地破坏您的操作系统,或者有人可能会远程控制您的操作系统) .

第二个选项是通过 nginx 或 apache 重定向您的 Web 服务器。一个简单的nginx配置文件:

server {
    # the port your site will be served on
    listen      80;
    # the domain name it will serve for
    server_name example.com; # substitute your machine's IP address or custom domain name
    charset     utf-8;

    # max upload size
    client_max_body_size 75M;  # Adjust to your need

    location /media  {
        alias /path/to/your/mysite/media;  # your Django project's media files
    }

    location /static {
        alias /path/to/your/mysite/static; # your Django project's collected static files
    }

    # Finally, send all non-media requests to the Django server.
    location / {
        proxy_pass  http://127.0.0.1:8000;
        include     /etc/nginx/proxy_params; # the uwsgi_params file you installed
    }
}

推荐阅读