python - Ajax, Rest, Flask, SQLAlchemy, JSON : create data -


i have problem when want add new data in file json , in sqlalchemy database.

my form add new data :

<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 question " />     </p> </form> 

my request 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; }); 

});

my view :

@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)} 

error of server display in terminal :

    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     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' not mapped 

so have error 500 in internal servor... in request ajax, not success error...

thank

so, you're trying add arbitrary dict database. since you're using sqlalchemy, here's bit on mapping:

http://docs.sqlalchemy.org/en/latest/orm/mapping_columns.html better resource specifying classes explicitly: http://docs.sqlalchemy.org/en/latest/orm/extensions/automap.html#specifying-classes-explcitly

if don't already, should have model class represents table in database; link above goes that. should create instance of class, , pass that db.session.add() call.

i'm unfamiliar how sqlalchemy works, i'll little out of curiosity; if above advice doesn't help, i'll see if can find more on subject in docs.

edit:

so found this: http://docs.sqlalchemy.org/en/latest/orm/extensions/automap.html

if follow steps in "basic use" , have "question" table existing already, should able use "question" class.


Comments

Popular posts from this blog

tcpdump - How to check if server received packet (acknowledged) -