0

一个典型的 chalice 应用程序定义了多个路由,但是如何正确地将其连接到 RDS 以便我可以保存 POST 数据或从数据库中检索数据?我已经通过 RDS 面板创建了一个数据库;我只是不确定如何从 Chalice 访问它。

是否只是让每条路由使用用户/通行证连接到给定的 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 的正确方法是什么?

4

1 回答 1

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

希望能帮助到你。

于 2018-04-16T15:12:26.760 回答