How to get raven to report Django runscript exceptions to Sentry? - django

My Django web app logs exceptions to Sentry via raven. I also run a number of scripts (via manage.py runscript) as cron jobs. Right now any exceptions in those scripts are not being reported to Sentry. How do I set such reporting up?

As of version 5.3.1 of raven-python it should correctly patch Django's BaseCommand.execute, which effectively will handle errors in these commands (unless that parent call is never made).

For those out there that:
still have an issue of raven not patching itself for django management commands correctly
have Django==1.6.11
haven raven==5.12.0
I have found a fix that works for me.
The problem seems to be that raven is not patching BaseCommand.execute by the time it is called by Django. So to fix that, I make sure BaseCommand.execute is patched right away. I've updated my manage.py file to include the following lines:
from raven.contrib.django.management import patch_cli_runner
patch_cli_runner()
My final manage.py file looks like this:
#!/usr/bin/env python
from os.path import abspath
from os.path import dirname
import os
import sys
if __name__ == "__main__":
# add the ../ directory to the os path, so that we can find
# app.settings below
sys.path.insert(0, os.path.abspath(os.path.join(dirname(abspath(__file__)), '..')))
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "app.settings")
from django.core.management import execute_from_command_line
from raven.contrib.django.management import patch_cli_runner
patch_cli_runner()
execute_from_command_line(sys.argv)

Related

How to write a stand-alone Python script working with Django modules?

In PyCharm, I created a blank new Django app. Having created some models and issued manage.py makemigrations and manage.py migrate, I tried to write a standalone script that would populate the database with initial data. In its imports I wrote:
from MyApp.models import Model1, Model2, …
Sadly, running this script in PyCharm throws an exception: django.core.exceptions.ImproperlyConfigured: Requested setting DEFAULT_TABLESPACE, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings.
I Googled this exception, and found an answer in SO https://stackoverflow.com/a/27455703/4385532 advising to put this in the top of my script:
import os
os.environ['DJANGO_SETTINGS_MODULE'] = 'mysite.settings'
So I did. Sadly, this didn’t fix the issue. Now I am greeted with another exception:
django.core.exceptions.AppRegistryNotReady: Models aren't loaded yet.
What should I do?
Make sure you also do:
import django
django.setup()
To load your models.
Documentation: https://docs.djangoproject.com/en/1.10/topics/settings/#calling-django-setup-is-required-for-standalone-django-usage

Applying Django 1.6 project settings in PyDev

I have no problems running the python shell with the python manage.py -shell command in the terminal; I can import my modules and make queries on the database and so on. However, in PyDev, even though I can import modules, when I try to access the data stored in my SQLite database, I get this message:
ImproperlyConfigured: settings.DATABASES is improperly configured.
Please supply the ENGINE value.
Since my project's settings are ok (the site works fine locally), it must have to do with Pydev not applying the project configs. The sequence of starting up the Django/python shell is as follows:
from django.conf import settings; settings.configure()
from django.core import management
import XX.settings as settings
management.setup_environ(settings) # This throws an error as setup_environ
# setup_environ is deprecated in Django 1.6
The last 3 lines are hard-coded (and were, I gather, working pre-Django 1.6)
I thought doing something like:
from django.conf import settings as djangoSettings
from XX import settings
djangoSettings.configure(settings)
But then I get this error:
ImportError: Could not import settings ''XX.settings'' (Is it on
sys.path? Is there an import error in the settings file?): No module
named 'XX.settings'
And yes, the path is in sys.path.
Any help greatly appreciated.

Django: Manage.py runserver no error, but mod_wsgi report cannot import name connection

When testing my django website by python manage.py runserver 0.0.0.0:8000, there is no error.
But if I deploy it to production with apache and mod_wsgi, it reports error cannot import name connection.
I find some other questions like django 1.4 database router - "cannot import name connection" suggesting adding from django.db import connections into settings.py.
But I found adding this import can prevent this error, but it also disables database router.
I think it may due to different running environment between manage.py runserver and WSGI.
This is how my wsgi.py looks like
import os
import sys
sys.path.insert(0,"/home/my/myweb")
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mywebsite.settings")
from django.core.wsgi import get_wsgi_application
application = get_wsgi_application()
How can I fix this bug?
My python version is 2.7 and django version is 1.4.3
Edit 1:
My OS is CentOS 6.4, on this server:
If I run it using python manage.py runserver 0.0.0.0:8000, no error.
If I remove database router, it can work under WSGI.
But database router and WSGI cannot work together.
Any advice is appreciated.
Edit 2:
Thanks to #Graham Dumpleton, I figured it out by myself.
This is the wsgy.py that works for me.
import sys
sys.path.insert(0, '/home/my/myweb')
from mywebsite import settings
import django.core.management
django.core.management.setup_environ(settings)
utility = django.core.management.ManagementUtility()
command = utility.fetch_command('runserver')
command.validate()
import django.conf
import django.utils
django.utils.translation.activate(django.conf.settings.LANGUAGE_CODE)
import django.core.handlers.wsgi
application = django.core.handlers.wsgi.WSGIHandler()
Usually caused by using a mix of imports where some imports are via the site package and some don't. You can add:
sys.path.insert(0,"/home/my/myweb/mywebsite")
and that may help.
For a bit of a discussion of the problem see:
http://blog.dscpl.com.au/2010/03/improved-wsgi-script-for-use-with.html

django automate syncdb

I'm working on a project that includes a django server, and also a setup module.
The user will be configuring their system to run my program, which includes a django webserver element along with other items. I'm working on a setup module that assists the user in getting all of the settings correct and sets up all of the appropriate files. One of the things that I'd like to be during the setup process is essentially a "manage.py syncdb" command that creates an appropriate SQLite file and table from nothing.
I could grab the code found in manage.py and directly stick it into my setup module appropriately, but I'm not sure if there's a better approach that I'm missing - along the lines of two lines consisting of:
import django.something
import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mysite.settings")
django.something.syncdb()
Or something of the sort. Am I just missing something here?
This should do it:
import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mysite.settings")
from django.core import management
management.call_command('syncdb', interactive=False)
You can also do
import os
import settings
from django.core.management.commands import syncdb
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mysite.settings")
syncdb.Command().execute(noinput=True)

Cannot import django.core

I am trying to setup django with fastcgi on apache. Django is installed and seems to be running correctly but I am having problems with setting up fastcgi.
I decided to test out my dispatch.fcgi script in the interactive python shell line by line and the following line:
from django.core.servers.fastcgi import runfastcgi
results in the following error:
ImportError: No module named core.servers.fastcgi
I can import django with no problem but import django.core gives yet another ImportError (No module named core).
How can I go about ensuring that I can import django.core. If I can import django then in must be on my path, and so why can I not import core?
You probably have a file/folder called django somewhere in your path, that isn't the actual path.
try this
import sys
sys.path
And then check everything in that output to see if there is a file/folder called django(.py) somewhere.
If so, change the path (sys.path = ['/path/to/directory/below/django/install'] + sys.path) or move/rename the file.
Probably you have django.py module in your working directory or in any other that is in python path.
For anyone having this problem and coming across this question like I did, it turns out that fastcgi support has been removed as of Django 1.9, thus you will get this import error if trying to import it. Refer Using Django with virtualenv, get error ImportError: No module named 'django.core.servers.fastcgi'