-
Notifications
You must be signed in to change notification settings - Fork 4
/
blogmv.py
82 lines (69 loc) · 2.85 KB
/
blogmv.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
77
78
79
80
81
82
from flask import Flask, request, escape
from flask_cors import CORS
from google.appengine.ext import ndb
from models import Article, Comment
from json_serializer import JSONEncoder
import json
app = Flask(__name__)
app.config['CORS_HEADERS'] = 'Content-Type'
cors = CORS(app)
def serialize(result):
if not result and not isinstance(result, list):
return "", 404, {"Content-Type": "application/json"}
return json.dumps(result, cls=JSONEncoder), 200, {"Content-Type": "application/json"}
@app.route("/api/articles/", methods=['GET'])
def getArticles():
articles = Article.query()
if articles.count() == 0:
hello = Article()
hello.title = "Hello World"
hello.content = "Lorem ipsum dolor sit amet, consectetur adipisicing elit. Consequuntur, voluptatum. Provident accusamus sit, commodi corrupti illo, veniam possimus minima rerum itaque. Magni, beatae, facere."
hello.put()
bye = Article()
bye.title = "Bye World"
bye.content = "Iraqi PM Nouri Maliki steps aside, ending political deadlock in Baghdad as the government struggles against insurgents in the north."
bye.put()
del hello, bye
articles = Article.query()
return serialize(list(articles.order(Article.date).fetch(10)))
@app.route("/api/articles/<int:article_id>/", methods=['GET'])
def getArticle(article_id):
return serialize(Article.get_by_id(article_id))
@app.route("/api/articles/<int:article_id>/comments/", methods=['GET'])
def getComments(article_id):
if not Article.get_by_id(article_id):
return "", 404, {"Content-Type": "application/json"}
return serialize(list(Comment.query(Comment.article == ndb.Key(Article, article_id)).order(Comment.date).fetch(10)))
@app.route("/api/articles/<int:article_id>/comments/<int:comment_id>/", methods=['GET'])
def getComment(article_id, comment_id):
return serialize(
Comment.query(
ndb.AND(
Comment.article == ndb.Key(Article, article_id),
Comment.key == ndb.Key(Comment, comment_id)
)
).get()
)
@app.route("/api/articles/<int:article_id>/comments/", methods=['POST'])
def postComment(article_id):
article = Article.get_by_id(article_id)
if not article:
return "", 404, {"Content-Type": "application/json"}
data = request.get_json()
if not data:
return "Missing data", 400
comment = Comment()
comment.article = article.key
comment.author_name = escape(data.get("author_name"))
comment.author_email = escape(data.get("author_email"))
comment.content = escape(data.get("content"))
comment.put()
comments = Comment.query().order(Comment.date).fetch(keys_only=True)
if len(comments) >= 10:
comments[0].delete()
return serialize(comment)
@app.route("/")
def home():
return "OK"
if __name__ == "__main__":
app.run()