【问题标题】:Django: No module named 'psycopg2' when launching migrations to herokuDjango:启动迁移到heroku时没有名为“psycopg2”的模块
【发布时间】:2020-02-27 05:43:53
【问题描述】:

我是 django 的新手,我创建了一个网站,现在我处于部署阶段,一切都运行良好,直到启动从数据库迁移到服务器。我会告诉你我从一开始所做的一切

我的项目结构

OC_project8/
    pur_beurre/
        catalog/
            dumps/
                catalog.json
            ...        # other classic file
        media/
        pur_beurre/
            static/
                .gitignore
            ...        # other classic file
        static/
        templates/
        users/
        manage.py
        Procfile
    venv/
    requirements.txt/
        certifi==2019.9.11
        chardet==3.0.4
        coverage==4.5.4
        dj-database-url==0.5.0
        Django==2.2.6
        django-debug-toolbar==2.0
        gunicorn==19.9.0
        idna==2.8
        mysqlclient==1.4.4
        Pillow==6.2.0
        pytz==2019.3
        requests==2.22.0
        sqlparse==0.3.0
        urllib3==1.25.6
        whitenoise==4.1.4
    .gitignore/

所有命令都在虚拟环境中运行,例如:

(venv) ~/OC_project8/pur_beurre$ sudo apt-get install python-psycopg2

在运行命令 git push heroku master 之前,我已经完成了所有必要的步骤 (git commit, heroku create my-app ...) 如果您需要有关这些步骤的更多详细信息,请告诉我。

运行命令 git push heroku master 后,我遇到了这个错误:

....

remote:        Collecting pkg-resources==0.0.0 (from -r /tmp/build_cac68f54540915062647a425c52dc61b/requirements.txt (line 11)) 
remote:          Could not find a version that satisfies the requirement pkg-resources==0.0.0 (from -r/tmp/build_cac68f54540915062647a425c52dc61b/requirements.txt (line 11)) (from versions: )
remote:        No matching distribution found for pkg-resources==0.0.0 (from -r /tmp/build_cac68f54540915062647a425c52dc61b/requirements.txt (line 11))
remote:  !     Push rejected, failed to compile Python app.
remote: 
remote:  !     Push failed
remote: Verifying deploy...
remote: 
remote: !       Push rejected to pur-beurre-oc8.
remote: 
To https://git.heroku.com/pur-beurre-oc8.git
! [remote rejected] master -> master (pre-receive hook declined)
error: impossible de pousser des références vers 'https://git.heroku.com/pur-beurre-oc8.git'

我在 stackoverflow 中看到我必须这样做:

pip uninstall pkg-resources==0.0.0

在我提交之后:

git add requirements.txt
git commit -m "uninstalling pkg-resources==0.0.0"

现在git push heroku master 工作正常,但是当我访问我的网站时出现错误:Apllication error。我不知道我是不是湿透了,但我想是因为我还没有完成数据库的迁移。

所以我运行命令heroku run python pur_beurre/manage.py migrate

现在我遇到了这个错误:

Running python pur_beurre/manage.py migrate on ⬢ pur-beurre-oc8... up, run.4138 (Free)
Traceback (most recent call last):
  File "/app/.heroku/python/lib/python3.6/site-packages/django/db/backends/postgresql/base.py", line 20, in <module>
    import psycopg2 as Database
ModuleNotFoundError: No module named 'psycopg2'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "pur_beurre/manage.py", line 21, in <module>
    main()
  File "pur_beurre/manage.py", line 17, in main
    execute_from_command_line(sys.argv)
  File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line
    utility.execute()
  File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/__init__.py", line 357, in execute
    django.setup()
  File "/app/.heroku/python/lib/python3.6/site-packages/django/__init__.py", line 24, in setup
    apps.populate(settings.INSTALLED_APPS)
  File "/app/.heroku/python/lib/python3.6/site-packages/django/apps/registry.py", line 114, in populate
    app_config.import_models()
  File "/app/.heroku/python/lib/python3.6/site-packages/django/apps/config.py", line 211, in import_models
    self.models_module = import_module(models_module_name)
  File "/app/.heroku/python/lib/python3.6/importlib/__init__.py", line 126, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 994, in _gcd_import
  File "<frozen importlib._bootstrap>", line 971, in _find_and_load
  File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 665, in _load_unlocked
  File "<frozen importlib._bootstrap_external>", line 678, in exec_module
  File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
  File "/app/.heroku/python/lib/python3.6/site-packages/django/contrib/auth/models.py", line 2, in <module>
    from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager
  File "/app/.heroku/python/lib/python3.6/site-packages/django/contrib/auth/base_user.py", line 47, in <module>
    class AbstractBaseUser(models.Model):
  File "/app/.heroku/python/lib/python3.6/site-packages/django/db/models/base.py", line 117, in __new__
    new_class.add_to_class('_meta', Options(meta, app_label))
  File "/app/.heroku/python/lib/python3.6/site-packages/django/db/models/base.py", line 321, in add_to_class
    value.contribute_to_class(cls, name)
  File "/app/.heroku/python/lib/python3.6/site-packages/django/db/models/options.py", line 204, in contribute_to_class
    self.db_table = truncate_name(self.db_table, connection.ops.max_name_length())
  File "/app/.heroku/python/lib/python3.6/site-packages/django/db/__init__.py", line 28, in __getattr__
    return getattr(connections[DEFAULT_DB_ALIAS], item)
  File "/app/.heroku/python/lib/python3.6/site-packages/django/db/utils.py", line 201, in __getitem__
    backend = load_backend(db['ENGINE'])
  File "/app/.heroku/python/lib/python3.6/site-packages/django/db/utils.py", line 110, in load_backend
    return import_module('%s.base' % backend_name)
  File "/app/.heroku/python/lib/python3.6/importlib/__init__.py", line 126, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "/app/.heroku/python/lib/python3.6/site-packages/django/db/backends/postgresql/base.py", line 24, in <module>
    raise ImproperlyConfigured("Error loading psycopg2 module: %s" % e)
django.core.exceptions.ImproperlyConfigured: Error loading psycopg2 module: No module named 'psycopg2'

我不知道为什么会出现此错误,因为 psycopg2 是使用 PostgreSQL 所需的库,而我正在使用 MySQL,这是我的 settings.py:

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',   
        'NAME': 'openfoodfacts',             
        'USER': 'root',
        'PASSWORD': 'my-password',        
        'HOST': '',                    
        'PORT': '5432',                         
    }
}

无论如何,在出现此错误后,我尝试安装 psycopg2:

pip install psycopg2

但我还有另一个错误:

Collecting psycopg2
  Downloading https://files.pythonhosted.org/ packages/84/d7/6a93c99b5ba4d4d22daa3928b983cec66df4 536ca50b22ce5dcac65e4e71/psycopg2-2.8.4.tar.gz (377kB)
    100% |████████████████████████████████| 378kB 1.8MB/s 
    Complete output from command python setup.py egg_info:
    Traceback (most recent call last):
      File "<string>", line 1, in <module>
      File "/home/rouizi/OC_project8/venv/lib/python3.6/site-packages/setuptools/__init__.py", line 12, in <module>
        import setuptools.version
      File "/home/rouizi/OC_project8/venv/lib/python3.6/site-packages/setuptools/version.py", line 1, in <module>
        import pkg_resources
    ModuleNotFoundError: No module named 'pkg_resources'

    ----------------------------------------
Command "python setup.py egg_info" failed with error code 1 in /tmp/pip-build-gf4fxs4k/psycopg2/

也许我收到此错误是因为我卸载了 在开始 pkg-resources !但我尝试重新安装 pkg-resources:

sudo apt-get install --reinstall python-pkg-resources

我重新运行命令pip install psycopg2,但仍然有同样的错误

通过谷歌搜索,我发现这里@9​​87654321@ 需要运行这个命令:

wget https://bootstrap.pypa.io/ez_setup.py -O - | python

然后我重新运行命令pip install psycopg2,但我还有另一个错误:

Collecting psycopg2
  Using cached https://files.pythonhosted.org/ packages/84/d7/6a93c99b5ba4d4d22daa3928b983cec66df 4536ca50b22ce5dcac65e4e71/psycopg2-2.8.4.tar.gz
    Complete output from command python setup.py egg_info:
    running egg_info
    creating pip-egg-info/psycopg2.egg-info
    writing pip-egg-info/psycopg2.egg-info/PKG-INFO
    writing dependency_links to pip-egg-info/psycopg2.egg-info/dependency_links.txt
    writing top-level names to pip-egg-info/psycopg2.egg-info/top_level.txt
    writing manifest file 'pip-egg-info/psycopg2.egg-info/SOURCES.txt'

    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.

    For further information please check the 'doc/src/install.rst' file (also at
    <http://initd.org/psycopg/docs/install.html>).


    ----------------------------------------
Command "python setup.py egg_info" failed with error code 1 in /tmp/pip-build-sglmdb2o/psycopg2/

如果我运行命令which pg_config 它什么都不会返回,但经过一些研究我喜欢这里pg_config executable not found 有必要运行这个命令:

sudo apt-get install libpq-dev

现在which pg_config 回复这个:

/usr/bin/pg_config

于是我重新运行pip install psycopg2,又出现了一个错误:

Collecting psycopg2
  Using cached https://files.pythonhosted.org/ packages/84/d7/6a93c99b5ba4d4d22 daa3928b983cec66df4536ca50b22ce5dcac65e4e71/psycopg2-2.8.4.tar.gz
Building wheels for collected packages: psycopg2
  Running setup.py bdist_wheel for psycopg2 ... error
  Complete output from command /home/rouizi/OC_project8/venv/bin/python3 -u -c "import setuptools, tokenize;__file__='/tmp/pip-build-lu4ihs81/psycopg2/setup.py';f=getattr(tokenize,    
'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" bdist_wheel -d /tmp/tmphgjf714ppip-wheel- --python-tag cp36:
  usage: -c [global_opts] cmd1 [cmd1_opts] [cmd2 [cmd2_opts] ...]
     or: -c --help [cmd1 cmd2 ...]
     or: -c --help-commands
     or: -c cmd --help

  error: invalid command 'bdist_wheel'

  ----------------------------------------
  Failed building wheel for psycopg2
  Running setup.py clean for psycopg2
Failed to build psycopg2
Installing collected packages: psycopg2
  Running setup.py install for psycopg2 ... error



           #I cut here because it's very long


    Traceback (most recent call last):
      File "<string>", line 1, in <module>
      File "/tmp/pip-build-lu4ihs81/psycopg2/setup.py", line 611, in <module>
        'Documentation': 'http://initd.org/psycopg/docs/',
      File "/home/rouizi/OC_project8/venv/lib/python3.6/site-packages/setuptools/__init__.py", line 129, in setup
        return distutils.core.setup(**attrs)
      File "/usr/lib/python3.6/distutils/core.py", line 148, in setup
        dist.run_commands()
      File "/usr/lib/python3.6/distutils/dist.py", line 955, in run_commands
        self.run_command(cmd)
      File "/usr/lib/python3.6/distutils/dist.py", line 974, in run_command
        cmd_obj.run()
      File "/home/rouizi/OC_project8/venv/lib/python3.6/site-packages/setuptools/command/install.py", line 61, in run
        return orig.install.run(self)
      File "/usr/lib/python3.6/distutils/command/install.py", line 601, in run
        self.run_command(cmd_name)
      File "/usr/lib/python3.6/distutils/cmd.py", line 313, in run_command
        self.distribution.run_command(command)
      File "/usr/lib/python3.6/distutils/dist.py", line 974, in run_command
        cmd_obj.run()
      File "/home/rouizi/OC_project8/venv/lib/python3.6/site-packages/setuptools/command/install_scripts.py", line 17, in run
        import setuptools.command.easy_install as ei
      File "/home/rouizi/OC_project8/venv/lib/python3.6/site-packages/setuptools/command/easy_install.py", line 47, in <module>
        from setuptools.sandbox import run_setup
      File "/home/rouizi/OC_project8/venv/lib/python3.6/site-packages/setuptools/sandbox.py", line 15, in <module>
        import pkg_resources.py31compat
    ModuleNotFoundError: No module named 'pkg_resources.py31compat'

    ----------------------------------------
Command "/home/rouizi/OC_project8/venv/bin/python3 -u -c "import setuptools, tokenize;__file__='/tmp/pip-build-lu4ihs81/psycopg2/setup.py';f=getattr(tokenize, 'open', open)(__file__)
;code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" install --record /tmp/pip-eya3xv3b-record/install-record.txt --single-version-externally-managed 
--compile --install-headers /home/rouizi/OC_project8/venv/include/site/python3.6/psycopg2" failed with error code 1 in /tmp/pip-build-lu4ihs81/psycopg2/

我试过这个命令:

sudo apt-get install --reinstall python-setuptools

现在,当我尝试运行 pip install psycopg2 时,他返回给我:

Requirement already satisfied: psycopg2 in /home/rouizi/OC_project8/venv/lib/python3.6/site-packages

但是如果我尝试运行命令heroku run python pur_beurre/manage.py migrate 我仍然有错误:

django.core.exceptions.ImproperlyConfigured: Error loading psycopg2 module: No module named 'psycopg2'

但是如果我运行sudo apt-get install python-psycopg2 它可以工作,但运行heroku run python pur_beurre/manage.py migrate 时仍然出现错误 由于我仍然有同样的错误,所以我尝试卸载 psycopg2:

sudo pip uninstall psycopg2

但它告诉我:

The directory '/home/rouizi/.cache/pip/http' or its parent directory is not owned by the current user and the cache has been disabled. Please check the permissions and owner of that directory. If executing pip with sudo, you may want sudo's -H flag.
Not uninstalling psycopg2 at /usr/lib/python2.7/dist-packages, outside environment /usr  

我被困了一天没有找到解决办法,希望你能帮忙

对不起,我的帖子太长了,我的拼写错误

【问题讨论】:

  • 这太过分了。我认为你需要指出一些你可以想到并关注的具体问题,而不是给出整个历史。我可能是错的,但这是一个非常多的信息需要涉水
  • 只是让您知道 apt-get 与虚拟环境无关。当您运行sudo apt-get install python-psycopg2 时,它会将python2 版本安装到系统环境中。您可以使用apt show psycopg2 命令验证这一点。我认为可能会有所帮助,激活您的虚拟环境运行pip3 list | grep psycopg 看看会返回什么。如果它什么也没返回,请尝试pip3 install psycopg2-binary。我以前不使用二进制文件时遇到过问题。
  • @Arctor pip3 列表 | grep psycopg 返回此:psycopg2 (2.8.4) 以及此:弃用:默认格式将在未来切换到列。您可以使用 --format=(legacy|columns) (或在 [list] 部分下的 pip.conf 中定义 format=(legacy|columns))来禁用此警告。
  • edit您的问题并向我们展示您的requirements.txt。另外,请确认您没有Pipfile 和/或Pipfile.lock 文件。
  • @Chris 我没有 Pipfile 或 Pipfile.lock

标签: python django heroku psycopg2


【解决方案1】:

我解决了我的问题! 我运行了命令pip install psycopg2,它返回给我错误:

ModuleNotFoundError: No module named 'pkg_resources.py31compat'

但如果我尝试重新运行命令pip install psycopg2,它会说:

Requirement already satisfied: psycopg2 in /home/rouizi/OC_project8/venv/lib/python3.6/site-packages

所以我尝试提交我的更改:

pip freeze > requirements.txt
git add requirements.txt
git commit -m "installing psycopg2"
git push heroku master

现在heroku run python pur_beurre/manage.py migrate 工作正常。

我不知道为什么,因为我有错误,如果有人解释就好了

【讨论】:

    猜你喜欢
    • 2021-03-14
    • 2012-11-17
    • 1970-01-01
    • 1970-01-01
    • 2017-09-17
    • 2023-03-25
    • 2012-01-08
    • 2012-09-22
    • 2014-02-05
    相关资源
    最近更新 更多