Rietveld Code Review Tool
Help | Bug tracker | Discussion group | Source code

Side by Side Diff: sitescripts/filterhits/web/query.py

Issue 4615801646612480: Issue 395 - Filter hits statistics backend (Closed)
Patch Set: Improvements regarding comments Created Feb. 17, 2015, 10:50 a.m.
Left:
Right:
Use n/p to move between diff chunks; N/P to move between comments.
Jump to:
View unified diff | Download patch
OLDNEW
1 # coding: utf-8 1 # coding: utf-8
2 2
3 # This file is part of the Adblock Plus web scripts, 3 # This file is part of the Adblock Plus web scripts,
4 # Copyright (C) 2006-2014 Eyeo GmbH 4 # Copyright (C) 2006-2015 Eyeo GmbH
5 # 5 #
6 # Adblock Plus is free software: you can redistribute it and/or modify 6 # Adblock Plus is free software: you can redistribute it and/or modify
7 # it under the terms of the GNU General Public License version 3 as 7 # it under the terms of the GNU General Public License version 3 as
8 # published by the Free Software Foundation. 8 # published by the Free Software Foundation.
9 # 9 #
10 # Adblock Plus is distributed in the hope that it will be useful, 10 # Adblock Plus is distributed in the hope that it will be useful,
11 # but WITHOUT ANY WARRANTY; without even the implied warranty of 11 # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 # GNU General Public License for more details. 13 # GNU General Public License for more details.
14 # 14 #
15 # You should have received a copy of the GNU General Public License 15 # You should have received a copy of the GNU General Public License
16 # along with Adblock Plus. If not, see <http://www.gnu.org/licenses/>. 16 # along with Adblock Plus. If not, see <http://www.gnu.org/licenses/>.
17 17
18 import os, MySQLdb, json 18 import os, MySQLdb, json
19 from urlparse import parse_qsl 19 from urlparse import parse_qsl
20
20 from sitescripts.web import url_handler 21 from sitescripts.web import url_handler
21 from sitescripts.utils import cached, get_config, setupStderr 22 from sitescripts.utils import cached, get_config, setupStderr
23 from sitescripts.filterhits import common
24 from sitescripts.filterhits import db
22 25
23 import sitescripts.filterhits.common as common 26 def query(domain=None, filter=None, skip=0, take=20, order_by="hits DESC", **_):
Sebastian Noack 2015/02/17 14:59:17 Any reason why you silently ignore additional keyw
kzar 2015/02/24 18:05:11 I do that because we're taking the parameters stra
Sebastian Noack 2015/02/26 16:39:25 I see.
24 import sitescripts.filterhits.db as db 27 """
25 28 Returns the SQL and parameters needed to perform a query of the filterhits dat a.
26 def query_sql(domain=None, filter=None, skip=0, take=20, order_by="hits DESC", * *_): 29 """
27 sql = """SELECT SQL_CALC_FOUND_ROWS domain, filter, hits 30 sql = """SELECT SQL_CALC_FOUND_ROWS domain, filter, hits
28 FROM geometrical_mean as g 31 FROM geometrical_mean as g
29 LEFT JOIN filters as f ON f.md5=g.filter_md5 32 LEFT JOIN filters as f ON f.sha1=g.filter_sha1
30 %s 33 %s
31 ORDER BY %s 34 ORDER BY %s
32 LIMIT %d, %d;""" 35 LIMIT %%s, %%s"""
33 where = ["domain LIKE '%%%s%%'" % db.escape(domain) if domain else None, 36
34 "filter LIKE '%%%s%%'" % db.escape(filter) if filter else None] 37 where_fields = [(s, "%" + p + "%") for s, p in (("domain", domain),
Sebastian Noack 2015/02/17 14:59:17 It's best practice to use format string when conca
kzar 2015/02/24 18:05:11 I disagree that `"%%%s%%" % p` is easier to read t
Sebastian Noack 2015/02/26 16:39:25 Fair enough.
35 where = " AND ".join([f for f in where if f]) 38 ("filter", filter)) if p]
Sebastian Noack 2015/02/17 14:59:17 Nit: Seems that the indentation is a little off he
kzar 2015/02/24 18:05:11 Done.
36 where = "WHERE " + where if where else "" 39 where = " AND ".join([f[0] + " LIKE %s" for f in where_fields])
37 return sql % (where, db.escape(order_by), int(skip), int(take)) 40 where_sql = "WHERE " + where if where else ""
41
42 order_by, order = order_by.split()
Sebastian Noack 2015/02/17 14:59:17 Strings aren't proper data structures. So how abou
kzar 2015/02/24 18:05:11 Done.
43 order = order.upper() if order.upper() in ["ASC", "DESC"] else "ASC"
Sebastian Noack 2015/02/17 14:59:17 Nit: When a sequence doesn't need to be modified u
kzar 2015/02/24 18:05:11 Done.
44 order_by_sql = "`%s` %s" % (MySQLdb.escape_string(order_by), order)
45
46 params = [f[1] for f in where_fields] + [int(skip), int(take)]
47 return [sql % (where_sql, order_by_sql)] + params
38 48
39 @url_handler("/query") 49 @url_handler("/query")
40 def query(environ, start_response): 50 def query_handler(environ, start_response):
41 setupStderr(environ["wsgi.errors"]) 51 setupStderr(environ["wsgi.errors"])
42 config = get_config() 52 config = get_config()
43 params = dict(parse_qsl(environ.get('QUERY_STRING', ''))) 53 params = dict(parse_qsl(environ.get('QUERY_STRING', '')))
44 54
45 try: 55 try:
46 db.connect(config.get("filterhitstats", "dbuser"), 56 db_connection = db.connect(config.get("filterhitstats", "dbuser"),
47 config.get("filterhitstats", "dbpassword"), 57 config.get("filterhitstats", "dbpassword"),
48 config.get("filterhitstats", "database")) 58 config.get("filterhitstats", "database"))
49 results = db.query(query_sql(**params), dict_result=True) 59 results = db.query(db_connection, *query(**params), dict_result=True)
50 total = db.query("SELECT FOUND_ROWS();")[0][0] 60 total = db.query(db_connection, "SELECT FOUND_ROWS()")[0][0]
51 except MySQLdb.Error: 61 except MySQLdb.Error:
52 return common.showError("Failed to query database!", start_response, 62 return common.showError("Failed to query database!", start_response,
53 "500 Database error") 63 "500 Database error")
54 finally: 64 finally:
55 db.disconnect() 65 if db_connection:
Sebastian Noack 2015/02/17 14:59:17 This will result in a NameError, in case db_connec
kzar 2015/02/24 18:05:11 Done.
66 db_connection.close()
56 67
57 try: 68 try:
58 echo = int(params["echo"]) 69 echo = int(params["echo"])
59 except (ValueError, KeyError): 70 except (ValueError, KeyError):
60 echo = 0 71 echo = 0
61 72
62 response_headers = [("Content-type", "application/json")] 73 response_headers = [("Content-type", "application/json")]
63 start_response("200 OK", response_headers) 74 start_response("200 OK", response_headers)
64 return [json.dumps({"results": results, "echo": echo, 75 return [json.dumps({"results": results, "echo": echo,
65 "total": total, "count": len(results)})] 76 "total": total, "count": len(results)})]
OLDNEW

Powered by Google App Engine
This is Rietveld