use*_*827 2 python amazon-web-services aws-lambda
我试图从m RDS数据库返回一个装备.dte字段都在DATETIME格式化,这导致我得到以下错误:
TypeError: datetime.datetime(2012, 8, 8, 21, 46, 24, 862000) is not JSON serializable
Run Code Online (Sandbox Code Playgroud)
我怎么能绕过这个?
继承我的代码:
import pymysql
import json
from rds import *
#rds settings
host = rds_host
name = rds_name
password = rds_password
db_name = rds_db_name
port = rds_port
try:
conn = pymysql.connect(host = host, user=name, passwd=password, db=db_name, connect_timeout=5)
except:
raise Exception('Database Error: The server encountered an unexpected condition which prevented it from fulfilling the request.')
def handler(event, context):
cur = conn.cursor(pymysql.cursors.DictCursor)
#selects a user from the database
query = "SELECT * FROM Outfits WHERE outfit_id = '" + event['outfitId'] + "' LIMIT 1"
#runs the SQL query
try:
cur.execute(query)
except:
raise Exception('Internal Error: The server encountered an unexpected condition which prevented it from fulfilling the request.')
#stores the downloaded record into the user variable
rows = cur.fetchone()
return result
Run Code Online (Sandbox Code Playgroud)
尚未使用AWS Lambda,但此问题是特定于python的.datetime.datetime对象不能被JSON序列化,你需要在JOSN序列化之前将它们转换为字符串.您可以使用.strftime()将datetime.datetime对象转换为字符串.