2015-04-01 89 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(); 

希望它可以幫助:)