|
| 1 | +# Django Explain Errors Middleware |
| 2 | + |
| 3 | +This Django middleware captures errors and exceptions, sends them to OpenAI for explanation, and prints the explanation to stdout when debug mode is enabled. It uses an environment variable to securely manage the OpenAI API key. |
| 4 | + |
| 5 | +## Features |
| 6 | + |
| 7 | +- Captures Django errors and exceptions |
| 8 | +- Uses OpenAI to explain the error |
| 9 | +- Securely manages the OpenAI API key using environment variables |
| 10 | + |
| 11 | +## Installation |
| 12 | + |
| 13 | +1. Install django-explain-errors by running: |
| 14 | +```bash |
| 15 | +pip install django-explain-errors |
| 16 | +``` |
| 17 | + |
| 18 | +2. **Add the middleware to your Django project**: |
| 19 | + |
| 20 | + - Open your `settings.py` file and add the middleware to the `MIDDLEWARE` list. Ensure that the middleware is added last in the list: |
| 21 | + |
| 22 | + ```python |
| 23 | + MIDDLEWARE = [ |
| 24 | + ... |
| 25 | + 'explain_errors.ExplainErrorsMiddleware', |
| 26 | + ] |
| 27 | + ``` |
| 28 | + |
| 29 | +4. **Set up environment variables**: |
| 30 | + |
| 31 | + - Create a `.env` file in your project’s root directory and add your OpenAI API key. Alternatively, you can list the API key in `settings.py`: |
| 32 | + |
| 33 | + ```plaintext |
| 34 | + OPENAI_API_KEY=your_openai_api_key_here |
| 35 | + ``` |
| 36 | + |
| 37 | +## Usage |
| 38 | + |
| 39 | +1. **Ensure DEBUG is set to True**: |
| 40 | + |
| 41 | + Open your `settings.py` file and set: |
| 42 | + |
| 43 | + ```python |
| 44 | + DEBUG = True |
| 45 | + ``` |
| 46 | + |
| 47 | +2. **Trigger an error in your Django application**: |
| 48 | + |
| 49 | + The middleware will capture the error, send it to OpenAI for explanation, and print the explanation to stdout. |
| 50 | + |
| 51 | +## Example |
| 52 | + |
| 53 | +Here is an example of how to use the middleware in a Django project: |
| 54 | + |
| 55 | +```python |
| 56 | +# settings.py |
| 57 | +
|
| 58 | +DEBUG = True |
| 59 | +
|
| 60 | +MIDDLEWARE = [ |
| 61 | + ... |
| 62 | + 'explain_errors.ExplainErrorsMiddleware', |
| 63 | +] |
| 64 | +
|
| 65 | +# .env |
| 66 | +
|
| 67 | +OPENAI_API_KEY=your_openai_api_key_here |
| 68 | +``` |
| 69 | + |
| 70 | +When an error occurs, you will see an explanation printed to stdout. |
| 71 | + |
| 72 | +## License |
| 73 | + |
| 74 | +This project is licensed under the MIT License. See the [LICENSE](LICENSE) file for details. |
| 75 | + |
| 76 | +## Contributing |
| 77 | + |
| 78 | +Contributions are welcome! Please open an issue or submit a pull request for any improvements or bug fixes. |
| 79 | + |
| 80 | +## Acknowledgements |
| 81 | + |
| 82 | +- [Django](https://www.djangoproject.com/) |
| 83 | +- [OpenAI](https://www.openai.com/) |
| 84 | +- [python-dotenv](https://github.com/theskumar/python-dotenv) |
0 commit comments