pythondatabasepsycopg3

Working on new version of psycopg 3 and while installing psycopg[c] it wont install at all


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!


Solution

  • 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