Return to Snippet

Revision: 47055
at May 31, 2011 11:53 by alejandrombernardis


Initial Code
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright (c) 2011 The Octopus Apps Inc.
# Licensed under the Apache License, Version 2.0 (the "License")
#
# Author: Alejandro M. Bernardis
# Email: alejandro.m.bernardis at gmail.com
# Created: May 10, 2011 7:18:55 PM
#

import os
import urllib
import urllib2
import datetime
import tornado.auth
import tornado.escape
import tornado.web
#	
from uuid import uuid1
from poster.encode import multipart_encode
from poster.streaminghttp import register_openers

class SimpleRequest(object):
    
    def __init__(self, path, token, args={}, post_args=None):
        self._path = path
        self._token = token
        self._args = args
        self._post_data = post_args
        
    def read(self):
        post_data = None
        
        if self._post_data is not None:
            self._post_data["access_token"] = self._token
            post_data = urllib.urlencode(self._post_data)
            
        else:
            self._args["access_token"] = self._token
        
        path = "https://graph.facebook.com%s?%s" % (self._path, urllib.urlencode(self._args))
        request = urllib.urlopen(path, post_data)
        
        try:
            response = tornado.escape.json_decode(request.read())
        
        except:
            return False, "-1"
            
        finally:
            request.close()
        
        if response.get("error"):
            return False, response.get("error")
        
        return True, response

class BaseHandler(tornado.web.RequestHandler):
       
    def get_access_token(self):
        token = self.current_user["access_token"]
        if not token:
            return None
        return token
    
    def get_key(self, source, key, default=None):
        try:
            return source[key]
        except:
            return default


class PostPhotoHandler(BaseHandler, tornado.auth.FacebookGraphMixin):
    
    @tornado.web.authenticated
    def get(self):
        self.render('fbupload.html')
    
    @tornado.web.authenticated
    def post(self):
        error = "-1"
        argument = "Filedata"
        
        if argument in self.request.files:
            success, data = SimpleRequest("/me/albums", self.get_access_token()).read()
            
            if success:
                album_id = None
                album_name = self.get_argument("album", self.settings["facebook_album_name"])
                album_message = self.get_argument("album_message", "")
                                
                for a in data["data"]:
                    if a["name"] == album_name:
                        album_id = str(a["id"]) 
                
                if not album_id:
                    success, data = SimpleRequest("/me/albums", self.get_access_token(), post_args={
                        "name": album_name, 
                        "message": album_message
                    }).read()
                    
                    if success:
                        album_id = str(data["id"])
                    
                    else:
                        error = "6"
                        
                if album_id is not None:
                    path = 'https://graph.facebook.com/%s/photos' % album_id
                    file = self.request.files[argument][0]
                    
                    to_ext = str(os.path.splitext(file['filename'])[1]).lower()
                    
                    if to_ext in ['.jpg', '.jpge', '.png', '.gif']:     
                        to_name = uuid1().hex
                        to_file = '%s/%s%s' % (self.settings["upload_path"], 
                                               to_name, to_ext)
                        
                        try:
                            f = open(to_file, 'w')
                            f.write(file["body"])
                            
                        except Exception:
                            if f: f.close()
                            error = "5"
                            
                        finally:
                            if f:
                                f.close()
                                
                                register_openers()
                                
                                datagen, headers = multipart_encode({
                                    "access_token": self.get_access_token(),
                                    "message": self.get_argument("message", self.settings["facebook_title"]),
                                    "source": open(to_file)
                                })
                                
                                try:
                                    request = urllib2.Request(path, datagen, headers)
                                    error = tornado.escape.json_decode(urllib2.urlopen(request).read())
                                    
                                    if error.get("id"):
                                        error = tornado.escape.json_encode({
                                            'fbid': error.get("id"), 
                                            'name': to_name,
                                            'extension': to_ext,
                                            'path': '/static/upload/',
                                            'content-type': file["content_type"],
                                            'url': '%s://%s/static/upload/%s%s' % (
                                                self.request.protocol, 
                                                self.request.host, 
                                                to_name, 
                                                to_ext
                                            )
                                        })
                                    
                                except urllib2.HTTPError, urllib2.URLError:
                                    error = "4"
                                    
                    else:
                        error = "3"
                        
            else:
                error = "2"
            
        else:
            error = "1"
            
        self.finish(str(error))

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

Initial Description

                                

Initial Title
Py | Tornado Facebook Upload Photo

Initial Tags
facebook

Initial Language
Python