2017-07-02 50 views

回答

1

這是我在我的一個項目確實以JSON輸入從HTTP請求轉換爲動態的sqlalchemy型號:

if request.method == "POST" or request.method == "PUT": 
    data = request.get_json(force=True) 
    print("data:", data) 
    try: 
     TableClass = models.get_class_by_tablename(table_name) 
     if TableClass == None: raise Exception("Table not found: %s" % table_name) 
     if request.method == "POST": #insert data 
      object = TableClass(**data) 
      dbsession.add(object) 
      dbsession.commit() 
     else: #update data 
      object = dbsession.query(TableClass).filter_by(**{"id":id}).first() 
      if object == None: raise Exception("No data found.") 
      #object.update(**data) 
      for key in data.keys(): 
       setattr(object, key, data[key]) 
      #dbsession.add(object) 
      dbsession.commit() 
     return jsonify({ 
      "status": "success", 
      "id": object.id, 
      }) 
    except Exception as e: 
     return jsonify({ 
      "status": "error", 
      "error": str(e), 
      }) 

data是會從JSON輸入轉換爲普通的Python解釋變量。然後**data作爲sqlalchemy表類的實例創建的參數傳遞。

相關問題