python - Flask coverting to and from JSON -


i'm working on flask example takes blog posts , adding them database through restful service.

prior implementing restful service, adding blog posts local database doing following:

@main.route('/', methods=['get', 'post']) def index():     form = postform()     if current_user.can(permission.write_articles) , \             form.validate_on_submit():         post = post(body=form.body.data,                     author=current_user._get_current_object())         db.session.add(post)         return redirect(url_for('.index')) 

now i've gotten restful service section, following to_json() , from_json() functions have been post model:

//convert post json //class post(db.model) def to_json(self):         json_post = {             'url': url_for('api.get_post', id=self.id, _external=true),             'body': self.body,             'body_html': self.body_html,             'timestamp': self.timestamp,             'author': url_for('api.get_user', id=self.author_id,                               _external=true),             'comments': url_for('api_get_post_comments', id=self.id,                                 _external=true),             'comment_count': self.comments.count()         }         return json_post  //create blog post json //class post(db.model) @staticmethod def from_json(json_post):     body = json_post.get('body')     if body none or body == '':         raise validationerror('post not have body')     return post(body=body) 

the following inserts new blog post in database:

//post resource handler posts @api.route('/posts/', methods=['post']) @permission_required(permission.write_articles) def new_post():     post = post.from_json(request.json)     post.author = g.current_user     db.session.add(post)     db.session.commit()     return jsonify(post.to_json()), 201, \         {'location': url_for('api.get_post', id=post.id, _external=true)} 

would appreciate if explain how these functions work each other. understanding of blog post typed on client device , in order send web service, to_json function called convert post json. once web service receives json version of blog post, from_json function called convert json post original state. correct?

edit: re-read page , think understanding reverse of whats happening. in order blog post web service, to_json function called convert data json. on client side, from_json function called convert data json.

your edit correct. common response format rest api json, why the response converted "to json" when returning.

also common header sending data rest api application/json, why code converts received data "from json".


Comments