Commits

ronald martinez committed b814211

ok

  • Participants
  • Parent commits 4d525fb
  • Branches dev2

Comments (0)

Files changed (5)

File controllers/__init__.py

 import cPickle
 import settings
-import urllib
-import logging
-import simplejson
 import memcache
+import logging
 
 from models import User
 from tornado.web import RequestHandler
             return None
         else:
 
-            cookie_user = cPickle.loads(cookie)
-
-            user = Session.query(User).filter_by(
-                fbid=cookie_user.get('user_id')).first()
-
-            if user:
+            try:
+                cookie_user = cPickle.loads(cookie)
+            except Exception as exc:
+                logging.error(exc)
+                return None
+            else:
 
-                user.access_token = self.user_data_facebook.get('access_token')
-
-            return user
+                return Session.query(User).filter_by(
+                    fbid=cookie_user.get('user_id')).first()
 
     def render_string(self, template, **kwargs):
 
     def render(self, template, **kwargs):
 
         self.finish(self.render_string(template, **kwargs))
-
-    def load_data_url(self, url, params, json=True):
-
-        try:
-            data = urllib.urlopen('%s?%s' % (
-                url, urllib.urlencode(params))).read()
-
-            if json:
-                data = simplejson.loads(data)
-
-        except Exception as exc:
-            logging.error(exc)
-            data = None
-
-        return data
-
-    def pagination(self, limit, page):
-
-        if not page.isdigit():
-            page = int(page)
-        else:
-            page = 1
-
-        offset = ((page - 1) * limit)
-
-        return (limit, offset)

File controllers/gift.py

 import logging
 import settings
+import urllib
+import simplejson
 
 from models import Gift, UserGift
 from tornado.web import authenticated
         return (between(field, left, right))
 
 
-def sql_multiquery_kwords(friend_id, items):
+def faceboook_sql(access_token, friend_id, items):
 
-    q = None
-    tmp_queries = []
+    def sql_multiquery_kwords(friend_id, items):
 
-    for x in items:
+        q = None
+        tmp_queries = []
 
-        sku = x.sku
-        keywords = x.keywords.split(',')
+        for x in items:
 
-        kwors = ''
-        tmp_keywords_sql = []
+            sku = x.sku
+            keywords = x.keywords.split(',')
 
-        for k in keywords:
+            kwors = ''
+            tmp_keywords_sql = []
 
-            tmp_keywords_sql.append(
-                "strpos(lower(message), '%s') >= 0" % k.lower())
+            for k in keywords:
 
-        if tmp_keywords_sql:
-            kwors = ' or '.join(tmp_keywords_sql)
-            kwors = ' and (%s)' % kwors
+                tmp_keywords_sql.append(
+                    "strpos(lower(message), '%s') >= 0" % k.lower())
 
-        tmp_queries.append(
-            '"%s": "select uid from status where uid=%s %s"' % (
-                sku, friend_id, kwors))
+            if tmp_keywords_sql:
+                kwors = ' or '.join(tmp_keywords_sql)
+                kwors = ' and (%s)' % kwors
 
-    if tmp_queries:
-        url = ','.join(tmp_queries)
-        q = '{%s}' % url
+            tmp_queries.append(
+                '"%s": "select uid from status where uid=%s %s"' % (
+                    sku, friend_id, kwors))
 
-    return {'q': q, 'tmp_queries': tmp_queries}
+        if tmp_queries:
+            url = ','.join(tmp_queries)
+            q = '{%s}' % url
+
+            #logging.info('q: %s' % q)
+
+        return {'q': q, 'tmp_queries': tmp_queries}
+
+    q = sql_multiquery_kwords(friend_id, items)
+
+    if not q.get('tmp_queries'):
+        return None
+    else:
+        params = dict(
+            q=q.get('q'),
+            access_token=access_token
+        )
+
+        url = '%s/fql' % settings.FACEBOOK_GRAPH
+
+        print '%s?%s' % (
+                url, urllib.urlencode(params))
+
+        try:
+            data = urllib.urlopen('%s?%s' % (
+                url, urllib.urlencode(params))).read()
+            return simplejson.loads(data)
+
+        except Exception as exc:
+            logging.error(exc)
+            return None
 
 
 class Add(BaseHandler):
     @authenticated
     def get(self, friend_id, **kwargs):
 
+        Memcached.delete('509300321')
+
         user = self.current_user
         data = get_facebook_user(user.access_token, friend_id)
 
 
         if not skus:
 
-            q = sql_multiquery_kwords(
+            data = faceboook_sql(
+                user.access_token,
                 friend_id,
                 Session.query(Gift.sku, Gift.keywords).filter_by(
                     enabled=True).all()
             )
 
-            #print q
-            #return
-
-            if q.get('tmp_queries'):
-
-                params = dict(
-                    q=q.get('q'),
-                    access_token=user.access_token
-                )
-
-                data = self.load_data_url(
-                    url='%s/fql' % settings.FACEBOOK_GRAPH,
-                    params=params,
-                    json=True
-                )
-
-                #logging.info(data)
-                #return
+            if data:
 
                 if 'error' in data:
                     if data.get('error').get('type') == 'OAuthException':
 
         for x in user.gifts:
 
-            friend_data = self.load_data_url(
-                url='%s/%s' % (settings.FACEBOOK_GRAPH, x.friend_id),
-                params={'access_token': user.access_token,
-                    'fields': 'name'},
-                json=True
-            )
+            friend_data = get_facebook_user(x.friend_id, user.access_token)
 
             gifts.append({x.friend_id: x.gift})
 

File controllers/user.py

 from models import User
 
 from controllers import Session, BaseHandler
-from tornado.web import HTTPError
+from tornado.web import HTTPError, authenticated
 
 
 def window_location(redirect):
         return None
 
 
+def get_facebook_friends(access_token, user_id, limit, page):
+
+    def pagination(limit, page):
+
+        if not page.isdigit():
+            page = int(page)
+        else:
+            page = 1
+
+        offset = ((page - 1) * limit)
+
+        return (limit, offset)
+
+    limit, offset = pagination(limit, page)
+
+    params = dict(
+        access_token=access_token,
+        fields='name',
+        limit=limit,
+        offset=offset
+    )
+
+    url = '%s/%s/friends' % (settings.FACEBOOK_GRAPH, user_id)
+
+    try:
+        data = urllib.urlopen('%s?%s' % (
+            url, urllib.urlencode(params))).read()
+        return simplejson.loads(data)
+
+    except Exception as exc:
+        logging.error(exc)
+        return None
+
+
 class Authorize(BaseHandler):
 
     def check_xsrf_cookie(self):
 
         cookie = self.get_current_user()
 
-        print 'cookie', cookie
-
         if not cookie:
             self.finish(window_authorize_location('list_friends'))
         else:
     def check_xsrf_cookie(self):
         pass
 
+    @authenticated
     def get(self):
 
         ids_friends = Session.query(User).filter_by(
             fbid=self.user_data_facebook.get('user_id')).first()
 
-        #print 'ids_friends'
-
         if ids_friends:
             ids_friends = [x.friend_id for x in ids_friends.gifts]
         else:
             ids_friends = []
 
-        limit, offset = self.pagination(
+        data = get_facebook_friends(
+            self.current_user.access_token,
+            self.current_user.fbid,
             settings.PAGES_LIMIT,
             self.get_argument('page', '1')
         )
 
-        params = dict(
-            access_token=self.user_data_facebook.get('access_token'),
-            fields='name',
-            limit=limit,
-            offset=offset
-        )
-
-        data = self.load_data_url(
-            url='%s/me/friends' % settings.FACEBOOK_GRAPH,
-            params=params,
-            json=True
-        )
-
         if 'error' in data:
             if data.get('error').get('type') == 'OAuthException':
                 self.finish(window_authorize_location('list_friends'))

File load_data.py

 engine = create_engine(settings.DATABASE_DSN)
 Session = orm.sessionmaker(bind=engine)()
 
+def delete_data():
+    import subprocess
+
+    subprocess.call([
+    'mysql', '-u', 'root', '-proot', '-e',
+    'use saga_gifts; delete from gifts'])
+
 data = [
     dict(
+        title='jojo',
+        price=78,
+        sexo='male',
+        age=15,
+        category='mujer',
+        keywords=['auto2', 'cc', 'band'],
+        sku='20009',
+        gender='male'
+    ),
+    dict(
         title='carro',
         price=78,
         sexo='male',
     ),
     ]
 
+
+delete_data()
+
 for x in data:
     gift = Gift()
     gift.title = x.get('title')
     email = Column(Unicode(50), unique=True, nullable=False)
     fbid = Column(Unicode(100), unique=True, nullable=False)
     created_at = Column(DateTime, default=datetime.now)
-    #access_token = Column(Unicode(200), nullable=False)
+    access_token = Column(Unicode(200), nullable=False)
     age = Column(Integer, nullable=True)
     gender = Column(Unicode(10), nullable=True)
     gifts = relationship('UserGift', backref='user')
     import settings
     from sqlalchemy import create_engine
 
+    def drop_all():
+        import subprocess
+
+        subprocess.call([
+        'mysql', '-u', 'root', '-proot', '-e',
+        'drop database saga_gifts; create database saga_gifts'])
+
+    drop_all()
     engine = create_engine(settings.DATABASE_DSN)
     Base.metadata.create_all(engine)