Flask应用部署Heroku:绝对路径转相对路径的问题
Hey there, I’ve been in your exact spot—building a Flask app on Windows that runs perfectly locally, only to hit a "folder not found" error when deploying to Heroku. The culprit is almost always those Windows-specific absolute paths clashing with Heroku’s Linux environment. Let’s fix this:
Replace Windows absolute paths with project-relative paths
Heroku uses Linux, so paths likeC:\my-app\assetswon’t make sense there. Instead, build paths relative to your app’s root directory usingos.pathproperly. Here’s the go-to code snippet:import os # Get the absolute path of your Flask app's root folder BASE_DIR = os.path.dirname(os.path.abspath(__file__)) # Build the path to your target folder using relative folder names TARGET_FOLDER = os.path.join(BASE_DIR, "your-target-folder", "subfolder-if-needed")os.path.abspath(__file__)grabs the full path of your main script (likeapp.py),os.path.dirnamemoves up one level to your project root, andos.path.joinautomatically uses the right path separator (no more mixing/and\).Ensure your folder is actually pushed to Heroku
Check your.gitignorefile—if your target folder is listed here, Git won’t send it to Heroku, so the server can’t find it. If the folder has static files you need, remove it from.gitignoreand commit the folder to Git. If it’s a runtime-generated folder, use Heroku’s temporary/tmpdirectory instead (since Heroku’s filesystem resets every time your app restarts).Debug the path directly on Heroku
Add a quick debug route to see exactly what’s happening on the server:@app.route("/check-path") def check_path(): return f""" Target Folder Path: {TARGET_FOLDER}<br> Does Folder Exist? {os.path.exists(TARGET_FOLDER)}<br> Current Working Directory: {os.getcwd()} """Deploy this, visit the route, and you’ll instantly see if the path is correct and if the folder exists. This catches tiny typos in folder names that are easy to miss locally.
Stop hardcoding path separators
Never manually concatenate paths likeBASE_DIR + "/assets"—always useos.path.join. It handles Windows’ backslashes and Linux’s forward slashes flawlessly, so your code works everywhere.
内容的提问来源于stack exchange,提问作者NotSure

