我正在尝试发布以下JSON并保存到Flask服务器和Python 2.7,restless framework和SQLAlchemy上使用curl的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 末尾没有/
,但您使用尾随/
指定了路由。当您这样做时,Flask 会发出重定向到"规范"URL,并带有/
.
由于您使用的是 POST,因此帖子数据将丢失,因此在调试模式下会引发异常,通知您应该在帖子中使用尾部斜杠。
如果您查看错误消息的正文,您会看到类似以下内容:
FormDataRoutingRedirect:向此 URL (http://seroney-pc:5000/api/attributes( 发送了一个请求,但重定向是 路由系统自动发出到"http://seroney-pc:5000/api/attributes/"。URL 是使用尾部斜杠定义的,因此,如果在没有尾部斜杠的情况下访问该 URL,Flask 将自动重定向到带有尾部斜杠的 URL。确保直接将您的 POST 请求发送到此 URL,因为我们无法可靠地使用表单数据或无需用户交互即可使浏览器或 HTTP 客户端重定向。
注意:此异常仅在调试模式下引发
请参阅规则格式文档:
以斜杠结尾的 URL 规则是分支 URL,其他规则是叶子。如果启用了strict_slashes(这是默认值(,则访问的所有没有尾部斜杠的分支 URL 都将触发重定向到附加了该斜杠的同一 URL。
请注意,您的curl
POST 使用了错误的标头;您需要设置内容类型标头。您的视图正在寻找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))