/
resources.py
343 lines (283 loc) · 11.9 KB
/
resources.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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
# -*- coding: utf-8 -*-
'''
Created on Feb 9, 2014
@author: guillem
'''
import webapp2
import json
import string
import logging
import re, datetime
import array
import xml.etree.ElementTree as ET
from collections import OrderedDict
from google.appengine.ext import ndb
from google.appengine.datastore.datastore_query import Cursor
from models import Article, Comment
from google.appengine.api import mail
from google.appengine.api import memcache
ITEMS_PER_PAGE = 6
class ArchiveResource(webapp2.RequestHandler):
def get(self):
archive = memcache.get('archive')
if archive is not None:
self.response.out.headers['Content-Type'] = 'application/json'
self.response.out.write(json.dumps({'articles':archive}))
else:
more = True
archive = OrderedDict()
curs = None
while more:
articles, curs, more = Article.query().order(
-Article.when).fetch_page(
50,
start_cursor=curs,
projection=[Article.title,
Article.when,
Article.keywords])
for article in articles:
article_key = article.key.urlsafe()
if article_key in archive:
archive[article_key]['keywords'].extend(
article.keywords)
else:
archive[article_key] = {
'title': article.title,
'when': article.when.strftime("%d/%m/%Y %H:%M:%S"),
'keywords': article.keywords,
'key': article_key,
'ncomments': 0}
more = True
curs = None
while more:
page, curs, more = Comment.query().fetch_page(
100,
start_cursor = curs)
for comment in page:
parent_key = comment.key.parent().urlsafe()
if parent_key in archive:
archive[parent_key]['ncomments'] += 1
memcache.add('archive',
[a for a in archive.itervalues()],
time=86400)
self.response.out.headers['Content-Type'] = 'application/json'
self.response.out.write(json.dumps(
{'articles':[a for a in archive.itervalues()]}
))
class ArticleResource(webapp2.RequestHandler):
def get(self):
article = ndb.Key(urlsafe = self.request.get('key')).get()
if article:
self.response.out.headers['Content-Type'] = 'application/json'
self.response.out.write(json.dumps(article.as_dict()))
@ndb.transactional
def post(self):
d = json.loads(self.request.body)
if d['secret'] == '16jutges16':
if 'key' in d and len(d['key']) > 10: #Keys are looong.
article = ndb.Key(urlsafe = d['key']).get()
logging.info('Modifying entry {}'.format(d['key']))
else:
article = Article()
article.slug = d['slug']
article.title = d['title']
article.text = d['text']
if 'when' in d:
# Matches isoformat into datetime object. Found in stackoverflow
article.when = datetime.datetime(
*map(int, re.split('[^\d]', d['when'])[:-1])
)
else:
article.when = datetime.datetime.now()
try:
article.keywords = string.split(d['keywords'])
except AttributeError:
article.keywords = d['keywords']
article.put()
def delete(self):
article = ndb.Key(urlsafe = self.request.get('key')).get()
secret = self.request.get('secret')
if secret == '16jutges16':
logging.info('Removing entry {}'.format(article.key.urlsafe()))
article.key.delete()
class ArticleKeyFromSlugResource(webapp2.RequestHandler):
def get(self):
# An if that is just a router.
# Ask for a key, return the article in json format
if self.request.get('slug'):
slug = self.request.get('slug')
self.response.out.write(Article.key_from_slug(slug))
class ArticleListResource(webapp2.RequestHandler):
'''
classdocs
'''
# Ask for a page, return a list of keys as a json list,
# to be processed by the client
def get(self):
if self.request.get('p'):
curs = Cursor(urlsafe=self.request.get('p'))
articles, curs, more = Article.query().order(
-Article.when).fetch_page(ITEMS_PER_PAGE, start_cursor=curs)
if more:
curs = curs.urlsafe()
else:
curs = None
self.response.out.headers['Content-Type'] = 'application/json'
self.response.out.write(
json.dumps(
{'articles': [a.as_dict() for a in articles],
'next': curs,
'more': more}
)
)
# If nothing is queried, return initial page.
# TODO: merge those two conditionals.
else:
articles, curs, more = Article.query().order(
-Article.when).fetch_page(ITEMS_PER_PAGE)
if more:
curs = curs.urlsafe()
else:
curs = None
self.response.out.headers['Content-Type'] = 'application/json'
self.response.out.write(
json.dumps(
{'articles': [a.as_dict() for a in articles],
'next': curs,
'more': more}
)
)
class TaggedArticleListResource(webapp2.RequestHandler):
'''
classdocs
'''
def get(self):
tag = self.request.get('tag')
if self.request.get('p'):
curs = Cursor(urlsafe=self.request.get('p'))
articles = list()
query_iterator = Article.query().order(
-Article.when).iter(produce_cursors=True,
start_cursor=curs)
for article in query_iterator:
if tag in article.keywords:
articles.append(article)
if len(articles) == ITEMS_PER_PAGE:
break
curs = query_iterator.cursor_after().urlsafe()
more = query_iterator.probably_has_next()
self.response.out.headers['Content-Type'] = 'application/json'
self.response.out.write(
json.dumps(
{'articles': [a.as_dict() for a in articles],
'next': curs,
'more': more}
)
)
# If nothing is queried, return initial page.
# TODO: merge those two conditionals.
else:
articles = list()
query_iterator = Article.query().order(
-Article.when).iter(produce_cursors=True)
for article in query_iterator:
if tag in article.keywords:
articles.append(article)
if len(articles) == ITEMS_PER_PAGE:
break
curs = query_iterator.cursor_after().urlsafe()
more = query_iterator.probably_has_next()
self.response.out.headers['Content-Type'] = 'application/json'
self.response.out.write(
json.dumps(
{'articles': [a.as_dict() for a in articles],
'next': curs,
'more': more}
)
)
class ArticleLastRSS(webapp2.RequestHandler):
def get(self):
articles, curs, more = Article.query().order(
-Article.when).fetch_page(ITEMS_PER_PAGE)
self.response.out.headers['Content-Type'] = 'application/rss+xml'
self.response.out.write('<?xml version="1.0" encoding="UTF-8" ?>')
rss = ET.Element('rss')
rss.set('version','2.0')
channel = ET.SubElement(rss,'channel')
ET.SubElement(channel,
'title').text = 'I HAVE BECOME CONFORTABLY NUMB. Guillem Borrell et al.'
ET.SubElement(channel,
'description').text = 'Blog de Guillem Borrell'
ET.SubElement(channel,
'link').text = 'http://guillemborrell.es/'
ET.SubElement(channel,
'lastBuildDate').text = datetime.datetime.now().strftime(
'%a, %d %b %Y %H:%M:%S %z')
ET.SubElement(channel,
'pubDate').text = datetime.datetime.now().strftime(
'%a, %d %b %Y %H:%M:%S %z')
ET.SubElement(channel,
'ttl').text = '1800'
items = []
for i,article in enumerate(articles):
items.append(ET.SubElement(channel,'item'))
ET.SubElement(items[i],'title').text = article.title
ET.SubElement(items[i],'description').text = article.text
ET.SubElement(items[i],'link').text ='http://guillemborrell.es/article/{}'.format(article.key.urlsafe())
ET.SubElement(items[i],'guid').text = article.key.urlsafe()
ET.SubElement(items[i],'pubDate').text= article.when.strftime(
'%a, %d %b %Y %H:%M:%S %z')
self.response.out.write(ET.tostring(rss))
class CommentResource(webapp2.RequestHandler):
'''
classdocs
'''
def get(self):
if self.request.get('key'):
comment = ndb.Key(urlsafe = self.request.get('key')).get()
if comment:
self.response.out.headers['Content-Type'] = 'application/json'
self.response.out.write(json.dumps(comment.as_dict()))
else:
self.abort(404)
elif self.request.get('article'):
self.response.out.headers['Content-Type'] = 'application/json'
self.response.out.write(
json.dumps(
Comment.from_article(self.request.get('article'))
)
)
else:
self.abort(404)
@ndb.transactional
def post(self):
d = json.loads(self.request.body)
if d['safety'] == 'Borrell':
if 'when' in d:
# Matches isoformat into datetime object. Found in stackoverflow
d['when'] = datetime.datetime(
*map(int, re.split('[^\d]', d['when'])[:-1])
)
else:
d['when'] = datetime.datetime.now()
parent = ndb.Key(urlsafe = d['parent'])
comment = Comment(parent = parent,
author = d['author'],
text = d['text'],
when = d['when'])
comment.put()
#Send mail to me.
mail.send_mail(
sender="guillemborrell@gmail.com",
to="Guillem Borrell <guillemborrell@gmail.com>",
subject="Nuevo comentario en el blog de Guillem Borrell",
body=u"""
Déu vos guard.
Nou comentari a http://www.guillemborrell.es/article/{}
{} | {}
{}
""".format(d['parent'],
d['author'],
d['when'].isoformat(),
d['text'])
)