典型的圣杯应用程序定义了多个路由,但是如何将其正确连接到RDS以便我可以保存POST数据或从数据库中检索数据?我已经通过RDS面板创建了一个数据库;我只是不确定如何从Chalice访问它。
是否只是让每条路由都通过user / pass连接到给定的RDS主机?
例如,
from chalice import Chalice
import psycopg2
app = Chalice(app_name='test')
db_user = 'test'
db_pass = 'password'
db_host = 'https://.....'
db_port = 5432
@app.route('/save_data')
def save_data():
with psycopg2.connect(user=db_user, password=db_pass, ...) as conn:
with conn.cursor() as cur:
cur.execute("INSERT INTO test (num, data) VALUES (%s, %s)", (1,2))
@app.route('/get_data')
def get_data():
with psycopg2.connect(user=db_user, password=db_pass, ...) as conn:
with conn.cursor() as cur:
cur.execute("SELECT * FROM test")
@app.route('/something')
def something():
with psycopg2.connect(user=db_user, password=db_pass, ...) as conn:
with conn.cursor() as cur:
cur.execute(....) # some other query
如果是这样,是否有更简单的方法来处理它,而不是每次都必须指定数据库连接?是否存在与此相关的奇怪会话/竞赛条件?
或者,如果我完全关闭,从Chalice路线连接到RDS的正确方法是什么?
答案 0 :(得分:0)
我实际上已经在我的Chalice应用程序中设置了这个。我所做的是设置参数存储并在那里存储我不同的数据库连接并将它们调用到Chalice中。
我创建了一个名为Parameters.py的文件并将其放入其中:
import boto3
def getParameter(param_name):
# Create the SSM Client
ssm = boto3.client('ssm', region_name='us-east-1')
# Get the requested parameter
response = ssm.get_parameters(
Names=[
param_name,
],
WithDecryption=True
)
# Store the credentials in a variable
credentials = response['Parameters'][0]['Value']
return credentials
然后我可以这样称呼它:
def dbInsert(query, stage):
stageParm = stage + "_database"
parm = Parameters.getParameter(stageParm)
pJson = json.loads(parm)
repli = pJson["replication"]
dbName = pJson["database"]
writeEndPoint = repli["write"]["host"]
writeUsername = repli["write"]["username"]
writePassword = repli["write"]["password"]
try:
conn = pymysql.connect(
writeEndPoint,
user=writeUsername,
passwd=writePassword,
db=dbName,
connect_timeout=5)
except Exception as ex:
return ex
cur = conn.cursor()
cur.execute(query)
results = cur.fetchall()
cur.close()
conn.close()
return results
results = cur.fetchall()
cur.close()
conn.close()
return results
希望它有所帮助。