Using psycopg2 in Azure Functions

If you wish to interface with any PostgreSQL DB within Azure functions, you may have tried to include psycopg2 in the requirements.txt file. Your code may work perfectly locally, but you may get an error similar to the following when you check Azure Function logs:

ImportError: libpq.so.5: cannot open shared object file: No such file or directory

The extended path of the error will finally point to the

import psycopg2

line in your code. What is the solution?

Simple. Use psycopg2-binary instead of psycopg2. The only change you need to make is in requirements.txt.

Instead of

psycopg2==2.8.6

Use

psycopg2-binary==2.8.6

Of course, you may want to check the latest version, or use an older version depending on your requirements. If you don’t wish to dig any further, you can stop reading here.

However, if you do wish to know why psycopg2 doesn’t work but psycopg2-binary works, here’s the explanation:

psycopg2 is not a standalone package. It is built using libpq-dev package, during installation. Now, psycopg2 depends on the host OS to find this library. And Azure Functions don’t have libpq, as the error above clearly indicates.

You may be wondering that we can perhaps simply add libpq-dev to requirements.txt. But that doesn’t work. You will get the error:

No matching distribution found for libpq-dev

Thus, the required solution is to use a package of psycopg2 that doesn’t require libpq. psycopg2-binary is exactly that. I hope this provided a satisfactory explanation.

You can refer to the following links for more details:

  1. https://access.crunchydata.com/documentation/psycopg2/2.7.3/install.html
  2. https://pypi.org/project/libpq-dev/
  3. https://stackoverflow.com/questions/61054203/cant-install-libpq-dev

If you liked this article, you may check out other articles related to Azure here: https://iotespresso.com/category/azure/


If you are planning to appear for the Azure Administrator Exam Certification, check out this course on Udemy.

1 comment

Leave a comment

Your email address will not be published.