python - 如何在 python 中使用单个 json 命令添加多个表条目?
问题描述
我想使用单个 JSON 输入将多个条目放入表中,但我不知道如何从这里开始。一旦用户声明,我就会到达哪里
[
{
"VIN": "kjasdfh",
"Make": "Toyota",
"model": "Corolla",
"Year": 1998
},
{
"VIN": "wqeiryu",
"Make": "Honda",
"model": "Civic",
"Year": 1997
}
]
我不会让它第一个有自己的条目,而第二个有另一个条目。
@app.route('/api/addcar', methods = ['POST']) # This is a post method because the user needs to be able to add info
def adding_stuff():
request_data = request.get_json() # Gets the info from the table and converts to JSON format
new_vin = request_data['VIN']
new_make = request_data['Make']
new_year = request_data['Year']
new_color = request_data['Color']
sql = "INSERT INTO carsTEST (VIN, Make, Year, Color, username) VALUES ('%s', '%s', %s, '%s')" % (new_vin, new_make, new_year, new_color) # This sql statement will then be uploaded to the databse to add a new record
conn = create_connection()
execute_query(conn, sql) # This will execute the query
return 'Post worked'
解决方案
您必须将您的 json 数组转换为模型数组(使用序列化程序或您的框架提供的东西)。或者尝试使用以下内容构建原始 sql:
json_data = [
{
"VIN": "kjasdfh",
"Make": "Toyota",
"model": "Corolla",
"Color": "red",
"Year": 1998
},
{
"VIN": "wqeiryu",
"Make": "Honda",
"model": "Civic",
"Color": "white",
"Year": 1997
}
]
sql = "INSERT INTO carsTEST (VIN, Make, Year, Color, username) VALUES"
for jo in json_data:
new_vin = jo['VIN']
new_make = jo['Make']
new_year = jo['Year']
new_color = jo['Color']
value_sql = "('{}', '{}', '{}', '{}'),".format(new_vin, new_make, new_year, new_color)
sql = sql + value_sql
sql = sql.rstrip(',') + ";"
print(sql)
Edit1:该方法应该类似于:
@app.route('/api/addcar', methods=['POST'])
def adding_stuff():
request_data = request.get_json() # post body must be a json array
sql = "INSERT INTO carsTEST (VIN, Make, Year, Color) VALUES"
for jo in request_data:
new_vin = jo['VIN']
new_make = jo['Make']
new_year = jo['Year']
new_color = jo['Color']
value_sql = "('{}', '{}', '{}', '{}'),".format(new_vin, new_make, new_year, new_color)
sql = sql + value_sql
sql = sql.rstrip(',') + ";"
conn = create_connection()
execute_query(conn, sql) # This will execute the query
return 'Post worked'
推荐阅读
- slider - 徽标滑块内的垂直对齐
- python - 如何将数据形式的json文件保存在字典中?不和谐.py
- typescript - 生成客户端代码后 TypeScript 版本与 Angular 11 不兼容
- r - 向没有编号轴的箱线图添加文本
- html - 当我只想要一个可滚动元素时页面扩展
- flutter - Open Source alternatives to push notifications by Google's FCM or Amazon's AWS SQS?
- c# - 如何在 ASPNET Core MVC 中处理 JWT
- javascript - 将对象数组的值与字符串进行比较 - 返回布尔值
- swift - navigationBarItems 之间的间距
- ruby-on-rails - 使用 postgres 生成列的 Rails 迁移,无法在测试环境中运行