H.P*_*oli 6 postgresql python-3.x flask-sqlalchemy
我是python的新手.我必须使用PostgreSQL作为数据库开发一个简单的Flask应用程序(在我的本地Ubuntu 16.4中).
我安装了pgadmin,Flask,SQLAlchemy和postgres,这也是我的应用代码:
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql://dbUserName:userNamePassword@localhost/dbName'
db = SQLAlchemy(app)
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(80), unique=True)
email = db.Column(db.String(120), unique=True)
def __init__(self, username, email):
self.username = username
self.email = email
def __repr__(self):
return '<User %r>' % self.username
@app.route('/')
def index():
return "Hello Flask"
if __name__ == "__main__":
app.run()
Run Code Online (Sandbox Code Playgroud)
我还在pgAdmin中创建了一个数据库和新用户(并在我的代码中用相关变量替换它们),但是当我尝试在python shell中测试这段代码时,我发现错误.
我的python代码:
from app import db
Run Code Online (Sandbox Code Playgroud)
结果:
/home/user/point2map2/venv/lib/python3.5/site-packages/flask_sqlalchemy/__init__.py:839: FSADeprecationWarning: SQLALCHEMY_TRACK_MODIFICATIONS adds significant overhead and will be disabled by default in the future. Set it to True or False to suppress this warning.
'SQLALCHEMY_TRACK_MODIFICATIONS adds significant overhead and '
Run Code Online (Sandbox Code Playgroud)
然后:
db.create_all()
Run Code Online (Sandbox Code Playgroud)
结果:
(psycopg2.OperationalError) FATAL: password authentication failed for user "dbUserName"
FATAL: password authentication failed for user "dbUserName"
Run Code Online (Sandbox Code Playgroud)
经过大量的论坛搜索,我找到了这个指南:
在你的pg_hba.conf中
Run Code Online (Sandbox Code Playgroud)# IPv4 local connections: # TYPE DATABASE USER CIDR-ADDRESS METHOD host all all 127.0.0.1/32 trust
但它不适合我.
我陷入了同样的错误。对我来说,问题是我没有为psql用户设置密码。在此处查看具有答案的类似问题:https : //askubuntu.com/questions/413585/postgres-password-authentication-fails
我做的时候就解决了
ALTER USER db_username PASSWORD 'new_password'
Run Code Online (Sandbox Code Playgroud)
对 sqlalchemy 代码进行一些调试后,我发现 sqlalchemy 使用的 url 是解码后的 url 字符串(至少对于 postgres 而言)。这意味着,如果连接字符串中有子字符串,例如%34
,则 sqlalchemy 连接字符串将为4
,因为这是 url 解码的字符串。这个问题的解决方案很简单:只需将%
连接字符串中所有出现的 替换为%25
,因为这是 的 url 编码%
。其代码很简单:
from sqlalchemy import create_engine
connection_string_orig = "postgres://user_with_%34_in_the_string:pw@host:port/db"
connection_string = connection_string_orig.replace("%", "%25")
engine = create_engine(connection_string)
print(engine.url) # should be identical to connection_string_orig
engine.connect()
Run Code Online (Sandbox Code Playgroud)
这可能并不能解决每个人的问题,但了解这一点还是有好处的。
归档时间: |
|
查看次数: |
6634 次 |
最近记录: |