2015-04-01 47 views
1

我想在文件JSON和SQLAlchemy数据库中添加新数据时遇到问题。Ajax,Rest,Flask,SQLAlchemy,JSON:创建数据

我的形式为增加新的数据:

<form id="form" name="formquestions" style="text-align:center;" method="POST"> 
    <p> 
     <h3>Title </h3> 
     <input type="text" id="title" required> 
    </p> 
    <p> 
     <h3>Answer 1 </h3> 
     <input type="text" required> 
    </p> 
    <p> 
     <h3>Answer 2 </h3> 
     <input type="text" required> 
    </p> 
    <p> 
     <input id="buttonquestion" class="btn-success btn" type="submit" value=" Create the question " /> 
    </p> 
</form> 

我的请求的Ajax:

$(function() { 
$('#form').submit(function(event){ 
    event.preventDefault(); 
    var title = $('#title').val(); 
    var answer1=$('#firstAlternative').val(); 
    var answer2=$('#secondAlternative').val(); 
    var q= { 
     "title": title, 
     "firstAlternative": answer1, 
     "secondAlternative": answer2, 
    }; 
    var data=JSON.stringify(q); 
    $.ajax({ 
     type:"POST", 
     url:"/api/questions", 
     data:data, 
     dataType:"json", 
     contentType:"application/json", 
     success:function(data){ 
      console.log(data); 
      }, 
     error: function(){console.log('Error');} 

     }); 
     return false; 
}); 

});

我的观点:

@app.route('/api/questions', methods=['POST']) 
def create_question(): 
    print(request.json) 
    if not request.json or not 'title' in request.json: 
     abort(400) 

    question = { 
     'id': quests[-1]['id'] + 1, 
     'title': request.json['title'], 
     'firstAlternative': request.json.get('firstAlternative', ""), 
     'secondAlternative': request.json.get('secondAlternative', ""), 
    } 
    db.session.add(question) 
    db.session.commit() 
    return jsonify(question.to_json()), 201, 
    {'Location': url_for('get_post', id=question.id, _external=True)} 

在终端服务器显示的错误:

127.0.0.1 - - [01/Apr/2015 17:40:08] "POST /api/questions 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 1461, in dispatch_request 
    return self.view_functions[rule.endpoint](**req.view_args) 
    File "/home/dzde/UNIVERSITE/WEB/ProjetSondage/sondages/views.py", line 53, in create_question 
    db.session.add(question) 
    File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/orm/scoping.py", line 150, in do 
    return getattr(self.registry(), name)(*args, **kwargs) 
    File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/orm/session.py", line 1490, in add 
    raise exc.UnmappedInstanceError(instance) 
UnmappedInstanceError: Class '__builtin__.dict' is not mapped 

所以我有这样的错误500内部servor ... 在请求阿贾克斯,不成功只是错误...

谢谢

+1

你的烧瓶服务器应该显示一个错误。请张贴,以及。 – wholevinski 2015-04-01 15:38:47

+0

我的帖子被修改了,谢谢 – YassVegas 2015-04-01 15:43:25

回答

0

所以,你试图添加一个任意的字典到数据库。由于您使用的SQLAlchemy, 这里的一对映射位:

http://docs.sqlalchemy.org/en/latest/orm/mapping_columns.html 这是明确地指定一个类更好的资源:http://docs.sqlalchemy.org/en/latest/orm/extensions/automap.html#specifying-classes-explcitly

如果你没有准备好,你应该有它代表一个模型类数据库中的表格;上面的链接进入。然后您应该创建该类的一个实例,并将传递给db.session.add()调用。

我不熟悉SqlAlchemy是如何工作的,但现在出于好奇,我会稍微考虑一下;如果上述建议没有帮助,我会看看我是否可以在他们的文档中找到关于该主题的更多信息。

编辑:

所以我发现这一点:http://docs.sqlalchemy.org/en/latest/orm/extensions/automap.html

如果按照“基本使用”中的步骤,你有一个“问题”表中已有的,接下来就能够使用“问题“课。

0

我见过的jQuery您的代码似乎并没有在HTML ID正确的请求:

你的HTML代码应该是这样的:

<p> 
    <h3>Title </h3> 
    <input type="text" id="title" required> 
</p> 
<p> 
    <h3>Answer 1 </h3> 
    <input type="text" id="firstAlternative" required> 
</p> 
<p> 
    <h3>Answer 2 </h3> 
    <input type="text" id="secondAlternative" required> 
</p> 
<p> 

您的jQuery的要求是:

var title = $('#title').val(); 
var answer1=$('#firstAlternative').val(); 
var answer2=$('#secondAlternative').val(); 

希望它可以帮助:)