3 ###############################################################################
5 # This script assumes the presence of the COVID-19 repo.
7 # It (1) reads in the article list and then (2) calls the Wikimedia API to
8 # fetch view information for each article. Output is to (3) JSON and TSV.
10 ###############################################################################
25 parser = argparse.ArgumentParser(description='Call the views API repeatedly.')
26 parser.add_argument('-o', '--output_folder', help='Where to save output', default="../data/", type=str)
27 parser.add_argument('-i', '--article_file', help='File listing article names', default="../resources/articles.txt", type=str)
28 parser.add_argument('-d', '--query_date', help='Date if not yesterday, in YYYYMMDD format please.', type=str)
29 args = parser.parse_args()
38 outputPath = args.output_folder
39 articleFile = args.article_file
42 queryDate = args.query_date
44 yesterday = datetime.datetime.today() - datetime.timedelta(days=1)
45 queryDate = yesterday.strftime("%Y%m%d")
47 queryDate = queryDate + "00" #requires specifying hours
51 #1 Load up the list of article names
53 j_Out = f"{outputPath}dailyviews{queryDate}.json"
54 t_Out = f"{outputPath}dailyviews{queryDate}.tsv"
56 with open(articleFile, 'r') as infile:
57 next(infile) #skip header
58 articleList = list(infile)
62 #2 Repeatedly call the API with that list of names
65 a = a.strip("\"\n") #destringify
66 url= f"https://wikimedia.org/api/rest_v1/metrics/pageviews/per-article/en.wikipedia/all-access/all-agents/{a}/daily/{queryDate}/{queryDate}"
68 response = requests.get(url)
70 jd = json.loads(response.content)
71 j.append(jd["items"][0])
74 print(f"Not ok response: {response.status_code} from {url}")
76 #3 Save results as a JSON and TSV
78 #all data in j now, make json file
79 with open(j_Out, 'w') as j_outfile:
80 json.dump(j, j_outfile, indent=2)
82 with open(t_Out, 'w') as t_outfile:
83 dw = csv.DictWriter(t_outfile, sorted(j[0].keys()), delimiter='\t')
88 # f_Out = outputPath + "dailyviews" + queryDate + ".feather"
89 # read the json back in and make a feather file?
92 if __name__ == "__main__":