簡體   English   中英

Python Flask SQLalchemy JSON POST錯誤

[英]Python Flask SQLalchemy JSON POST Error

我正在嘗試發布以下JSON並保存到Flask服務器和Python 2.7,不安框架和帶有curl的SQLAlchemy上的MySQL數據庫中:

curl -i -H "Accept: application/json" -X POST  -d '{"attribute_id": "1", "product_id": "44","text":"Something","language":"1"}' http://seroney-pc:5000/api/attributes

{
    "attribute_id": "1",
    "product_id": "44",
    "text": "Something",
    "language": "1"
}

我的代碼如下:

from flask import Flask,request,jsonify, abort
from flask_sqlalchemy import SQLAlchemy
import flask_restless


app = Flask(__name__)
db = SQLAlchemy(app)
manager = flask_restless.APIManager(app)

app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql://root:seroney@localhost:3306/test'


class Attributes(db.Model):
    __tablename__ = 'oc_product_attribute'
    product_id = db.Column(db.Integer,primary_key=True)
    attribute_id = db.Column(db.Integer,primary_key=True)
    language_id = db.Column(db.Integer,primary_key=True)
    text=db.Column(db.String)

@app.route('/api/attributes/',methods=['GET'])
def getProductAttributes():
    if request.method =='GET':
        results = Attributes.query.limit(10).offset(0).all()
        json_results = []
        for result in results:
            d = {
                'product_id':result.product_id,
                'attribute_id':result.attribute_id,
                'language_id':result.language_id,
                'text':result.text
            }
            json_results.append(d)

        return jsonify(items = json_results)

@app.route('/api/attributes/', methods=['POST'])

def postProductAttributes():
    product_id = request.json['product_id']
    attribute_id = request.json['attribute_id']
    language_id = request.json['language_id']
    text = request.json['text']
    if product_id is None or attribute_id is None or language_id is None or text is None:
        return jsonify({"message": "Error."}), 400
    new_attrib = (product_id,attribute_id,language_id,text)
    db.session.add(new_attrib)
    db.session.commit()
    return jsonify({'message' :'Attribute Created successfully'}), 200

if __name__ == '__main__':
    app.run(debug=True)

發布時,我一直收到內部服務器錯誤。 非常感謝您的幫助。

追溯為:

seroney-pc - - [23/Dec/2014 20:48:40] "POST /api/attributes HTTP/1.1" 500 -
Traceback (most recent call last):
  File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1836, in __call__
    return self.wsgi_app(environ, start_response)
  File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1820, in wsgi_app
    response = self.make_response(self.handle_exception(e))
  File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1403, in handle_exception
    reraise(exc_type, exc_value, tb)
  File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1817, in wsgi_app
    response = self.full_dispatch_request()
  File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1477, in full_dispatch_request
    rv = self.handle_user_exception(e)
  File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1381, in handle_user_exception
    reraise(exc_type, exc_value, tb)
  File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1475, in full_dispatch_request
    rv = self.dispatch_request()
  File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1453, in dispatch_request
    self.raise_routing_exception(req)
  File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1439, in raise_routing_exception
    raise FormDataRoutingRedirect(request)

注意:僅在調試模式下引發此異常

您要發布到URL的末尾沒有 / ,但是您在路由后加上 / 當你這樣做,瓶發出重定向到“規范”的網址,用/

由於您使用的是POST,因此后的數據將丟失,因此在調試模式下會引發異常,以通知您應在帖子中使用斜杠。

假如你看着錯誤消息的身體 ,你會看到這樣的:

FormDataRoutingRedirect:請求已發送到該URL(http:// seroney-pc:5000 / api / attributes),但是路由系統自動將重定向發送到“ http:// seroney-pc:5000 / api / attributes / ”。 該URL定義了一個斜杠,因此如果沒有訪問Flask,它將自動重定向到帶有斜杠的URL。 請確保直接將您的POST請求發送到此URL,因為我們無法使瀏覽器或HTTP客戶端可靠地重定向表單數據或沒有用戶交互。

注意:僅在調試模式下引發此異常

請參閱規則格式文檔

以斜杠結尾的URL規則是分支URL,其他則是葉子。 如果啟用了strict_slashes (默認設置),則所有訪問的沒有尾隨斜杠的分支URL都將觸發重定向到添加了該斜杠的相同URL。

請注意,您的curl POST使用了錯誤的標題; 您需要設置Content-Type標頭。 您的視圖正在尋找language_id鍵,但是您的帖子僅包含一個language鍵,您也需要更正該錯誤:

curl -i -H "Content-Type: application/json" -X POST \
     -d '{"attribute_id": "1", "product_id": "44","text":"Something","language_id":"1"}' http://seroney-pc:5000/api/attributes/

Accept標頭也可能有用,但是它用於協商響應內容類型,並且您已將視圖硬編碼為返回JSON。

您創建數據庫對象的代碼也不正確,您需要調用模型並將參數作為單獨的參數傳遞,然后將結果傳遞給session.add()

new_attrib = Attributes(*new_attrib)
db.session.add(new_attrib)

但是在這里重用JSON對象會更容易:

db.session.add(Attributes(**request.json))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM