我正在使用SQLalchemy作为Python项目,我希望有一个整洁的连接字符串来访问我的数据库.例如:
engine = create_engine('postgres://user:pass@host/database')
Run Code Online (Sandbox Code Playgroud)
问题是我的密码包含一系列特殊字符,在我尝试连接时会被解释为分隔符.
我意识到我可以创建一个对象然后传递我的凭据,如下所示:
drivername = 'postgres',
username = 'user',
password = 'pass',
host = 'host',
database = 'database'
Run Code Online (Sandbox Code Playgroud)
但是如果可能的话,我宁愿使用连接字符串.
所以要清楚,是否可以编码我的连接字符串或连接字符串的密码部分 - 以便可以正确解析它?
我正在尝试从我的 Flask 应用程序连接到 postgresql 中的数据库,但在浏览器中收到以下消息
sqlalchemy.exc.OperationalError: (psycopg2.OperationalError) FATAL: password authentication failed for user "flask_admin"
FATAL: password authentication failed for user "flask_admin"
(Background on this error at: http://sqlalche.me/e/e3q8)
Run Code Online (Sandbox Code Playgroud)
我已将环境变量设置DATABASE_URL
为该语句下方的内容
postgresql://flask_admin:example@dev@18@localhost/flask_dev
Run Code Online (Sandbox Code Playgroud)
这是我的代码config.py
import os
basedir = os.path.abspath(os.path.dirname(__file__))
class Config:
DEBUG = False
SECRET_KEY = os.environ.get('SECRET_KEY') or \
'\xfe\xccT\nn\x80\xe3\xfd\xc6\xf8\xd6\xab\xd8\x82\xc2\x1f'
SQLALCHEMY_COMMIT_ON_TEARDOWN = True
SQLALCHEMY_TRACK_MODIFICATIONS = False
@staticmethod
def init_app(app):
pass
class DevelopmentConfig(Config):
DEBUG = True
SQLALCHEMY_DATABASE_URI = os.environ.get('DATABASE_URL') or \
'sqlite:///' + os.path.join(basedir, 'test.db')
class ProductionConfig(Config):
DEBUG = False
SQLALCHEMY_DATABASE_URI = …
Run Code Online (Sandbox Code Playgroud)