예제 #1
0
    def user(self, username):
        """
        Retrieve user information and latest posts from the reddit API.

        Args:
            username: reddit username, expected to be valid but not necessarily existent
        Returns:
            dictionary containing username, some basic user information, time or retrieval
            and latest posts.
            If an exception is countered, returns a dictionary with key "error"
        """

        url = self.api_url + username
        posts_per_request = 100
        p = {"limit": posts_per_request}
        posts = []
        posts_received = 0

        try:
            response = self._send_request(url + "/about", p)
            if "error" in response:
                return response

            user_info = response["data"]

            while posts_received < post_limit:
                post_response = self._send_request(url + "/overview", p)
                if "error" in post_response:
                    return post_response

                post_batch = post_response["data"]["children"]
                posts.extend(post_batch)

                # Add name of last post to params to get next set of posts
                p["after"] = post_batch[-1]["data"]["name"]

                l = len(post_batch)
                posts_received += l

                if l < posts_per_request:
                    break

            data = {"info": user_info,
                    "username": username,
                    "refreshed": parse_date(int(time.time()))}
            if posts:
                data["posts"] = posts

            return data

        except Exception as e:
            app.logger.error("Some data could not be retrieved: %s", str(e))
            return {"error": str(e)}
예제 #2
0
파일: app.py 프로젝트: rkheikkila/u-stats
def stats(name):
    if not valid(name):
        return jsonify(error="Invalid name")

    refresh = request.args.get("refresh") == "true"

    if refresh:
        user_data = retrieve_data(name)
    else:
        user_data = users.find_one({"username": name})
        if not user_data:
            user_data = retrieve_data(name)

    if "error" in user_data:
        return jsonify(**user_data)

    if not (user_data.get("posts") or user_data.get("analytics")):
        return jsonify(error="No posts were found!")

    statistics = user_data["analytics"]

    payload = {
        "postcount": len(user_data["posts"]),
        "refreshed": user_data["refreshed"],
        "account_created": parse_date(int(user_data["info"]["created_utc"])),
        "oldest_post_date": user_data["posts"][-1]["data"]["created_utc"],
        "total_karma": statistics["total_score"],
        "words_per_post": "{:.1f}".format(statistics["avg_words"]),
        "karma_per_word": "{:.2f}".format(statistics["karma_per_word"]),
        "avgscore": "{:.1f}".format(statistics["avg_score"]),
        "posts": user_data["posts"],
        "subreddits": statistics["subreddits"],
        "daydata": statistics["by_day"],
        "hourdata": statistics["by_hour"],
        "wordcount": statistics["top_phrases"],
        "recommendations": statistics["recommendations"]
    }
    return jsonify(**payload)