Hope this helps những của những người có thể làm điều này trong python.
Tôi đã tạo một tập lệnh/giải pháp làm việc hoàn chỉnh trên GitHubGist - xem URL bên dưới đoạn mã này.
# ref: https://stackoverflow.com/questions/8546759/how-to-check-if-a-postgres-user-exists
check_user_cmd = ("SELECT 1 FROM pg_roles WHERE rolname='%s'" % (deis_app_user))
# our create role/user command and vars
create_user_cmd = ("CREATE ROLE %s WITH LOGIN CREATEDB PASSWORD '%s'" % (deis_app_user, deis_app_passwd))
# ref: https://stackoverflow.com/questions/37488175/simplify-database-psycopg2-usage-by-creating-a-module
class RdsCreds():
def __init__(self):
self.conn = psycopg2.connect("dbname=%s user=%s host=%s password=%s" % (admin_db_name, admin_db_user, db_host, admin_db_pass))
self.conn.set_isolation_level(0)
self.cur = self.conn.cursor()
def query(self, query):
self.cur.execute(query)
return self.cur.rowcount > 0
def close(self):
self.cur.close()
self.conn.close()
db = RdsCreds()
user_exists = db.query(check_user_cmd)
# PostgreSQL currently has no 'create role if not exists'
# So, we only want to create the role/user if not exists
if (user_exists) is True:
print("%s user_exists: %s" % (deis_app_user, user_exists))
print("Idempotent: No credential modifications required. Exiting...")
db.close()
else:
print("%s user_exists: %s" % (deis_app_user, user_exists))
print("Creating %s user now" % (deis_app_user))
db.query(create_user_cmd)
user_exists = db.query(check_user_cmd)
db.close()
print("%s user_exists: %s" % (deis_app_user, user_exists))
Provides idempotent remote (RDS) PostgreSQL create role/user from python without CM modules, etc.
Bạn có nhớ được xây dựng trong tiện ích dòng lệnh để thực hiện SQL là gì? Cuối cùng tôi muốn thực hiện và lấy kết quả từ trình bao nếu có thể. – m33lky
'psql' là lệnh. Nhưng nếu bạn đang nói về tiện ích dòng lệnh 'createuser' (bạn rõ ràng là vậy, tôi không nhận thấy thiếu không gian trong' tạo user' lúc đầu), thì có thể dễ dàng bỏ qua trạng thái thoát và đầu ra chuyển hướng thành '/ dev/null'. –
@ m33lky: Hoặc bạn có thể kiểm tra giá trị trả lại của lệnh này trong shell (như người dùng postgres): 'psql postgres -tAc" SELECT 1 FROM pg_roles WHERE rolname = 'USR_NAME' "'. Lợi nhuận '1' nếu tìm thấy và không có gì khác. –