尝试使用psycopg2从wsgi文件连接到PostgreSQL时遇到500服务器错误。
import psycopg2
def application(environ, start_response):
try:
conn = psycopg2.connect("database = testdb, user = postgres, password = secret")
execept:
print "I am unable to connect to the database"
status = '200 OK'
output = 'Hello Udacity, Robert!'
response_headers = [('Content-type', 'text/plain'), ('Content-Length', str(len(output)))]
start_response(status, response_headers)
return [output]
答案 0 :(得分:1)
创建数据库(在我的情况下为“ udacity”),一个表(在我的情况下为“ hello”)和人口(在我的情况下为“ Hello world”)之后:
# psql environment
CREATE DATABASE udacity;
CREATE TABLE hello(
word text);
INSERT INTO hello VALUES ('Hello world');
您必须安装python依赖项:
# shell environment
sudo apt install python-psycopg2 libpq-dev
sudo apt install python-pip
pip install psycopg2
然后,下一个 myapp.wsgi 脚本对我有用:
import psycopg2
def application(environ, start_response):
status = '200 OK'
output = 'Original message'
response_headers = [('Content-type', 'text/plain'), ('Content-Length', str(len(output)))]
start_response(status, response_headers)
# DB connection
try:
connection = psycopg2.connect("dbname='udacity' user='ubuntu' host='localhost' password='udacity'")
cursor = connection.cursor()
cursor.execute("""SELECT * from hello""")
rows = cursor.fetchall()
for row in rows:
output = row[0]
except:
output = 'E: Python script'
return [output]