Execute code when Django starts ONCE only?

前端 未结 7 1483
终归单人心
终归单人心 2020-11-22 13:55

I\'m writing a Django Middleware class that I want to execute only once at startup, to initialise some other arbritary code. I\'ve followed the very nice solution posted by

7条回答
  •  星月不相逢
    2020-11-22 14:36

    if you want print "hello world" once time when you run server, put print ("hello world") out of class StartupMiddleware

    from django.core.exceptions import MiddlewareNotUsed
    from django.conf import settings
    
    class StartupMiddleware(object):
        def __init__(self):
            #print "Hello world"
            raise MiddlewareNotUsed('Startup complete')
    
    print "Hello world"
    

提交回复
热议问题