Example #1
0
def get_devices():
    ip_range = get_ip_range()
    for result in conn.query("SELECT * FROM device_log"):
        if result['ipv4'].startswith(ip_range):
            devices[result['ipv4']] = result['name'], result['mac']
    for result in conn.query("SELECT * FROM device_monitor"):
        monitored_devices[result['ipv4']] = result['name']
Example #2
0
def get_public_feed(item_offset=15, item_start_id=None):
    if item_start_id:
        last_post = conn.get("SELECT * FROM index_posts WHERE entity_id = %s",
                             item_start_id)
        posts = conn.query(
            "SELECT * FROM index_posts WHERE rank < %s ORDER BY rank DESC LIMIT 0, %s",
            last_post["rank"], item_offset)
    else:
        posts = conn.query(
            "SELECT * FROM index_posts ORDER BY rank DESC LIMIT 0, %s",
            item_offset)
    item_ids = [i["entity_id"] for i in posts]

    if posts:
        items = [
            dict(item, id=item_id)
            for item_id, item in nomagic._get_entities_by_ids(item_ids)
        ]
        return [
            dict(
                item,
                like_count=len(item.get("likes", [])),
                comment_count=len(item.get("comment_ids", [])),
                url=item.get("url"),
            ) for item in items
        ]
    return []
Example #3
0
File: main.py Project: kenans/front
    def get(self):
        page = self.get_argument("page", "0")
        if not page.isdigit():
            return
        page = int(page)

        board_id = self.get_argument("board_id", "0")
        if not board_id.isdigit():
            return
        board_id = int(board_id)
        if board_id == 0:
            collection = conn.query("SELECT * FROM collection ORDER BY id DESC LIMIT %s, 20", page*20)
        else:
            collection = conn.query("SELECT * FROM collection WHERE board_id = %s ORDER BY id DESC LIMIT %s, 20", board_id, page*20)

        if self.current_user:
            ids = tuple([i["id"] for i in collection])
            if len(ids) > 1:
                likes = conn.query("SELECT * FROM likes WHERE user_id=%s AND collection_id IN %s", self.current_user["id"], ids)
            elif len(ids) == 1:
                likes = conn.query("SELECT * FROM likes WHERE user_id=%s AND collection_id = %s", self.current_user["id"], ids[0])
            else:
                self.write({"collection":[]})
                return

            liked = set([i["collection_id"] for i in likes])
            for i in collection:
                i["liked"] = i["id"] in liked

        self.write({"collection":collection})
Example #4
0
def daily(hours):
    now = time.time()
    offset = 0
    post_ids_to_email = set()
    while True:
        index_posts = conn.query(
            "SELECT * FROM index_posts ORDER BY rank DESC LIMIT %s, 100",
            offset)

        if len(index_posts) == 0:
            break

        post_ids = [post["entity_id"] for post in index_posts]
        for post_id, post in nomagic._get_entities_by_ids(post_ids):
            period = (now - time.mktime(
                datetime.datetime.strptime(
                    post["datetime"],
                    "%Y-%m-%dT%H:%M:%S.%f").timetuple())) / 3600

            if period <= hours:
                post_ids_to_email.add(post_id)

        offset += 100

    posts_to_email = nomagic._get_entities_by_ids(post_ids_to_email)
    loader = tornado.template.Loader(
        os.path.dirname(os.path.abspath(__file__)) + "/../template/")

    locale = tornado.locale.get()
    msg = amazon_ses.EmailMessage()
    msg.subject = locale.translate('Pythonic Info Daily').encode("utf-8")
    msg.bodyHtml = loader.load("email_daily.html").generate(
        posts=posts_to_email, _=locale.translate)

    users = []
    users_not_to_send = []
    users_exists = conn.query("SELECT * FROM index_login")
    for user_id, user in nomagic._get_entities_by_ids(
        [user_exists["entity_id"] for user_exists in users_exists]):
        if user.get("receive_daily_email", True):
            users.append(user)
        else:
            users_not_to_send.append(user)

    users_invited = conn.query("SELECT * FROM invite")

    sender = amazon_ses.AmazonSES(settings["AmazonAccessKeyID"],
                                  settings["AmazonSecretAccessKey"])
    emails = set([user["login"] for user in users_exists] +
                 [user["email"] for user in users_invited]) - set(
                     [user["email"] for user in users_not_to_send])
    for email in emails:
        if "@" in email:
            print email
            sender.sendEmail(settings["email_sender"], email, msg)
Example #5
0
 def post(self):
     username = self.get_argument("username", None)
     password = self.get_argument("password", None)
     print username
     print password
     result = conn.query(
         "SELECT COUNT(*) FROM member WHERE member_username = %s AND member_password = PASSWORD(%s)",
         username, password)
     print result
     if result[0]['COUNT(*)'] > 0:
         user_id = result[0].get("entity_id", "")
         print result
         print u"=== 登录 ==="
         self.set_secure_cookie("user",
                                tornado.escape.json_encode({
                                    "id": user_id,
                                    "v": 1
                                }),
                                expires=time.time() + 63072000,
                                domain=settings.get("cookie_domain"))
         self.finish({
             "info": "success",
             "login_account": username,
             "action": "redirect",
             "redirect_uri": "/"
         })
         return
     else:
         print u"=== 账号密码错误 ==="
         self.finish({"info": "reload"})
Example #6
0
def ranking():
    now = time.time()
    offset = 0
    while True:
        index_posts = conn.query(
            "SELECT * FROM index_posts ORDER BY rank DESC LIMIT %s, 100",
            offset)

        if len(index_posts) == 0:
            break

        post_ids = [post["entity_id"] for post in index_posts]
        for post_id, post in nomagic._get_entities_by_ids(post_ids):
            period = (now - time.mktime(
                datetime.datetime.strptime(
                    post["datetime"],
                    "%Y-%m-%dT%H:%M:%S.%f").timetuple())) / 3600
            points = len(post["likes"])
            post_rank = rank(points, period)

            conn.execute(
                "UPDATE index_posts SET rank = %s WHERE entity_id = %s",
                post_rank, post_id)

        offset += 100
Example #7
0
    def get(self):
        global current_remote_ip, queue_ips, authed_ips, waiting_clients
        if current_remote_ip not in authed_ips:
            authed_ips.add(current_remote_ip)

        current_client = waiting_clients.get(current_remote_ip)
        if current_client:
            device_logs = conn.query("SELECT * FROM device_log WHERE ipv4 = %s ORDER BY id DESC", current_remote_ip)
            if len(device_logs) == 0:
                self.finish({"error": "Can't find MAC address by the IP!"})
                return
            mac = device_logs[0]["mac"]

            current_client.finish({"msg":"online_now", "position": 0, "redirect": "http://10.0.0.1:2060/wifidog/auth?token=%s" % mac})
            del waiting_clients[current_remote_ip]

        for ip in queue_ips:
            client = waiting_clients.get(ip)
            if client:
                del waiting_clients[ip]
            position = queue_ips.index(ip)
            if position:
                client.finish({"msg":"queue", "position":position})
            else:
                client.finish({"msg":"ring_the_bell", "position":position})

        if queue_ips:
            current_remote_ip = queue_ips.pop(0)
        else:
            current_remote_ip = None

        self.finish({"length_of_queue": len(queue_ips)})
Example #8
0
    def post(self):
        email = self.get_argument("email")
        """
        reg = conn_remote.get("SELECT * FROM event_reg WHERE email = %s", email)
        if not reg:
            self.finish("You email is not registered.")
            return
        """

        regs = conn_remote.query("SELECT * FROM event_reg_mac WHERE email = %s", email)
        if len(regs) >= 2:
            self.finish("Sorry, your email has been used for too many times")
            return

        # find mac by ip?
        remote_ip = self.request.remote_ip if self.request.remote_ip != '127.0.0.1' else self.request.headers['X-Forwarded-For']
        device_logs = conn.query("SELECT * FROM device_log WHERE ipv4 = %s ORDER BY id DESC", remote_ip)
        if len(device_logs) == 0:
            self.finish("Something wrong!")
            return
        mac = device_logs[0]["mac"]

        conn_remote.execute("INSERT INTO event_reg_mac (email, mac) VALUES(%s, %s)", email, mac)

        # create an unquie token in database
        self.redirect("http://10.0.0.1:2060/wifidog/auth?token=%s" % mac)
Example #9
0
    def get(self):
        next = self.get_argument("next", "")
        if next:
            next = "?next="+next

        collection = conn.query("SELECT * FROM collection WHERE user_id = %s", self.current_user['id'])
        self.render("./template/partners/dashboard.html", user=self.current_user, collection=collection, next=next, version=setting.VERSION)
Example #10
0
def get_public_feed(item_offset=15, item_start_id=None):
    if item_start_id:
        last_post = conn.get("SELECT * FROM index_posts WHERE entity_id = %s", item_start_id)
        posts = conn.query("SELECT * FROM index_posts WHERE rank < %s ORDER BY rank DESC LIMIT 0, %s", last_post["rank"], item_offset)
    else:
        posts = conn.query("SELECT * FROM index_posts ORDER BY rank DESC LIMIT 0, %s", item_offset)
    item_ids = [i["entity_id"] for i in posts]

    if posts:
        items = [dict(item, id=item_id)
                        for item_id, item in nomagic._get_entities_by_ids(item_ids)]
        return [dict(item,
                     like_count = len(item.get("likes", [])),
                     comment_count = len(item.get("comment_ids", [])),
                     url = item.get("url"),
                     ) for item in items]
    return []
Example #11
0
    def get(self):
        wp_perfix = settings.get("wordpress_prefix", "wp_")

        term = self.get_argument("t", None)
        if term:
            term_record = conn.get("SELECT * FROM "+wp_perfix+"terms WHERE slug = %s", term)
            term_taxonomy = conn.get("SELECT * FROM "+wp_perfix+"term_taxonomy WHERE term_id = %s", term_record["term_id"])
            object_records = conn.query("SELECT * FROM "+wp_perfix+"term_relationships WHERE term_taxonomy_id = %s ORDER BY object_id DESC LIMIT 5", term_taxonomy["term_taxonomy_id"])
            self.post_list = conn.query("SELECT * FROM "+wp_perfix+"posts WHERE post_status = 'publish' AND post_type = 'post' AND ID IN %s ORDER BY ID DESC", tuple([i["object_id"] for i in object_records]))
            self.term = "&t=%s" % term
        else:
            self.post_list = conn.query("SELECT * FROM "+wp_perfix+"posts WHERE post_status = 'publish' AND post_type = 'post' ORDER BY ID DESC LIMIT 5")
            self.term = ""

        post_thumbnail_ids = {}
        meta_thumbnails = {}
        post_thumbnails = {}

        postmeta_list = conn.query("SELECT * FROM "+wp_perfix+"postmeta WHERE meta_key = '_thumbnail_id' AND post_id IN %s", tuple([int(i.ID) for i in self.post_list]))
        for postmeta in postmeta_list:
            post_thumbnail_ids[postmeta.post_id] = postmeta.meta_value

        postmeta_list = conn.query("SELECT * FROM "+wp_perfix+"postmeta WHERE meta_key = '_wp_attached_file' AND post_id IN %s" , tuple([int(i) for i in post_thumbnail_ids.values()]))
        for postmeta in postmeta_list:
            meta_thumbnails[postmeta.post_id] = postmeta.meta_value

        for k, v in post_thumbnail_ids.iteritems():
            post_thumbnails[k] = meta_thumbnails[long(v)]

        self.post_id_from = self.post_list[-1].ID
        self.carousel_list = []
        carousel_count = 0
        color_count = 0
        for post in self.post_list:
            post.thumbnail = "/wp-content/uploads/%s" % post_thumbnails[post.ID] if post_thumbnails.get(post.ID) else None
            if post.thumbnail and carousel_count < 3:
                self.carousel_list.append(post)
                carousel_count += 1

            soup = BeautifulSoup(post.post_content.split("<!--more-->")[0])
            post.post_excerpt = soup.get_text()

            post.color = POST_COLORS[color_count % len(POST_COLORS)]
            color_count += 1

        self.render('../template/main.html')
Example #12
0
def daily(hours):
    now = time.time()
    offset = 0
    post_ids_to_email = set()
    while True:
        index_posts = conn.query("SELECT * FROM index_posts ORDER BY rank DESC LIMIT %s, 100", offset)

        if len(index_posts) == 0:
            break

        post_ids = [post["entity_id"] for post in index_posts]
        for post_id, post in nomagic._get_entities_by_ids(post_ids):
            period = (now - time.mktime(datetime.datetime.strptime(post["datetime"], "%Y-%m-%dT%H:%M:%S.%f").timetuple())) / 3600

            if period <= hours:
                post_ids_to_email.add(post_id)

        offset += 100

    posts_to_email = nomagic._get_entities_by_ids(post_ids_to_email)
    loader = tornado.template.Loader(os.path.dirname(os.path.abspath(__file__)) + "/../template/")

    locale = tornado.locale.get()
    msg = amazon_ses.EmailMessage()
    msg.subject = locale.translate('Pythonic Info Daily').encode("utf-8")
    msg.bodyHtml = loader.load("email_daily.html").generate(posts=posts_to_email, _=locale.translate)

    users = []
    users_not_to_send = []
    users_exists = conn.query("SELECT * FROM index_login")
    for user_id, user in nomagic._get_entities_by_ids([user_exists["entity_id"] for user_exists in users_exists]):
        if user.get("receive_daily_email", True):
            users.append(user)
        else:
            users_not_to_send.append(user)

    users_invited = conn.query("SELECT * FROM invite")

    sender = amazon_ses.AmazonSES(settings["AmazonAccessKeyID"], settings["AmazonSecretAccessKey"])
    emails = set([user["login"] for user in users_exists] + [user["email"] for user in users_invited]) - set([user["email"] for user in users_not_to_send])
    for email in emails:
        if "@" in email:
            print email
            sender.sendEmail(settings["email_sender"], email, msg)
Example #13
0
    def get(self):
        wp_perfix = settings.get("wordpress_prefix", "wp_")

        from_id = int(self.get_argument("from", ""))
        term = self.get_argument("t", None)
        if term:
            term_record = conn.get("SELECT * FROM "+wp_perfix+"terms WHERE slug = %s", term)
            term_taxonomy = conn.get("SELECT * FROM "+wp_perfix+"term_taxonomy WHERE term_id = %s", term_record["term_id"])
            object_records = conn.query("SELECT * FROM "+wp_perfix+"term_relationships WHERE term_taxonomy_id = %s AND object_id < %s ORDER BY object_id DESC LIMIT 5", term_taxonomy["term_taxonomy_id"], from_id)
            post_list = conn.query("SELECT * FROM "+wp_perfix+"posts WHERE post_status = 'publish' AND post_type = 'post' AND ID IN %s ORDER BY ID DESC", tuple([i["object_id"] for i in object_records]))
            self.term = "&t=%s" % term
        else:
            post_list = conn.query("SELECT * FROM "+wp_perfix+"posts WHERE post_status = 'publish' AND post_type = 'post' AND ID < %s ORDER BY ID DESC LIMIT 5", from_id)

        post_thumbnail_ids = {}
        meta_thumbnails = {}
        post_thumbnails = {}

        postmeta_list = conn.query("SELECT * FROM "+wp_perfix+"postmeta WHERE meta_key = '_thumbnail_id' AND post_id IN %s", tuple([int(i.ID) for i in post_list]))
        for postmeta in postmeta_list:
            post_thumbnail_ids[postmeta.post_id] = postmeta.meta_value

        postmeta_list = conn.query("SELECT * FROM "+wp_perfix+"postmeta WHERE meta_key = '_wp_attached_file' AND post_id IN %s" , tuple([int(i) for i in post_thumbnail_ids.values()]))
        for postmeta in postmeta_list:
            meta_thumbnails[postmeta.post_id] = postmeta.meta_value

        for k, v in post_thumbnail_ids.iteritems():
            post_thumbnails[k] = meta_thumbnails[long(v)]

        post_list_json = []
        color_count = 0
        for post in post_list:
            soup = BeautifulSoup(post.post_content.split("<!--more-->")[0])
            post_json = {}
            post_json["post_excerpt"] = soup.get_text()
            post_json["post_title"] = post.post_title
            post_json["post_name"] = post.post_name
            post_json["thumbnail"] = "/wp-content/uploads/%s" % post_thumbnails[post.ID] if post_thumbnails.get(post.ID) else None
            post_json["color"] = POST_COLORS[color_count % len(POST_COLORS)]
            color_count += 1

            post_list_json.append(post_json)

        self.finish({"list":post_list_json, "post_id_from":post_list[-1].ID if post_list else 0})
Example #14
0
File: main.py Project: kenans/front
 def get(self):
     if self.current_user:
         board_id = self.get_argument("id", None)
         if board_id:
             board = conn.get("SELECT * FROM boards WHERE user_id = %s and id = %s", self.current_user["id"], board_id)
             self.finish({"board": board,"error":None})
             return
         boards = conn.query("SELECT * FROM boards WHERE user_id = %s", self.current_user["id"])
         self.finish({"boards":boards, "error":None})
     else:
         self.finish({"error":"login required"})
Example #15
0
File: main.py Project: kenans/front
    def get(self, city="Singapore"):
        next = self.get_argument("next", "")
        if next:
            next = "?next="+next
        global CATEGORIES
        global CITIES

        if not self.current_user:
            self.collection = conn.query("SELECT * FROM collection ORDER BY id DESC LIMIT 0, 20")

        self.render("./template/index.html", user=self.current_user, categories=CATEGORIES, cities=CITIES, next=next, version=VERSION)
Example #16
0
    def get(self, type):
        print self.request.query == ""

        types = {'1x4.js':4, '2x2.js':4, '4x1.js':4, '2x2s.js':4, '6x1s.js':6, 'test.js':6}
        if type in types: #404
            ret = types[type]
        else:
            self.finish()
            return

        #memcache for every table update
        links = [(i["weight"], i["collection_id"]) for i in conn.query("SELECT collection_id, weight FROM widget_links WHERE weight > 0")]
        collection_ids = WidgetHandler.weighted_shuffle(links, ret)
        collection_ids.sort()
        #print collection_ids

        #cache by collection_ids hash
        collection = conn.query("SELECT * FROM collection WHERE id in %s ORDER BY id DESC", collection_ids)
        #random.shuffle(collection)

        #jsmin.jsmin doesnt work here
        self.write(self.render_string("./template/widget/%s" % type, images=collection))
Example #17
0
    def get(self):
        #/wifi/login/?gw_address=10.0.0.1&gw_port=2060&gw_id=0C8268174423&url=http%3A//init-p01st.push.apple.com/bag
        #gw_address = self.get_argument("gw_address")
        #gw_port = self.get_argument("gw_port")
        #gw_id = self.get_argument("gw_id")
        #url = self.get_argument("url")

        # find mac by ip?
        remote_ip = self.request.remote_ip if self.request.remote_ip != '127.0.0.1' else self.request.headers['X-Forwarded-For']
        device_logs = conn.query("SELECT * FROM device_log WHERE ipv4 = %s ORDER BY id DESC", remote_ip)
        if len(device_logs) == 0:
            self.finish({"error": "Can't find MAC address by the IP!"})
            return

        self.render("../template/wifi/waiting.html")
Example #18
0
def get_public_news_feed(activity_offset=10, activity_start_id=None):
    if activity_start_id:
        pass
    else:
        posts = conn.query("SELECT * FROM index_posts ORDER BY id DESC LIMIT 0, %s", activity_offset)
    activity_ids = [i["entity_id"] for i in posts]

    if posts:
        activities = [dict(activity, id=activity_id)
                        for activity_id, activity in nomagic._get_entities_by_ids(activity_ids)]
        return [dict(activity,
                     like_count = len(activity.get("likes", [])),
                     comment_count = len(activity.get("comment_ids", [])),
                     ) for activity in activities]
    return []
Example #19
0
    def get(self):
        global authed_ips
        # find the mac address, user ip by token
        #/wifi/auth/?stage=login&ip=10.0.0.18&mac=84:38:35:52:ea:08&token=1234&incoming=0&outgoing=0&gw_id=0810781EE54D
        mac = self.get_argument("mac")

        device_logs = conn.query("SELECT * FROM device_log WHERE mac = %s ORDER BY id DESC", mac)
        if len(device_logs) == 0:
            self.finish({"error": "Can't find MAC address by the IP!"})
            return
        ipv4 = device_logs[0]["ipv4"]

        if ipv4 in authed_ips:
            self.finish("Auth: 1") #success
            return

        self.finish("Auth: 0")
Example #20
0
def ranking():
    now = time.time()
    offset = 0
    while True:
        index_posts = conn.query("SELECT * FROM index_posts ORDER BY rank DESC LIMIT %s, 100", offset)

        if len(index_posts) == 0:
            break

        post_ids = [post["entity_id"] for post in index_posts]
        for post_id, post in nomagic._get_entities_by_ids(post_ids):
            period = (now - time.mktime(datetime.datetime.strptime(post["datetime"], "%Y-%m-%dT%H:%M:%S.%f").timetuple())) / 3600
            points = len(post["likes"])
            post_rank = rank(points, period)

            conn.execute("UPDATE index_posts SET rank = %s WHERE entity_id = %s", post_rank, post_id)

        offset += 100
Example #21
0
    def get(self):
        #/wifi/login/?gw_address=10.0.0.1&gw_port=2060&gw_id=0C8268174423&url=http%3A//init-p01st.push.apple.com/bag
        #gw_address = self.get_argument("gw_address")
        #gw_port = self.get_argument("gw_port")
        #gw_id = self.get_argument("gw_id")
        #url = self.get_argument("url")

        # find mac by ip?
        remote_ip = self.request.remote_ip if self.request.remote_ip != '127.0.0.1' else self.request.headers['X-Forwarded-For']
        device_logs = conn.query("SELECT * FROM device_log WHERE ipv4 = %s ORDER BY id DESC", remote_ip)
        if len(device_logs) == 0:
            self.finish("Something wrong!")
            return
        mac = device_logs[0]["mac"]

        # find email by mac?
        reg = conn_remote.get("SELECT * FROM event_reg_mac WHERE mac = %s", mac)
        if reg:
            self.redirect("http://10.0.0.1:2060/wifidog/auth?token=%s" % mac)
            return

        self.render("../template/wifi/login.html")
Example #22
0
def get_public_news_feed(activity_offset=10, activity_start_id=None):
    if activity_start_id:
        pass
    else:
        posts = conn.query(
            "SELECT * FROM index_posts ORDER BY id DESC LIMIT 0, %s",
            activity_offset)
    activity_ids = [i["entity_id"] for i in posts]

    if posts:
        activities = [
            dict(activity, id=activity_id) for activity_id, activity in
            nomagic._get_entities_by_ids(activity_ids)
        ]
        return [
            dict(
                activity,
                like_count=len(activity.get("likes", [])),
                comment_count=len(activity.get("comment_ids", [])),
            ) for activity in activities
        ]
    return []
Example #23
0
    def get(self):
        wp_perfix = settings.get("wordpress_prefix", "wp_")

        from_id = int(self.get_argument("from", ""))
        term = self.get_argument("t", None)
        if term:
            term_record = conn.get(
                "SELECT * FROM %sterms WHERE slug = %s" % (wp_perfix, "%s"),
                term)
            term_taxonomy = conn.get(
                "SELECT * FROM %sterm_taxonomy WHERE term_id = %s" %
                (wp_perfix, "%s"), term_record["term_id"])
            object_records = conn.query(
                "SELECT * FROM %sterm_relationships WHERE term_taxonomy_id = %s AND object_id < %s ORDER BY object_id DESC LIMIT 5"
                % (wp_perfix, "%s", "%s"), term_taxonomy["term_taxonomy_id"],
                from_id)
            post_list = conn.query(
                "SELECT * FROM %sposts WHERE post_status = 'publish' AND post_type = 'post' AND ID IN %s ORDER BY ID DESC"
                % (wp_perfix, "%s"),
                tuple([i["object_id"] for i in object_records]))
            self.term = "&t=%s" % term
        else:
            post_list = conn.query(
                "SELECT * FROM %sposts WHERE post_status = 'publish' AND post_type = 'post' AND ID < %s ORDER BY ID DESC LIMIT 5"
                % (wp_perfix, "%s"), from_id)

        post_thumbnail_ids = {}
        meta_thumbnails = {}
        post_thumbnails = {}

        postmeta_list = conn.query(
            "SELECT * FROM %spostmeta WHERE meta_key = '_thumbnail_id' AND post_id IN %s"
            % (wp_perfix, "%s"), tuple([int(i.ID) for i in post_list]))
        for postmeta in postmeta_list:
            post_thumbnail_ids[postmeta.post_id] = postmeta.meta_value

        postmeta_list = conn.query(
            "SELECT * FROM %spostmeta WHERE meta_key = '_wp_attached_file' AND post_id IN %s"
            % (wp_perfix, "%s"),
            tuple([int(i) for i in post_thumbnail_ids.values()]))
        for postmeta in postmeta_list:
            meta_thumbnails[postmeta.post_id] = postmeta.meta_value

        for k, v in post_thumbnail_ids.iteritems():
            post_thumbnails[k] = meta_thumbnails[long(v)]

        post_list_json = []
        color_count = 0
        for post in post_list:
            soup = BeautifulSoup(post.post_content.split("<!--more-->")[0])
            post_json = {}
            post_json["post_excerpt"] = soup.get_text()
            post_json["post_title"] = post.post_title
            post_json["post_name"] = post.post_name
            post_json[
                "thumbnail"] = "/wp-content/uploads/%s" % post_thumbnails[
                    post.ID] if post_thumbnails.get(post.ID) else None
            post_json["color"] = POST_COLORS[color_count % len(POST_COLORS)]
            color_count += 1

            post_list_json.append(post_json)

        self.finish({
            "list": post_list_json,
            "post_id_from": post_list[-1].ID if post_list else 0
        })
Example #24
0
    def get(self):
        wp_perfix = settings.get("wordpress_prefix", "wp_")

        term = self.get_argument("t", None)
        if term:
            term_record = conn.get(
                "SELECT * FROM %sterms WHERE slug = %s" % (wp_perfix, "%s"),
                term)
            term_taxonomy = conn.get(
                "SELECT * FROM %sterm_taxonomy WHERE term_id = %s" %
                (wp_perfix, "%s"), term_record["term_id"])
            object_records = conn.query(
                "SELECT * FROM %sterm_relationships WHERE term_taxonomy_id = %s ORDER BY object_id DESC LIMIT 5"
                % (wp_perfix, "%s"), term_taxonomy["term_taxonomy_id"])
            self.post_list = conn.query(
                "SELECT * FROM %sposts WHERE post_status = 'publish' AND post_type = 'post' AND ID IN %s ORDER BY ID DESC"
                % (wp_perfix, "%s"),
                tuple([i["object_id"] for i in object_records]))
            self.term = "&t=%s" % term
        else:
            self.post_list = conn.query(
                "SELECT * FROM %sposts WHERE post_status = 'publish' AND post_type = 'post' ORDER BY ID DESC LIMIT 5"
                % wp_perfix)
            self.term = ""

        post_thumbnail_ids = {}
        meta_thumbnails = {}
        post_thumbnails = {}

        postmeta_list = conn.query(
            "SELECT * FROM %spostmeta WHERE meta_key = '_thumbnail_id' AND post_id IN %s"
            % (wp_perfix, "%s"), tuple([int(i.ID) for i in self.post_list]))
        for postmeta in postmeta_list:
            post_thumbnail_ids[postmeta.post_id] = postmeta.meta_value

        postmeta_list = conn.query(
            "SELECT * FROM %spostmeta WHERE meta_key = '_wp_attached_file' AND post_id IN %s"
            % (wp_perfix, "%s"),
            tuple([int(i) for i in post_thumbnail_ids.values()]))
        for postmeta in postmeta_list:
            meta_thumbnails[postmeta.post_id] = postmeta.meta_value

        for k, v in post_thumbnail_ids.iteritems():
            post_thumbnails[k] = meta_thumbnails[long(v)]

        self.post_id_from = self.post_list[-1].ID
        self.carousel_list = []
        carousel_count = 0
        color_count = 0
        for post in self.post_list:
            post.thumbnail = "/wp-content/uploads/%s" % post_thumbnails[
                post.ID] if post_thumbnails.get(post.ID) else None
            if post.thumbnail and carousel_count < 3:
                self.carousel_list.append(post)
                carousel_count += 1

            soup = BeautifulSoup(post.post_content.split("<!--more-->")[0])
            post.post_excerpt = soup.get_text()

            post.color = POST_COLORS[color_count % len(POST_COLORS)]
            color_count += 1

        self.render('../template/main.html')
Example #25
0
File: main.py Project: kenans/front
 def get(self):
     collection_id = self.get_argument("id")
     comments = conn.query("SELECT * FROM comments WHERE collection_id = %s", collection_id)
     self.finish({"comments":comments, "collection_id":collection_id, "error":None})