66 lines
1.9 KiB
Python
66 lines
1.9 KiB
Python
from flask import request, jsonify
|
|
from Models.Post import Post
|
|
from Models.Tag import Tag
|
|
from Models.Schema import post_schema, posts_schema
|
|
from flask_restful import Resource, abort
|
|
from app import db
|
|
from flask_jwt_extended import create_access_token, get_jwt_identity, jwt_required, JWTManager, current_user
|
|
|
|
class PostListResource(Resource):
|
|
@jwt_required()
|
|
def get(self):
|
|
posts = Post.query.all()
|
|
return posts_schema.dump(posts)
|
|
|
|
@jwt_required()
|
|
def post(self):
|
|
tags_array= []
|
|
for tag_id in request.json['tags']:
|
|
tags_array.append(Tag.query.filter_by(id=tag_id).first())
|
|
|
|
new_post = Post(
|
|
title=request.json['title'],
|
|
content=request.json['content'],
|
|
author_id=current_user.id,
|
|
author=current_user,
|
|
tags=tags_array
|
|
)
|
|
db.session.add(new_post)
|
|
db.session.commit()
|
|
return post_schema.dump(new_post)
|
|
|
|
|
|
class PostResource(Resource):
|
|
@jwt_required()
|
|
def get(self, post_id):
|
|
post = Post.query.get_or_404(post_id)
|
|
return post_schema.dump(post)
|
|
|
|
@jwt_required()
|
|
def put(self, post_id):
|
|
post = Post.query.get_or_404(post_id)
|
|
|
|
post.title = request.json['title']
|
|
post.content = request.json['content']
|
|
|
|
db.session.commit()
|
|
return post_schema.dump(post)
|
|
|
|
@jwt_required()
|
|
def patch(self, post_id):
|
|
post = Post.query.get_or_404(post_id)
|
|
|
|
if 'title' in request.json:
|
|
post.title = request.json['title']
|
|
if 'content' in request.json:
|
|
post.content = request.json['content']
|
|
|
|
db.session.commit()
|
|
return post_schema.dump(post)
|
|
|
|
@jwt_required()
|
|
def delete(self, post_id):
|
|
post = Post.query.get_or_404(post_id)
|
|
db.session.delete(post)
|
|
db.session.commit()
|
|
return '', 204 |