0

I am working on psycopg 3 and not 2. Here is my code that I am trying to work on:

from fastapi import FastAPI, Response, status, HTTPException
from fastapi.params import Body
from pydantic import BaseModel
from typing import Optional
from random import randrange
import psycopg
import psycopg2
from psycopg2.extras import RealDictCursor
import time

app = FastAPI()

while True:
    try:
        conn = psycopg.connect(host = 'localhost', database = 'fastapi', user = 'postgres',
                               password = 'islamabad', cursor_factory=RealDictCursor)
        cursor = conn.cursor()
        print("Database successfully connected!")
        break
    except Exception as error:
        print("Connection Failed")
        print("Error: ", error)
        time.sleep(2)

But I am getting the following error:

ImportError: no pq wrapper available.
Attempts made:
- couldn't import psycopg 'c' implementation: No module named 'psycopg_c'
- couldn't import psycopg 'binary' implementation: No module named 'psycopg_binary'
- couldn't import psycopg 'python' implementation: libpq library not found

So I read somewhere to install psycopg[c] and psycopg[binary] Now when I am installing psycopg[c] it is giving the following error:

  Using cached psycopg-c-3.1.2.tar.gz (616 kB)
  Installing build dependencies ... done
  Getting requirements to build wheel ... done
  Preparing metadata (pyproject.toml) ... error
  error: subprocess-exited-with-error
  
  × Preparing metadata (pyproject.toml) did not run successfully.
  │ exit code: 1
  ╰─> [6 lines of output]
      running dist_info
      writing C:\Users\themr\AppData\Local\Temp\pip-modern-metadata-cr8kpz5q\psycopg_c.egg-info\PKG-INFO
      writing dependency_links to C:\Users\themr\AppData\Local\Temp\pip-modern-metadata-cr8kpz5q\psycopg_c.egg-info\dependency_links.txt
      writing top-level names to C:\Users\themr\AppData\Local\Temp\pip-modern-metadata-cr8kpz5q\psycopg_c.egg-info\top_level.txt
      couldn't run 'pg_config' --includedir: [WinError 2] The system cannot find the file specified
      error: [WinError 2] The system cannot find the file specified
      [end of output]

  note: This error originates from a subprocess, and is likely not a problem with pip.
error: metadata-generation-failed

× Encountered error while generating package metadata.
╰─> See above for output.

note: This is an issue with the package mentioned above, not pip.
hint: See above for details.

I can instead work on psycopg2 which is working but I want to shift to the new version. So, help out please!

snakecharmerb
  • 47,570
  • 11
  • 100
  • 153
  • Have you tried running just `pip install psycopg[binary]`? Installing with `[c]` builds the installation from source using a C compiler, which is generslly complicated (especially on whindows, which tou seem to be using). – M.O. Sep 30 '22 at 22:44
  • Yes I have. But just now I did it again. Now I am getting the long error which I cant type so here is the last three lines: `To fix this you could try to: 1. loosen the range of package versions you've specified 2. remove package versions to allow pip attempt to solve the dependency conflict ` – Hasan Abdul Ghaffar Oct 01 '22 at 08:21
  • That looks like a version resolution error. What does your requirements file look like? – M.O. Oct 01 '22 at 09:28
  • dont know how to share that file but i wrote down some of them here. hope it will help: `bcrypt==4.0.0 certifi==2022.9.24 cffi==1.15.1 charset-normalizer==2.1.1 fastapi==0.52.0 graphene==3.1.1 h11==0.14.0 idna==3.4 itsdangerous==2.1.2 Jinja2==3.1.2 Mako==1.2.3 MarkupSafe==2.1.1 passlib==1.7.4 psycopg==3.1.2 psycopg2==2.9.3 pyasn1==0.4.8 pycparser==2.21 pydantic==1.10.2 python-dotenv==0.21.0 python-jose==3.3.0 python-multipart==0.0.5 six==1.16.0 SQLAlchemy==1.4.41 starlette==0.13.2` – Hasan Abdul Ghaffar Oct 02 '22 at 04:40
  • Try removing the version constraint on `psycopg` and try again. If you get a resolution error again, it should say which package is the issue, and which versions it tried. – M.O. Oct 02 '22 at 10:31

1 Answers1

1

There are 3 ways of installing psycopg 3:

  1. Binary installation

This method will install a self-contained package with all the libraries required to connect python to your Postgres database. Install packages by running:

pip install "psycopg[binary]"
  1. Local installation

To use psycopg for a production site, this is the most preferred way of installing the psycopg adapter. Install packages by running:

pip install "psycopg[c]"

3)Pure python installation

In case you want to use pycopg for a test environment and for debugging purposes, use this method of installation. Install packages by running:

pip install psycopg

To use the pure python installation, your system must contain the libpq library. libpq library is what the PostgreSQLcommand line client uses to connect to the database. Install the library by running:

sudo apt install libpq5

Based on your code it seems that you are working on the python API development course. It would be best to use the 3rd method of installation as i assume you are using it for learning purposes. Therefore your code should look something like this:

from typing import Optional
from fastapi import Body, FastAPI, Response, status, HTTPException
from pydantic import BaseModel
from random import randrange
import psycopg
#from psycopg import ClientCursor
import time 

app = FastAPI()

try:
    conn = psycopg.connect(dbname='fastapi',user='postgres',password='islamabad', cursor_factory=RealDictCursor)
    cursor = conn.cursor()
    print("Database connection successful!")
    break
except Exception as error:
    print("Connection failed")
    print("Error: ", error)

    time.sleep(2)

For more information kindly check the docs at: https://www.psycopg.org/psycopg3/docs/basic/install.html

Ian Raburu
  • 26
  • 2