Advertisement
Guest User

getFacebookPostStats

a guest
May 22nd, 2015
478
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.85 KB | None | 0 0
  1. #-*- coding: utf-8 -*-
  2.  
  3. import logging
  4. import datetime
  5. from urllib.parse import urlparse
  6.  
  7. from facepy import GraphAPI
  8.  
  9. # 로깅 모듈 설정
  10. logging.basicConfig(
  11.     filename = ("%s.log" % (datetime.datetime.now().strftime("%Y%m%d%H%M%S%f"))),
  12.     filemode = "a",
  13.     format = "%(levelname)-10s %(asctime)s %(message)s",
  14.     level = logging.DEBUG
  15. )
  16.  
  17. """
  18. function name:
  19.     getFbStat
  20.  
  21. arguments:
  22.     oAuth_Access_Token
  23.         String
  24.         require
  25.     Stat_filename
  26.         String
  27.         option (default: "stat.csv")
  28.  
  29. return value:
  30.     없음
  31.  
  32. description:
  33.     페이스북의 액세스 토큰 oAuth_Access_Token을 받아, 해당 사용자의 월별 포스팅 수를 Stat_filename 파일로 출력한다.
  34.     만약 Stat_filename이 입력되지 않으면 파일명은 "stat.csv"로 기본 지정된다.
  35.     출력형식은 작성년월\t작성개수 이며, 각 년월은 줄바꿈 문자로 구분된다.
  36. """
  37. def getFbStats(oAuth_Access_Token, Stat_filename = "stat.csv"):
  38.     # 로깅 객체 생성
  39.     log = logging.getLogger("getFaceStats")
  40.  
  41.     log.debug("Facebook API Initialing... : Access token is %s", oAuth_Access_Token)
  42.     # GraphAPI 객체 초기화
  43.     graph = GraphAPI(oAuth_Access_Token)
  44.     log.debug("Facebook API Initailize")
  45.  
  46.     # Facebook Graph API URL의 형태
  47.     api_url_pattern = "/me/posts?fields=created_time,message&limit=%s&until=%s"
  48.  
  49.     # 초기 변수 설정
  50.     post_size = 0       # 읽어들인 포스팅의 개수. 초기값은 0
  51.     limit = "20"
  52.     until = ""
  53.     loops = 0           # 반복 횟수
  54.  
  55.     # 글 작성 현황
  56.     stats = {}
  57.  
  58.     while 1:
  59.         loops += 1
  60.  
  61.         # Graph API URL 작성
  62.         api_url = (api_url_pattern % (limit, until))
  63.  
  64.         # 포스팅 읽어들이기
  65.         posts = graph.get(api_url)
  66.  
  67.         # 포스팅 갯수 가져오기
  68.         post_size = len(posts["data"])
  69.  
  70.         # 조건 판단을 위해서 until값 저장
  71.         before_until = until
  72.  
  73.         log_message = ("{%d} Loop; until {%s}; post_size {%d}; API URL {%s}" % (loops, until, post_size, api_url))
  74.  
  75.         log.debug(log_message)
  76.         print(log_message)
  77.  
  78.         for post in posts["data"]:
  79.             create_date = post["created_time"]
  80.             create_YYYYMM = create_date[0:4] + create_date[5:7]
  81.             if (create_YYYYMM in stats):
  82.                 stats[create_YYYYMM] += 1
  83.             else:
  84.                 stats[create_YYYYMM] = 0
  85.        
  86.         # 다음 페이지 URL에서 until 값과 limit 값 추출하기
  87.         next_url = urlparse( posts["paging"]["next"] )
  88.         querys = next_url.query.split("&")
  89.  
  90.         for query in querys:
  91.             (query_key, query_value) = query.split("=")
  92.             query_key = query_key.lower()
  93.  
  94.             if (query_key == "until"):
  95.                 until = query_value
  96.             elif (query_key == "limit"):
  97.                 limit = query_value
  98.        
  99.         # 이번에 전달한 until 값과 다음에 전달할 until 값이 같다면 반복 종료
  100.         if (until == before_until):
  101.             break
  102.    
  103.     # 결과 출력
  104.     Stat_file = open(Stat_filename, "w")
  105.  
  106.     for key in stats.keys():
  107.         Stat_file.write( "%s\t%s\n" % (key, stats[key]) )
  108.    
  109.     Stat_file.close()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement