When I quit Django manage.py runserver with Ctrl+C, do threads running HTTP request finish properly or are they interrupted in the middle?
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
Done.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
Slept for: 10sso 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With