Python/Django + Apache on Webfaction
December 29, 2009 | Comments | Related to Apache Django PythonI recently purchased a shared hosting account from webfaction to host my new Django powered blog and I've had a nice experience so far. As a rookie to mod_wsgi, I found one thing quite annoying and that was having to restart my apache instance every time I made some changes to python code. Another problem was changing the debug mode of Django which for some reason I did quite frequently. I needed to SSH/FTP every time change the debug mode and restart apache. It might not be a problem for most of you, but for someone using something as bad as the BSNL Mobile Internet Card, even connecting to the SSH server is a 5-10 minute affair sometimes. If you are facing a similar problem, here is what to do.
Create two new URL patters and methods
MYSITE.URLS
(r'^restart/$','mysite.views.restart'),
(r'^debug/$','mysite.views.debug'),
MYSITE.VIEWS
def restart(request):
if request.user.is_superuser:
import xmlrpclib
server = xmlrpclib.ServerProxy('https://api.webfaction.com/')
sid, account = server.login('WEBFACTION_USERNAME', 'PASSWORD')
system(sid,'/home/USERNAME/webapps/APPNAME/apache2/bin/restart')
return HttpResponseRedirect('/')
else:
return render_to_response('401.html')
def debug(request):
if request.user.is_superuser:
import xmlrpclib
server = xmlrpclib.ServerProxy('https://api.webfaction.com/')
sid, account = server.login('WEBFACTION_USERNAME', 'PASSWORD')
from mysite import settings
if settings.DEBUG:
server.replace_in_file(sid, 'PATH_TO_SETTINGS.PY', ('DEBUG = True','DEBUG = False'))
else:
server.replace_in_file(sid, 'PATH_TO_SETTINGS.PY', ('DEBUG = False','DEBUG = True'))
return HttpResponseRedirect('/')
else:
return render_to_response('401.html')
Now you can point to domain.com/debug to change Django's debug mode and domain.com/restart to restart your apache instance.
This allows me to quickly switch to Debug when a problem occurs without using FTP or SSH. I'm sure you can do something similar with any other kind of deployment which demands apache restarts. Link to Webfaction API
I don't know how safe it is to totally rely on IS_SUPERUSER variable.
The request.user does not come from the http header (users browser) which makes it quite secure but still I'm no security expert (yet), so you should verify the security issues first.
blog comments powered by Disqus