Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- ###### from app/resources/post.py ##############
- class PostView(Resource):
- def get(self, post_id):
- return Post.query.filter_by(id=post_id).first_or_404()
- def put(self, post_id):
- post = Post.query.filter_by(id=post_id).first_or_404()
- args = parser.parse_args()
- title = args.get('title')
- body = args.get('body')
- if title:
- post.title = title
- if body:
- post.body = body
- db.session.add(post)
- return post
- class PostListView(Resource):
- def get(self):
- POSTS_PER_PAGE = current_app.config.get('POSTS_PER_PAGE') or 1
- args = parser.parse_args()
- offset = args.get('offset') or 1
- items = Post.query.all().\
- order_by(Post.timestamp.desc()).\
- paginate(offset, offset + POSTS_PER_PAGE, False).\
- items()
- return items
- def post(self):
- args = parser.parse_args()
- title = args.get('title')
- body = args.get('body')
- if title and body:
- post = Post(
- title=title,
- body=body,
- timestamp=datetime.datetime.utcnow()
- )
- db.session.add(post)
- return post
- else:
- return 400
- ############### from app/__init__.py ##################
- from flask import Flask
- from flask_sqlalchemy import SQLAlchemy
- from flask_restful import Api
- from config import config
- db = SQLAlchemy()
- rest_api = Api()
- def create_app(config_name='default'):
- app = Flask(__name__)
- app.config.from_object(config[config_name])
- db.init_app(app)
- rest_api.init_app(app)
- import resources
- rest_api.add_resource(resources.PostListView, '/', '/posts')
- rest_api.add_resource(resources.PostView, '/posts/<int:post_id>')
- return app
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement