Heroku上的Django应用可访问但无法提交更改且日志显示崩溃
Hey there, let's get your Django app back up and running smoothly! That bad magic number error you're hitting is a common hiccup with Python's compiled bytecode files (.pyc), and here's how to fix it step by step:
What's causing this?
This error pops up for one of two main reasons:
- Your local Python version doesn't match the one Heroku is using, creating incompatible compiled bytecode files.
- Corrupted or outdated
.pycfiles were accidentally committed to your Git repo, and Heroku is trying to use those broken files during deployment.
Step-by-Step Fixes
1. Make sure Python versions match
First, confirm your local Python version aligns with what Heroku is running:
- Check your local version:
python --version - Check Heroku's version:
heroku run python --version -a dagenssalg - If they don't match, update the
runtime.txtfile in your project root to specify the correct version (e.g.,python-3.9.16), then commit this change.
2. Clean up local bytecode files
Delete all compiled .pyc files and cache directories on your local machine:
# Delete all .pyc files find . -name "*.pyc" -delete # Delete all __pycache__ folders find . -name "__pycache__" -delete
If you're on Windows, you can manually delete these files and folders through File Explorer instead.
3. Update .gitignore to avoid future issues
Make sure your .gitignore excludes bytecode files so you don't accidentally commit them again. Add these lines if they're missing:
*.pyc __pycache__/
4. Re-deploy to Heroku
Commit your cleanup changes and push to Heroku:
git add . git commit -m "Fix bad magic number error by cleaning pyc files and aligning Python versions" git push heroku main # Replace 'main' with your branch name if it's different
5. Purge Heroku's cache (if the error sticks around)
Sometimes Heroku holds onto cached old bytecode. Clear the cache and re-deploy:
heroku repo:purge_cache -a dagenssalg git push heroku main
After finishing these steps, check the logs again with heroku logs --tail to confirm the app starts up without the magic number error.
内容的提问来源于stack exchange,提问作者Kresten

