【发布时间】:2015-07-16 07:10:27
【问题描述】:
我正在尝试用 Python 编写一个小网络服务。我使用 Heroku 和他们的 postgre-DB 服务(免费)。
但是我遇到了一个小但很烦人的问题。当我尝试在数据库中搜索某些内容时,程序会连接到数据库,但会继续尝试,即使它第一次运行也是如此。
调用search_image函数的部分:
def handle_send(update):
link = databasecon.search_image(update["message"]["text"], update)
connect_to_database 函数:
def connect_to_db():
global __is_connected
if "DATABASE_URL" not in os.environ or __is_connected == True:
print("Environment-variable missing or already connected")
else:
urllib.parse.uses_netloc.append("postgres")
url = urllib.parse.urlparse(os.environ["DATABASE_URL"])
con = psycopg2.connect(
database=url.path[1:],
user=url.username,
password=url.password,
host=url.hostname,
port=url.port
)
if con != None:
__is_connected = True
return con
search_image 函数:
def search_image(image_name, update):
db_con = connect_to_db()
cur = db_con.cursor()
query = """select link from mm_image where id=%s"""
cur.execute(query, (image_name))
result = cur.fetchone()
if result != None:
image_link = str(result[0])
disconnect_from_db(db_con)
return image_link
else:
disconnect_from_db(db_con)
return "Not found"
这就是调用 handle_send 函数后日志的外观: http://i.stack.imgur.com/pTZcF.png
这里有什么问题?
这是我第一个用 Python 编写的正确程序,所以如果这是一个明显的错误,我很抱歉:S
【问题讨论】:
标签: python database postgresql heroku psycopg2