Py | Tornado Facebook Upload Photo


/ Published in: Python
Save to your folder(s)



Copy this code and paste it in your HTML
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. #
  4. # Copyright (c) 2011 The Octopus Apps Inc.
  5. # Licensed under the Apache License, Version 2.0 (the "License")
  6. #
  7. # Author: Alejandro M. Bernardis
  8. # Email: alejandro.m.bernardis at gmail.com
  9. # Created: May 10, 2011 7:18:55 PM
  10. #
  11.  
  12. import os
  13. import urllib
  14. import urllib2
  15. import datetime
  16. import tornado.auth
  17. import tornado.escape
  18. import tornado.web
  19. #
  20. from uuid import uuid1
  21. from poster.encode import multipart_encode
  22. from poster.streaminghttp import register_openers
  23.  
  24. class SimpleRequest(object):
  25.  
  26. def __init__(self, path, token, args={}, post_args=None):
  27. self._path = path
  28. self._token = token
  29. self._args = args
  30. self._post_data = post_args
  31.  
  32. def read(self):
  33. post_data = None
  34.  
  35. if self._post_data is not None:
  36. self._post_data["access_token"] = self._token
  37. post_data = urllib.urlencode(self._post_data)
  38.  
  39. else:
  40. self._args["access_token"] = self._token
  41.  
  42. path = "https://graph.facebook.com%s?%s" % (self._path, urllib.urlencode(self._args))
  43. request = urllib.urlopen(path, post_data)
  44.  
  45. try:
  46. response = tornado.escape.json_decode(request.read())
  47.  
  48. except:
  49. return False, "-1"
  50.  
  51. finally:
  52. request.close()
  53.  
  54. if response.get("error"):
  55. return False, response.get("error")
  56.  
  57. return True, response
  58.  
  59. class BaseHandler(tornado.web.RequestHandler):
  60.  
  61. def get_access_token(self):
  62. token = self.current_user["access_token"]
  63. if not token:
  64. return None
  65. return token
  66.  
  67. def get_key(self, source, key, default=None):
  68. try:
  69. return source[key]
  70. except:
  71. return default
  72.  
  73.  
  74. class PostPhotoHandler(BaseHandler, tornado.auth.FacebookGraphMixin):
  75.  
  76. @tornado.web.authenticated
  77. def get(self):
  78. self.render('fbupload.html')
  79.  
  80. @tornado.web.authenticated
  81. def post(self):
  82. error = "-1"
  83. argument = "Filedata"
  84.  
  85. if argument in self.request.files:
  86. success, data = SimpleRequest("/me/albums", self.get_access_token()).read()
  87.  
  88. if success:
  89. album_id = None
  90. album_name = self.get_argument("album", self.settings["facebook_album_name"])
  91. album_message = self.get_argument("album_message", "")
  92.  
  93. for a in data["data"]:
  94. if a["name"] == album_name:
  95. album_id = str(a["id"])
  96.  
  97. if not album_id:
  98. success, data = SimpleRequest("/me/albums", self.get_access_token(), post_args={
  99. "name": album_name,
  100. "message": album_message
  101. }).read()
  102.  
  103. if success:
  104. album_id = str(data["id"])
  105.  
  106. else:
  107. error = "6"
  108.  
  109. if album_id is not None:
  110. path = 'https://graph.facebook.com/%s/photos' % album_id
  111. file = self.request.files[argument][0]
  112.  
  113. to_ext = str(os.path.splitext(file['filename'])[1]).lower()
  114.  
  115. if to_ext in ['.jpg', '.jpge', '.png', '.gif']:
  116. to_name = uuid1().hex
  117. to_file = '%s/%s%s' % (self.settings["upload_path"],
  118. to_name, to_ext)
  119.  
  120. try:
  121. f = open(to_file, 'w')
  122. f.write(file["body"])
  123.  
  124. except Exception:
  125. if f: f.close()
  126. error = "5"
  127.  
  128. finally:
  129. if f:
  130. f.close()
  131.  
  132. register_openers()
  133.  
  134. datagen, headers = multipart_encode({
  135. "access_token": self.get_access_token(),
  136. "message": self.get_argument("message", self.settings["facebook_title"]),
  137. "source": open(to_file)
  138. })
  139.  
  140. try:
  141. request = urllib2.Request(path, datagen, headers)
  142. error = tornado.escape.json_decode(urllib2.urlopen(request).read())
  143.  
  144. if error.get("id"):
  145. error = tornado.escape.json_encode({
  146. 'fbid': error.get("id"),
  147. 'name': to_name,
  148. 'extension': to_ext,
  149. 'path': '/static/upload/',
  150. 'content-type': file["content_type"],
  151. 'url': '%s://%s/static/upload/%s%s' % (
  152. self.request.protocol,
  153. self.request.host,
  154. to_name,
  155. to_ext
  156. )
  157. })
  158.  
  159. except urllib2.HTTPError, urllib2.URLError:
  160. error = "4"
  161.  
  162. else:
  163. error = "3"
  164.  
  165. else:
  166. error = "2"
  167.  
  168. else:
  169. error = "1"
  170.  
  171. self.finish(str(error))

URL: http://www.alejandrob.com.ar/

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.