【django】(定制 django)启动服务器时调用默认浏览器打开项目首页

版权声明:本文为博主原创文章,转载请注明出处。 https://blog.csdn.net/qq_29757283/article/details/85552041

(定制 django)启动服务器时调用默认浏览器打开项目首页

写这篇 blog 的思想是:写(代码)都写了,不总结发篇 blog 出来等着过春节吗?

写了对于 python 调用默认浏览器的方式也方便自己参考(不用去翻某个练习过的项目的源码)。

判断正确的进程

django 会启动两个进程,这一点我在我的另一篇 blog 中提到过了1
该篇 blog 也有了 solution。

这里就直接照搬,也贴出代码方便参考:

def Is_child_processing():
    from multiprocessing.connection import Listener
    from queue import Queue
    from threading import Thread

    q = Queue()

    def lock_system_port(_port):
        nonlocal q  # it's OK without this announce line 
        try:
            listener = Listener(("", _port))
            q.put(False)
        except Exception:  # port be used by parent
            # traceback.print_exc()
            q.put(True)
            return  # child don't listen

        while True:
            serv = listener.accept()  # just bind the port.

    t = Thread(target=lock_system_port, args=(62771, ))
    t.setDaemon(True)
    t.start(); del t;
    return q.get()

调用系统默认浏览器

#
# open browser(like $ jupyter notebook)
# parse argv Reference from `execute_from_command_line`
def enable_browser_with_delay(argv, _t=None):
    try:
        subcommand = argv[1]  # manage.py runserver
    except IndexError:
        pass

    if subcommand == 'runserver' and '--noreload' not in argv:
        try:
            parser_port = argv[2]
            port_with_colon = parser_port[parser_port.index(":"):]
        except (IndexError, ValueError):
            port_with_colon = ":8000"
        finally:
            import webbrowser
            import time
            if not _t: _t = 0.5
            time.sleep(_t)  # you may no need delay, if your machine run faster
            webbrowser.open_new("http://localhost" + port_with_colon)  # open project index page
            # webbrowser.open_new("http://localhost" + port_with_colon + "/app_name/")  # open app index page

修改 manage.py 定制启动 server 时浏览器打开首页

[...]

if __name__ == '__main__':
    os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'source.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

    if Is_child_processing():
        import threading
        t = threading.Thread(target=enable_browser_with_delay, args=(sys.argv, 1))
        t.start(); del t;

    execute_from_command_line(sys.argv)

上面的 [...] 表示代码省略。

因为你当然知道如何将上面 Is_child_processingenable_browser_with_delay 两个函数如何放在 manage.py 文件中。


Reference


  1. 【django】定制 django - 运行你的独立的不死线程 ↩︎

猜你喜欢

转载自blog.csdn.net/qq_29757283/article/details/85552041