Connecting via psycopg2 and the bit.io Python SDK

Below is an example of how to connect to bit.io using our python library via psycopg2. This library supports generation of pre-configured psycopg2 connections to bit.io

The snipped below shows how to upload a csv file to a new or existing table using a psycopg2 connection generated using the bitdotio Python library.

import bitdotio
import pandas as pd

# This is to provide a reproducible csv,
# you can ignore and use your own csv
df_test = pd.DataFrame(
    data=[[0, 1, 2], [3, 4, 5]],
    columns=['a', 'b', 'c'])
df_test.to_csv('test.csv', index=False)

# Connect with bit.io API key credentials
b = bitdotio.bitdotio("<YOUR_API_KEY>")

# Create table, if it does not already exist
create_table_sql = """
    CREATE TABLE test (
      a integer,
      b integer,
      c integer
    )
    """

with b.get_connection("<YOUR_DATABASE_NAME>") as conn:
    cursor = conn.cursor()
    cursor.execute(create_table_sql)
    
# Copy csv from a local file
copy_table_sql = """
    COPY test FROM stdin WITH CSV HEADER DELIMITER as ',';
    """

with open('test.csv', 'r') as f:
    with b.get_connection("<YOUR_DATABASE_NAME>") as conn:
        cursor = conn.cursor()
        cursor.copy_expert(sql=copy_table_sql, file=f)
        
# Note: you can also create a new repo from Python using the API, if needed

View in Github and download .py file here.


Did this page help you?