All jobs

Migrate From raven to sentry-sdk in a Django App

Yes. An agent replaces each raven Client, middleware and settings entry with sentry-sdk, proves every error path still reports, and opens a pull request.

Run this on RushOpens the console with this prompt ready to send, in a Project that has your repository.

What the agent does

The raven package is the old Sentry client for Python, and its replacement, sentry-sdk, has a different shape: one sentry_sdk.init() call at startup and integrations that hook frameworks for you, where raven had a Client object you created and passed around. The work is finding every place the old client was wired in by hand. In a Django app like feedhq/feedhq there are more of those than a search for import raven suggests. settings.py appends raven.contrib.django to INSTALLED_APPS when SENTRY_DSN is in the environment. wsgi.py wraps the application in raven.middleware.Sentry(application, Client()). feeds/forms.py and sync_pubsubhubbub.py each build a new Client() inside an except block and call captureException().

Two more are structural. feeds/management/commands/__init__.py defines a SentryCommand base class whose handle runs handle_sentry and, on any exception in production, reports it and returns, so the command exits cleanly; ten management commands inherit from it. And rqworker.py registers sentry_handler as an RQ exception handler that logs the failure with structlog and then sends it to Sentry with the job's id, function, arguments and description as extra.

The agent adds one sentry_sdk.init() to settings.py and removes the INSTALLED_APPS entry and the WSGI wrapper, because the SDK's Django integration turns itself on when Django is installed and instruments requests without middleware. init() reads SENTRY_DSN from the environment and does nothing without one, which is the same switch the app already uses. Each Client().captureException() becomes sentry_sdk.capture_exception(). In SentryCommand it keeps the report-and-return behaviour exactly, since cron jobs that now exit non-zero would be a change nobody asked for, and names it in the pull request as a decision for the reviewer.

The RQ handler needs a choice. The SDK's RQ integration supports the pinned rq==0.7.1 and reports failed jobs itself with the job id, function and description, but it sends arguments only when sending personal data is enabled, where the old handler always sent them. The agent keeps the structlog line, lets the integration do the reporting, and states the difference. It edits requirements.in and regenerates requirements.txt with pip-compile, which also drops contextlib2, present only for raven. Then it checks the result without a Sentry account: it initialises the SDK with a transport that records events in memory, raises inside a view, a management command and a job, and counts one event for each.

Start it with one API call

POST https://api.phoenix.so/o/{org}/sessions with this body:

{
  "agent": "claude",
  "input": "Migrate this project from the raven package to sentry-sdk. Find every use of raven: imports, raven.contrib entries in INSTALLED_APPS, RAVEN_CONFIG, WSGI or other middleware, logging handlers that point at raven, Client() objects created inline, and any helper or base class that reports errors (management commands, task or job exception handlers). List them all before changing anything. Add a single sentry_sdk.init() at startup that keeps the current way of switching reporting on (for example a SENTRY_DSN environment variable) and carries over release, environment and sample-rate options if the old config set them. Replace captureException and captureMessage calls with capture_exception and capture_message, and move extra and tags data to the SDK's scope API. Remove wiring the SDK's integrations make unnecessary. Where an existing helper swallows the exception after reporting it, keep that behaviour and point it out. For a job queue the SDK has an integration for, either use the integration or keep the custom handler, not both, and say what data each one sends. Update every manifest and regenerate compiled requirement files with the tool that produced them. Check that the Python and framework versions the project supports are ones the SDK supports and report any that are not. Verify without a real DSN: use a transport or before_send hook that records events, trigger one error per integration point, and report how many events each produced. Run the existing tests if the services they need can be started. Open a pull request.",
  "resources": [
    {
      "url": "https://github.com/your-org/your-app"
    }
  ]
}
  1. Get an API key. In the console, open Settings, then API keys, and create a key for your org. Send it in the Authorization header as a Bearer token.
  2. Send the request. POST the body in request.json to https://api.phoenix.so/o/{org}/sessions, with your repository as the resources URL. The run starts in its own cloud sandbox.
  3. Read what came back. Follow the run on its live stream or wait for the run.completed webhook, then read the result and its trajectory.

What comes back

A pull request that touches each file where raven appeared and removes more than it adds. For feedhq that means settings.py, wsgi.py, the command base class, rqworker.py, forms.py, sync_pubsubhubbub.py, and both requirements files. The description opens with the inventory of integration points and, beside each, how an error there reaches Sentry after the change: through the Django integration, through the RQ integration, or through an explicit capture_exception().

It then lists what behaves differently. Job arguments are no longer attached unless you enable them. Events are grouped by the new SDK's rules, so existing issues in Sentry may split or merge after the first deploy. The project's tox.ini still lists py34 and py35, and the current SDK requires Python 3.6 or later, so those environments cannot install it; the agent reports that instead of pinning an old SDK without being asked.

A reviewer checks the event counts from the recording transport, one per path and none doubled, and decides the two open questions: whether swallowed command errors should stay swallowed, and whether job arguments are safe to send.

Run it on every repository that still imports raven

This is a one-time job per codebase, so start it from a list. Search your organisation for raven in requirements files, and for each repository found send POST /o/{org}/sessions with the body above and that repository in resources, adding a request_id that is a UUID v5 of the repository name so a rerun of the script starts nothing new. A key runs up to its max_concurrent runs at once, four by default, and the rest are created queued and start as slots free, so the script needs no pacing of its own.

Set a webhook_url on the key to collect results. Each run the key starts posts run.completed or run.failed with its execution_id and a session_url, and reading that session gives the pull request to review.

The use case this job follows, with its automation and trigger: Upgrade dependencies weekly.

Why run it on Rush?

Error reporting is code that only runs when something else has gone wrong, which makes a broken migration invisible until the day it matters. The check that prevents that is dull: raise an exception at every integration point and count what arrives. The agent does it in its own sandbox with a recording transport, so no test events reach your real Sentry project, and the commands and their output stay in the session transcript for the reviewer.

The inventory is the other reason. Hand-wired clients hide in base classes, worker entry points and except blocks that a rename by search does not understand. An agent that reads the repository before editing finds the command base class and the job handler, and treats them as design decisions to preserve or question, where a mechanical replacement would leave them half converted.

Frequently asked questions

Do I still need raven.contrib.django in INSTALLED_APPS?

No. sentry-sdk is not a Django app. Calling sentry_sdk.init() in your settings module is the whole setup, and the Django integration enables itself when Django is importable. The RAVEN_CONFIG dict goes away; its values become arguments to init().

What replaces client.captureException()?

sentry_sdk.capture_exception(), called with no arguments inside an except block or with the exception object. There is no client to construct or pass around. captureMessage becomes capture_message, and extra or tags arguments are set on the scope before capturing.

Does sentry-sdk read SENTRY_DSN from the environment like raven did?

Yes. With no dsn argument, init() uses the SENTRY_DSN environment variable, and with no DSN at all the SDK sends nothing. Code that guarded every capture with a check for that variable keeps working, and most of those guards can be removed.

Will my existing Sentry issues keep their history?

The events go to the same project, but the new SDK builds stack traces and fingerprints its own way, so some issues will appear as new ones after the switch. Plan the deploy for a quiet period and expect a short burst of new-issue alerts.

Can the agent test this without my Sentry credentials?

Yes, and it should. The SDK accepts a custom transport or a before_send hook, so the agent records events in memory and asserts on them. Nothing is sent to Sentry, and no DSN is needed in the run.

More jobs like this: Upgrade dependencies weekly

Keep reading