diff --git a/uploads_by_user_and_duration.py b/uploads_by_user_and_duration.py index f5c1166..e9b34f5 100644 --- a/uploads_by_user_and_duration.py +++ b/uploads_by_user_and_duration.py @@ -1,118 +1,123 @@ #!/usr/bin/env python3 import os import cgi import sys from wmflabs import db import json import yaml from datetime import datetime, timedelta import pymysql # Print header print('Content-type: application/json\n') def jsonify(response): return json.dumps(response) def get_data_object(data_all_time, data_weekly, data_yearly): return {"all_time": data_all_time, "weekly": data_weekly, "yearly": data_yearly} def get_res(status, user, data): response = {'status': status, 'user': user, 'data': data} return jsonify(response) +def get_res_error(status, user, message): + response = {'status': status, 'user': user, 'message': message} + return jsonify(response) + + # Fetch params labs = False if 'QUERY_STRING' in os.environ: QS = os.environ['QUERY_STRING'] qs = cgi.parse_qs(QS) try: username = qs['user'][0].replace('_', ' ') except: - print(get_res('400', username, 'Bad Parameters')) + print(get_res_error('400', username, 'Invalid Parameters')) sys.exit(0) if 'labs' in qs: labs = True # Load config __dir__ = os.path.dirname(__file__) config = yaml.safe_load(open(os.path.join(__dir__, 'config.yaml'))) conn = pymysql.connect(db=qs['labs'][0], host=config['DB_HOST'], user=config['DB_USER'], password=config['DB_PASS'], charset="utf8", ) else: try: conn = db.connect(qs['db'][0]) except: conn = db.connect('commonswiki') else: - print(get_res('400', username, 'Bad Parameters')) + print(get_res_error('400', username, 'Invalid Parameters')) sys.exit(0) ##### PROGRAM #### def get_sql(duration, username): if duration == 'all_time': return """select count(*) from logging_userindex where log_type="upload" and log_actor=(select actor_id from actor where actor_name="{username}");""".format(username=username) elif duration == 'yearly': start_time = str(datetime.today().replace( month=1, day=1).strftime("%Y%m%d"))+"000000" end_time = str(datetime.today().strftime("%Y%m%d%H%M%S")) return """select count(*) from logging_userindex where log_type="upload" and log_actor=(select actor_id from actor where actor_name="{username}") and log_timestamp > "{start_time}" and log_timestamp < "{end_time}";""".format(username=username, start_time=start_time, end_time=end_time) elif duration == 'weekly': today = datetime.now().date() start_time = str( (today - timedelta(days=today.weekday())).strftime("%Y%m%d%H%M%S")) end_time = str(datetime.today().strftime("%Y%m%d%H%M%S")) return """select count(*) from logging_userindex where log_type="upload" and log_actor=(select actor_id from actor where actor_name="{username}") and log_timestamp > "{start_time}" and log_timestamp < "{end_time}";""".format(username=username, start_time=start_time, end_time=end_time) else: raise ValueError def get_count(duration, username): cur = conn.cursor() with cur: sql = get_sql(duration, username) if labs: sql = sql.replace('_userindex', '') cur.execute(sql) data = cur.fetchall() return data[0][0] try: data_all_time = get_count('all_time', username) data_weekly = get_count('weekly', username) data_yearly = get_count('yearly', username) result = get_data_object(data_all_time, data_weekly, data_yearly) print(get_res('200', username, result)) except: - print(get_res('500', username, 'Internal Server Error')) + print(get_res_error('500', username, 'Internal Server Error')) sys.exit(0)