在Heroku中将psycopg2与Python连接 [英] Connecting psycopg2 with Python in Heroku
问题描述
我一直在尝试将python 3脚本连接到Heroku中没有Django的PostgresSQL数据库(psycopg2
).
I've been trying for some days to connect my python 3 script to PostgresSQL database(psycopg2
) in Heroku, without Django.
我找到了一些文章和相关问题,但我不得不投入大量时间来获得我认为应该非常简单的内容,即使对于像我这样的新手也是如此.
I found some article and related questions, but I had to invest a lot of time to get something that I thought should be very straightforward, even for a newbie like me.
我最终以某种方式使它起作用,但希望发布问题(和答案)将有助于其他人更快地实现它.
I eventually made it work somehow but hopefully posting the question (and answer) will help other people to achieve it faster.
当然,如果有人有更好的方法,请分享.
Of course, if anybody has a better way, please share it.
正如我所说,我有一个python脚本,我想使它使用Heroku从云中运行.不涉及Django(仅是脚本/抓取工具).
As I said, I had a python script that I wanted to make it run from the cloud using Heroku. No Django involved (just a script/scraper).
一开始我发现有帮助的文章,即使它们还不够:
Articles that I found helpful at the beginning, even if they were not enough:
推荐答案
主要步骤:
1. Procfile
Procfile
必须是:
worker: python3 folder/subfolder/myscript.py
2. Heroku插件
附件Heroku Postgres :: Database
必须添加到heroku帐户中的相应个人应用中.
Add-on Heroku Postgres :: Database
has to be added to the appropriate personal app in the heroku account.
为确保正确设置,此非常有用.
To make sure this was properly set, this was quite helpful.
3.具有数据库连接的Python脚本
最后,要在我的python脚本myscript.py
中创建连接,我选择了本文作为参考,并将其修改为适用于Python 3:
Finally, to create the connection in my python script myscript.py
, I took this article as a reference and adapted it to Python 3:
import psycopg2
import urllib.parse as urlparse
import os
url = urlparse.urlparse(os.environ['DATABASE_URL'])
dbname = url.path[1:]
user = url.username
password = url.password
host = url.hostname
port = url.port
con = psycopg2.connect(
dbname=dbname,
user=user,
password=password,
host=host,
port=port
)
要创建新数据库,请此SO问题对此进行解释.关键行是:
To create a new database, this SO question explains it. Key line is:
con.set_isolation_level(ISOLATION_LEVEL_AUTOCOMMIT)
这篇关于在Heroku中将psycopg2与Python连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!