-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdbmanager.py
72 lines (59 loc) · 1.87 KB
/
dbmanager.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
#!/usr/bin/env python2.7
import psycopg2
DATABASE_NAME = "news"
MOST_POPULAR_ARTICLES_QUERY = """
select
articles.title,
count(log.id) as total
from
articles
left join log on log.path = ('/article/' || articles.slug)
group by
articles.title
order by
total desc
limit
3
"""
MOST_POPULAR_AUTHORS_QUERY = """
select
authors.name,
count(log.id)
from
authors
left join articles on articles.author = authors.id
left join log on log.path = ('/article/' || articles.slug)
group by
authors.name
order by
count desc
"""
DAYS_WITH_MORE_ERRORS_QUERY = """
select
to_char(errors_by_day.date,'Month DD, YYYY') as date,
to_char(((errors_by_day.count::decimal
/requests_by_day.count::decimal)*100)
,'9.99')
|| '%' as percentage
from
(select date(time),count(*) from log
group by date(time)) as requests_by_day,
(select date(time),count(*) from log where status != '200 OK'
group by date(time)) as errors_by_day
where
requests_by_day.date = errors_by_day.date
and ((errors_by_day.count::decimal
/requests_by_day.count::decimal)*100) > 1;
"""
def get(query):
db = psycopg2.connect(database=DATABASE_NAME)
cursor = db.cursor()
cursor.execute(query)
return cursor.fetchall()
db.close()
def get_most_popular_articles():
return get(MOST_POPULAR_ARTICLES_QUERY)
def get_most_popular_authors():
return get(MOST_POPULAR_AUTHORS_QUERY)
def get_days_with_more_errors():
return get(DAYS_WITH_MORE_ERRORS_QUERY)