porton porton - 2 months ago 10
Python Question

`manage.py runserver` and Ctrl+C (Django)

When I quit Django

manage.py runserver
with Ctrl+C, do threads running HTTP request finish properly or are they interrupted in the middle?

ht_ ht_
Answer

TL;DR running HTTP requests are stopped when Ctrl+C is hit on the django dev server

I thought your question is really interesting and investigated:

I made a view that takes 10 seconds to execute and after that sends a response. To test for your behaviour I stopped the development-server manage.py runserver using Ctrl+C and checked for the results.

My base test:

class TestView ( generic.View ):
    def get ( self, request ):
        import time
        time.sleep(10)
        response = HttpResponse('Done.')
        return response
  • Normal execute (10s runtime): Displays the msg Done.
  • interrupted execute (Ctrl+C while the request is running): Browser error, the host cannot be reached

so far everything as expected. But I played around a little bit, because Ctrl+C in python is not a full stop, but actually handled rather conveniently: As soon as Ctrl+C is hit, a KeyboardInterrupt aka an Exception is risen (equivalent to this):

raise KeyboardInterrupt()

so in your command-line based programm you can put the following:

try:
    some_action_that_takes_a_while()
except KeyboardInterrupt:
    print('The user stopped the programm.')

ported to django the new view looks like that:

def get ( self, request ):
    import time
    slept_for = 0
    try:
        for i in range( 100 ):
            slept_for += 0.1
            time.sleep( 0.1 )
    except KeyboardInterrupt:
        pass

    response = HttpResponse( 'Slept for: ' + str( slept_for ) + 's' )
    return response
  • Normal execute (10s runtime): Displays the msg Slept for: 10s
  • interrupted execute (Ctrl+C while the request is running): Browser error, the host cannot be reached

so no change in behaviour here. out of interest i changed one line, but the result didn't change; i used

slept_for = 1000*1000

instead of

time.sleep( 0.1 )

so to finally answer your question: on Ctrl+C the dev server shuts down immediately and running http-requets are not finished.

Comments