<s> from flask import jsonify , request , g , abort , url_for , current_app <EOL> from . . import db <EOL> from . . models import Post , Permission <EOL> from . import api <EOL> from . decorators import permission_required <EOL> from . errors import forbidden <EOL> @ api . route ( '<STR_LIT>' ) <EOL> def get_posts ( ) : <EOL> page = request . args . get ( '<STR_LIT>' , <NUM_LIT:1> , type = int ) <EOL> pagination = Post . query . paginate ( <EOL> page , per_page = current_app . config [ '<STR_LIT>' ] , <EOL> error_out = False ) <EOL> posts = pagination . items <EOL> prev = None <EOL> if pagination . has_prev : <EOL> prev = url_for ( '<STR_LIT>' , page = page - <NUM_LIT:1> , _external = True ) <EOL> next = None <EOL> if pagination . has_next : <EOL> next = url_for ( '<STR_LIT>' , page = page + <NUM_LIT:1> , _external = True ) <EOL> return jsonify ( { <EOL> '<STR_LIT>' : [ post . to_json ( ) for post in posts ] , <EOL> '<STR_LIT>' : prev , <EOL> '<STR_LIT>' : next , <EOL> '<STR_LIT:count>' : pagination . total <EOL> } ) <EOL> @ api . route ( '<STR_LIT>' ) <EOL> def get_post ( id ) : <EOL> post = Post . query . get_or_404 ( id ) <EOL> return jsonify ( post . to_json ( ) ) <EOL> @ api . route ( '<STR_LIT>' , methods = [ '<STR_LIT:POST>' ] ) <EOL> @ permission_required ( Permission . WRITE_ARTICLES ) <EOL> def new_post ( ) : <EOL> post = Post . from_json ( request . json ) <EOL> post . author = g . current_user <EOL> db . session . add ( post ) <EOL> db . session . commit ( ) <EOL> return jsonify ( post . to_json ( ) ) , <NUM_LIT> , { '<STR_LIT>' : url_for ( '<STR_LIT>' , id = post . id , _external = True ) } <EOL> @ api . route ( '<STR_LIT>' , methods = [ '<STR_LIT>' ] ) <EOL> @ permission_required ( Permission . WRITE_ARTICLES ) <EOL> def edit_post ( id ) : <EOL> post = Post . query . get_or_404 ( id ) <EOL> if g . current_user != post . author and not g . current_user . can ( Permission . ADMINISTER ) : <EOL> return forbidden ( '<STR_LIT>' ) <EOL> post . body = request . json . get ( '<STR_LIT:body>' , post . body ) <EOL> db . session . add ( post ) <EOL> return jsonify ( post . to_json ( ) ) </s>
