在Vercel部署Django应用时遇python setup.py egg_info错误求解决
解决Vercel部署Django应用时psycopg2安装失败的问题
问题描述
部署Django应用到Vercel时,执行pip install安装依赖失败,核心报错信息如下:
Error: pg_config executable not found. pg_config is required to build psycopg2 from source. Please add the directory containing pg_config to the $PATH or specify the full executable path with the option: python setup.py build_ext --pg-config /path/to/pg_config build ... or with the pg_config option in 'setup.cfg'. If you prefer to avoid building psycopg2 from source, please install the PyPI 'psycopg2-binary' package instead.
解决方案
方案1:改用psycopg2-binary预编译包(推荐)
- 打开项目根目录的
requirements.txt文件,将其中的psycopg2替换为psycopg2-binary - 本地执行
pip install psycopg2-binary更新依赖,将修改后的requirements.txt提交到代码仓库 - 重新触发Vercel部署,此时pip会直接安装预编译好的二进制包,无需编译环境即可解决问题
方案2:在Vercel构建环境中安装PostgreSQL依赖(适合必须用psycopg2源码包的场景)
- 在项目根目录创建
build.sh脚本,内容如下:#!/bin/bash # 安装PostgreSQL开发依赖 apt-get update && apt-get install -y libpq-dev # 安装Python依赖 pip3.9 install --disable-pip-version-check --target . --upgrade -r requirements.txt # 执行Django静态文件收集等部署命令(根据项目需求调整) python manage.py collectstatic --noinput - 给脚本添加执行权限:
chmod +x build.sh - 在项目根目录创建
vercel.json文件,配置构建命令指向脚本:{ "buildCommand": "./build.sh" } - 将
build.sh和vercel.json提交到代码仓库,重新触发Vercel部署
内容的提问来源于stack exchange,提问作者Luca Vasapolli
相关产品推荐
相关产品推荐

