首页 > 解决方案 > Python 包和方法未导入

问题描述

我用几个方法构建了一个简单的类,以便在使用 Python 将数据加载到 Postgres 时让我的生活更轻松一些。我还尝试打包它,以便我可以 pip 安装它(只是为了实验,以前从未这样做过)。

import psycopg2
from sqlalchemy import create_engine
import io


class py_psql:

    engine = None

    def engine(self, username, password, hostname, port, database):
        connection = 'postgresql+psycopg2://{}:{}@{}:{}/{}'.format(ntid.lower(), pw, hostname, port, database)
        self.engine = create_engine(connection)


    def query(self, query):
        pg_eng = self.engine
        return pd.read_sql_query(query, pg_eng)


    def write(self, write_name, df, if_exists='replace', index=False):
        mem_size = df.memory_usage().sum()/1024**2
        pg_eng = self.engine

        def write_data():
            df.head(0).to_sql(write_name, pg_eng, if_exists=if_exists,index=index)
            conn = pg_eng.raw_connection()
            cur = conn.cursor()
            output = io.StringIO()
            df.to_csv(output, sep='\t', header=False, index=False)
            output.seek(0)
            contents = output.getvalue()
            cur.copy_from(output, write_name, null="")
            conn.commit()

        if mem_size > 100:
            validate_size = input('DataFrame is {}mb, proceed anyway? (y/n): '.format(mem_size))
            if validate_size == 'y':        
                write_data()
            else:
                print("Canceling write to database")
        else:
            write_data()

我的包目录如下所示:

py_psql
    py_psql.py
    __init__.py
setup.py

我的init .py 是空的,因为我在其他地方读到我能够做到这一点。我不是这里的专家......

我能够 pip 安装该包并将其导入,如果我要将此类粘贴到 python shell 中,我将能够执行类似的操作

test = py_psql()
test.engine(ntid, pw, hostname, port, database)

并让它创建 sqlalchemy 引擎。但是,当我在 pip 安装后导入它时,我什至无法初始化 py_psql 对象:

>>> test = py_psql()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'module' object is not callable

>>> py_psql.engine(ntid, pw, hostname, port, database)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: module 'py_psql' has no attribute 'engine'

我确定我在这里搞砸了一些明显的东西,但是我在研究这个时发现包装过程相当混乱。我做错了什么?

标签: pythonclasspackaging

解决方案


你确定你在 pip install 后正确地导入了你的包吗?

例如:

from py_psql.py_psql import py_psql
test = py_psql()
test.engine(ntid, pw, hostname, port, database)

推荐阅读