Using Raygun’s automatic Python error tracking with FlaskPosted May 1, 2014 | 2 min. (409 words)
Earlier this week we received an email from a user requesting a sample of how to hook up a Flask web app to Raygun, and get automatic error tracking – we were more than happy to oblige!
For the uninitiated, Flask is a micro web framework for Python with a simple core that’s easy to dive in to. It has all the expected goodies: a dev server/debugger, a templating engine (Jinja2), route specifying as Decorators on methods, sessions, unicode, etc. The Hello World is pretty minimal:
import sys from flask import Flask app = Flask(__name__) @app.route('/') def index(): return 'Hello, world!'
Where the micro part comes in is it doesn’t include tons of extras you may not need resulting in it being incredibly lightweight and usable out-of-the-box. For instance, it doesn’t include an ORM by default, but there’s Flask-SQLAlchemy if you want one – or you could replace the templating system (e.g. with Mako).
Sending Flask errors to Raygun
The framework also has nice exception handing support, where you can place a decorator on a method that gets passed the HTTP status code you want to handle. Within these, you can use our official Raygun4PY provider to send the error object to the Raygun API. Here’s a complete example that will catch runtime exceptions:
import sys from flask import Flask from raygun4py import raygunprovider app = Flask(__name__) raygun = raygunprovider.RaygunSender("paste_your_api_key_here") @app.route('/') def hello_world(): raise StandardError("A Flask Error") return "I won't be hit" @app.errorhandler(500) def internal_error(error): send_exception() return 'I will be hit due to a 500 error: ' + error.args def send_error_to_raygun(): err = sys.exc_info() raygun.send_exception(err, err, err) if __name__ == '__main__': app.run()
Picking up 404 routing errors and having them sent to Raygun is just as easy:
@app.errorhandler(404) def not_found(error): send_exception() return 'Page Not Found'
Python error tracking
If you use Django for your Python web development needs, there’s also a third-party provider available here as a Django middleware. And you can of course use the vanilla Raygun4PY provider anywhere, from local scripts to networked applications.
Got a Raygun Crash and Error Reporting account already, and want to hook your Python app up to it? You’ll find the steps detailed in your Raygun dashboard once you create a new app. If you haven’t yet created an account, click here to start your 14-day free trial, no credit card needed. And if you’d like us to create other samples for your favorite framework, let us know in the comments below!