-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.py
76 lines (55 loc) · 1.91 KB
/
main.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
from flask import Flask, jsonify, request, make_response
from flask_sqlalchemy import SQLAlchemy
from flask_marshmallow import Marshmallow
from flask_restful import Api, Resource
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///test.db'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
db = SQLAlchemy(app)
ma = Marshmallow(app)
api = Api(app)
class Post(db.Model):
id = db.Column(db.Integer, primary_key=True)
title = db.Column(db.String(50))
content = db.Column(db.String(255))
def __repr__(self):
return '<Post %s>' % self.title
class PostSchema(ma.Schema):
class Meta:
fields = ("id", "title", "content")
post_schema = PostSchema()
posts_schema = PostSchema(many=True)
class PostListResource(Resource):
def get(self):
posts = Post.query.all()
return posts_schema.dump(posts)
def post(self):
new_post = Post(
title=request.json['title'],
content=request.json['content']
)
db.session.add(new_post)
db.session.commit()
return post_schema.dump(new_post)
class PostResource(Resource):
def get(self, post_id):
post = Post.query.get_or_404(post_id)
return post_schema.dump(post)
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)
def delete(self, post_id):
post = Post.query.get_or_404(post_id)
db.session.delete(post)
db.session.commit()
data = {"Eliminado":"Done"}
return make_response(jsonify(data),204)
api.add_resource(PostListResource, '/posts')
api.add_resource(PostResource, '/posts/<int:post_id>')
if __name__ == '__main__':
app.run(debug=True)