python - 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'
我确定我在这里搞砸了一些明显的东西,但是我在研究这个时发现包装过程相当混乱。我做错了什么?
解决方案
你确定你在 pip install 后正确地导入了你的包吗?
例如:
from py_psql.py_psql import py_psql
test = py_psql()
test.engine(ntid, pw, hostname, port, database)
推荐阅读
- c# - 我想比较应该不区分大小写并忽略所有空格的字符串
- google-apps-script - Google Apps 脚本,将单元格 A1 添加到 A2 以在 A2 中显示,然后清除 A1
- javascript - 在反应原生中单击保存按钮时编写具有旋转/翻转功能的视频
- python - AttributeError: '_io.BufferedReader' 对象没有属性 'load'
- php - 是否可以在不使用 javascript(Ajax) 和 cookie 的情况下使用 PHP 获取客户端时区?
- javascript - 如何在html表中循环并更改javascript中每个单元格的值
- qt - 如何让 QNetworkProxy 在第一个请求中发送用户名和密码?
- php - 在 mysqli 列中显示选定的值
- telnet - Windows Server 中的网络负载平衡不转发来自特定服务器的 telnet 请求
- firebase - 尝试从 firebase 集成到 jira(atlassian)时,我得到 403