django 这是我的www.example.com脚本的代码manage.py,我希望有人能解释每一行,请我几乎听不懂

jtw3ybtb  于 2023-02-14  发布在  Go
关注(0)|答案(1)|浏览(65)
import os
import sys

def main():
    """Run administrative tasks."""
    os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'bookr.settings')
    try:
        from django.core.management import execute_from_command_line
    except ImportError as exc:
        raise ImportError(
            "Couldn't import Django. Are you sure it's installed and "
            "available on your PYTHONPATH environment variable? Did you "
            "forget to activate a virtual environment?"
        ) from exc
    execute_from_command_line(sys.argv)

if __name__ == '__main__':
    main()

代码工作,我只是不明白为什么

0lvr5msh

0lvr5msh1#

一句话:www.example.com是django管理命令的入口点。manage.py is the entry point for django management commands.
再用几句话来解释上下文:
django框架被设计成由一个像apache这样的web服务器来"服务",它通过www.example.com接口链接到这个web服务器,所以apache会得到一个web请求,然后通过mod_wsgi调用django。wsgi.py interface. So Apache would get a web request and then call django via the mod_wsgi.

.... a rough path:
Browser 
 -> Web Request
  -> Apache (mod_wsgi)
   -> python interpreter
    -> wsgi.py 
     -> setup django (settings.py/DB connection ...) 
      -> url routing 
       -> view
       <- return response HTTP
     <- Apache
    <- Browser

在某些情况下,在服务器上用命令行执行管理或开发任务是有用的,而不是通过浏览器。

  • 将模型移植到数据库
  • 运行本地开发服务器进行调试
  • 以简单的方式测试代码
  • 通过python脚本将数据从遗留数据库移动到django模型....

django的这个"入口"是www.example.com脚本,通过它可以启动所谓的"管理命令manage.py script via that the so called "management commands" are started

terminal "python manage.py xyz" 
 -> import and setup django (settings.py/DB connection ...) 
  -> call the xyz management command
   ->

管理命令始终位于文件夹app_name/management/command/www.example.com中xyz.py
并且必须实施

class Command(BaseCommand):

    def add_arguments(self, parser):
        ....

    def handle(self, *args, **kwargs):
        ....
        here is the code

另请参见https://docs.djangoproject.com/en/4.1/howto/custom-management-commands/

相关问题