python连接dynamodb

导入库

import boto3
import psycopg2
from flask import Flask,request , jsonify

app = Flask(name)

region = "us-east-1"
dynamodb = boto3.resource('dynamodb',region_name=region)
table = dynamodb.Table('dynamodb-table')

RDS_CONFIG = {
"dbname" : "postgres",
"user" : "postgres",
"password" : "Wangyi178",
"host" : "database-1.cqbu442ikt9q.us-east-1.rds.amazonaws.com",
"port" : "5432"
}

@app.route('/health')
def health():
return "ok",200

@app.route('/post_data1', methods=['POST'])
def post_data1():
data = request.get_json()
table.put_item(
Item={
"id": data["id"],
'value':data["value"]
}
)
return jsonify(
{
"message":data
}
),200

@app.route('/post_data2', methods=['POST'])
def post_data2():
data = request.get_json()
conn = psycopg2.connect(**RDS_CONFIG)
cur = conn.cursor()
cur.execute("INSERT INTO student (id,value)VALUES (%s,%s)" , (data["id"] , data["value"]))
conn.commit()
cur.close()
conn.close()
return jsonify(
{
"message":data
}
),200

@app.route('/get_value', methods=['GET'])
def get_value():
id = request.args.get("id")
dynamodb_item = table.get_item(
Key={
'id': id
}
)
dynamodb_value = int(dynamodb_item['Item'].get("value"," "))
conn = psycopg2.connect(**RDS_CONFIG)
cur = conn.cursor()
cur.execute("select value from student where id = %s" , (id,))
rds_value = int(cur.fetchone()[0])
cur.close()
conn.close()
return jsonify(
{
"message":dynamodb_value+rds_value
}
),200

if name == "main":
app.run(host="0.0.0.0",port=80)

posted @ 2026-11-09 21:04  tabtab--007  阅读(6)  评论(0)    收藏  举报