PageRenderTime 251ms CodeModel.GetById 1ms RepoModel.GetById 0ms app.codeStats 0ms

/api/routes/Drafts.py

https://gitlab.com/fdemian/Shelob
Python | 281 lines | 216 code | 60 blank | 5 comment | 16 complexity | 289b205712fcca0a6f91c62394493e66 MD5 | raw file
  1. import json
  2. from api.model.models import Story, User, Category
  3. from sqlalchemy.orm.exc import NoResultFound, MultipleResultsFound
  4. from api.authentication.AuthenticatedHandler import AuthenticatedHandler
  5. from tornado.gen import coroutine
  6. from api.Utils import authenticated
  7. import datetime
  8. class DraftsHandler(AuthenticatedHandler):
  9. def data_received(self, chunk):
  10. pass
  11. # GET /drafts
  12. @coroutine
  13. def get(self):
  14. session = self.settings['db']
  15. story_id = self.get_argument("id", default=None)
  16. if story_id is not None:
  17. story = session.query(Story).filter(Story.id == story_id and Story.is_draft == True).one()
  18. if story.category is None:
  19. category = {'id': -1, 'name': "uncatalogued"}
  20. else:
  21. category = {'id': story.category.id, 'name': story.category.name}
  22. comments = []
  23. for comment in story.comments:
  24. json_comment = {
  25. 'id': comment.id,
  26. 'author': comment.author,
  27. 'content': comment.content,
  28. 'avatar': comment.avatar,
  29. 'url': comment.url,
  30. 'date': str(comment.date)
  31. }
  32. comments.append(json_comment)
  33. json_author = {
  34. 'id': story.author.id,
  35. 'name': story.author.fullname,
  36. 'avatar': story.author.avatar,
  37. 'username': story.author.username,
  38. 'signature': story.author.signature
  39. }
  40. response = {
  41. 'id': story.id,
  42. 'title': story.title,
  43. 'category': category,
  44. 'content': story.content,
  45. 'comments': comments,
  46. 'tags': story.tags.split(','),
  47. 'author': json_author,
  48. 'date': str(story.date),
  49. 'is_draft': True
  50. }
  51. self.set_header("Content-Type", "application/jsonp;charset=UTF-8")
  52. self.set_header("Access-Control-Allow-Origin", "*")
  53. self.write(response)
  54. return
  55. else:
  56. all_stories = session.query(Story).filter(Story.is_draft == True).order_by(Story.id.desc()).all()
  57. data = []
  58. for story in all_stories:
  59. if story.category is None:
  60. category = {'id': -1, 'name': "Uncategorized"}
  61. else:
  62. category = {'id': story.category.id, 'name': story.category.name}
  63. json_story = {
  64. 'id': story.id,
  65. 'name': story.title,
  66. 'content': story.content,
  67. 'tags': story.tags.split(','),
  68. 'author': {
  69. 'id': story.user.id,
  70. 'name': story.user.username,
  71. 'avatar': story.user.avatar
  72. },
  73. 'comments': len(story.comments),
  74. 'date': str(story.date),
  75. 'category': category,
  76. 'is_draft': story.is_draft
  77. }
  78. data.append(json_story)
  79. response = {"page": 1, "items": data}
  80. self.set_header("Content-Type", "application/jsonp;charset=UTF-8")
  81. self.set_header("Access-Control-Allow-Origin", "*")
  82. self.write(response)
  83. return
  84. # POST /stories/new
  85. @authenticated
  86. def post(self):
  87. request = self.request.body.decode("utf-8")
  88. json_request = json.loads(json.loads(request))
  89. title = json_request["title"]
  90. tags = ",".join(json_request["tags"])
  91. content = json.dumps(json_request["content"])
  92. author_id = json_request["author"]
  93. category_id = json_request["category"]
  94. is_draft = json_request['is_draft']
  95. session = self.settings['db']
  96. try:
  97. category = session.query(Category).filter(Category.id == category_id).one()
  98. except NoResultFound:
  99. category = None
  100. story = self.save_story(session, content, title, author_id, category, tags, is_draft)
  101. if story.category is not None:
  102. category = {'id': story.category.id, 'name': story.category.name}
  103. else:
  104. category = None
  105. json_story = {
  106. 'id': story.id,
  107. 'name': story.title,
  108. 'content': story.content,
  109. 'tags': story.tags.split(','),
  110. 'author': {
  111. 'id': story.user.id,
  112. 'name': story.user.username,
  113. 'avatar': story.user.avatar
  114. },
  115. 'comments': [],
  116. 'category': category,
  117. 'date': str(story.date),
  118. 'is_draft': str(is_draft)
  119. }
  120. self.set_status(200, 'Ok')
  121. self.set_header("Access-Control-Allow-Origin", "*")
  122. self.write(json.dumps(json_story))
  123. @authenticated
  124. def put(self, story_id):
  125. response = {"message": "This is not a valid method for this resource."}
  126. self.set_status(405, 'Error')
  127. self.set_header("Access-Control-Allow-Origin", "*")
  128. self.write(json.dumps(response))
  129. return
  130. @authenticated
  131. def delete(self, story_id):
  132. response = {"message": "This is not a valid method for this resource."}
  133. self.set_status(405, 'Error')
  134. self.set_header("Access-Control-Allow-Origin", "*")
  135. self.write(json.dumps(response))
  136. return
  137. @coroutine
  138. def trace(self):
  139. response = {"message": "This is not a valid method for this resource."}
  140. self.set_status(405, 'Error')
  141. self.set_header("Access-Control-Allow-Origin", "*")
  142. self.write(json.dumps(response))
  143. return
  144. @coroutine
  145. def connect(self):
  146. response = {"message": "This is not a valid method for this resource."}
  147. self.set_status(405, 'Error')
  148. self.set_header("Access-Control-Allow-Origin", "*")
  149. self.write(json.dumps(response))
  150. return
  151. @coroutine
  152. def options(self, *args):
  153. response = {}
  154. self.set_header("Content-Type", "test/plain;charset=UTF-8")
  155. self.set_header("Access-Control-Allow-Origin", "*")
  156. self.set_header("Access-Control-Allow-Headers", "Authorization")
  157. self.set_header("Access-Control-Allow-Methods ", "GET, POST, PUT, DELETE, OPTIONS")
  158. self.set_status(200, "Ok")
  159. self.write(response)
  160. return
  161. @coroutine
  162. def patch(self):
  163. response = {"message": "This is not a valid method for this resource."}
  164. self.set_status(405, 'Error')
  165. self.set_header("Access-Control-Allow-Origin", "*")
  166. self.write(json.dumps(response))
  167. return
  168. @coroutine
  169. def head(self):
  170. response = {"message": "This is not a valid method for this resource."}
  171. self.set_status(405, 'Error')
  172. self.set_header("Access-Control-Allow-Origin", "*")
  173. self.write(json.dumps(response))
  174. return
  175. @staticmethod
  176. def save_story(session, content, title, author_id, category, tags, is_draft):
  177. user = session.query(User).filter(User.id == author_id).one()
  178. current_date = datetime.datetime.now()
  179. story = Story()
  180. story.title = title
  181. story.content = str(content)
  182. story.category = category
  183. story.user_id = author_id
  184. story.tags = tags
  185. story.date = current_date
  186. story.is_draft = is_draft
  187. user.stories.append(story)
  188. session.commit()
  189. return story
  190. class DraftsByUserHandler(AuthenticatedHandler):
  191. # GET /user/stories
  192. def get(self, user_id):
  193. session = self.settings['db']
  194. data = []
  195. # TODO: esto no siempre es verdadero.
  196. # Asumimos que el usuario siempre existe.
  197. user = session.query(User).filter(User.id == user_id).one()
  198. all_stories = user.stories.filter(Story.is_draft == False)
  199. for story in all_stories:
  200. if story.category is None:
  201. category = {'id': -1, 'name': "Uncategorized"}
  202. else:
  203. category = {'id': story.category.id, 'name': story.category.name}
  204. json_story = {
  205. 'id': story.id,
  206. 'name': story.title,
  207. 'author': {
  208. 'id': user.id,
  209. 'name': user.username,
  210. 'avatar': user.avatar,
  211. 'signature': user.signature
  212. },
  213. 'comments': len(story.comments),
  214. 'category': category,
  215. 'is_draft': story.is_draft
  216. }
  217. data.append(json_story)
  218. response = {"page": 1, "stories": data}
  219. self.set_header("Content-Type", "application/jsonp;charset=UTF-8")
  220. self.set_header("Access-Control-Allow-Origin", "*")
  221. self.write(response)