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: Removed db.testing flag, instead overwrite config during testing. Created March 30, 2015, 12:58 p.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
(Empty)
1 # coding: utf-8
2
3 # This file is part of the Adblock Plus web scripts,
4 # Copyright (C) 2006-2015 Eyeo GmbH
5 #
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
8 # published by the Free Software Foundation.
9 #
10 # Adblock Plus is distributed in the hope that it will be useful,
11 # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 # GNU General Public License for more details.
14 #
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/>.
17
18 import os
19 import MySQLdb
20 import json
21 import traceback
22 from urlparse import parse_qsl
23
24 from sitescripts.web import url_handler
25 from sitescripts.utils import cached, setupStderr
26 from sitescripts.filterhits import db
27 from sitescripts.filterhits.web import common
28
29 def query(domain=None, filter=None, skip=0, take=20, order="DESC", order_by="fre quency", **_):
30 """
31 Returns the SQL and parameters needed to perform a query of the filterhits dat a.
32 """
33 sql = """SELECT SQL_CALC_FOUND_ROWS domain, filter, frequency
34 FROM frequencies as freq
35 LEFT JOIN filters as f ON f.sha1=freq.filter_sha1
36 %s
37 ORDER BY %s
38 LIMIT %%s, %%s"""
39
40 where = zip(*[("%s LIKE %%s" % s, "%%%s%%" % p) for s, p in (("domain", domain ),
41 ("filter", filter )) if p])
42 if where:
43 where_fields, params = where
44 where_sql = "WHERE " + " AND ".join(where_fields)
45 else:
46 where_sql = ""
47 params = []
48
49 order = order.upper() if order.upper() in ("ASC", "DESC") else "ASC"
50 if order_by not in ["filter", "domain", "frequency"]:
51 order_by = "frequency"
52 order_by_sql = "`%s` %s" % (order_by, order)
53
54 params = list(params) + [int(skip), int(take)]
55 return [sql % (where_sql, order_by_sql)] + params
56
57 @url_handler("/query")
58 def query_handler(environ, start_response):
59 setupStderr(environ["wsgi.errors"])
60 params = dict(parse_qsl(environ.get('QUERY_STRING', '')))
61
62 try:
63 db_connection = db.connect()
64 try:
65 results = db.query(db_connection, *query(**params), dict_result=True)
66 total = db.query(db_connection, "SELECT FOUND_ROWS()")[0][0]
67 finally:
68 db_connection.close()
69 except MySQLdb.Error:
70 traceback.print_exc()
71 return common.show_error("Failed to query database!", start_response,
72 "500 Database error")
73
74 try:
75 echo = int(params["echo"])
76 except (ValueError, KeyError):
77 echo = 0
78
79 response_headers = [("Content-type", "application/json; charset=utf-8")]
80 start_response("200 OK", response_headers)
81 return [json.dumps({"results": results, "echo": echo,
82 "total": total, "count": len(results)},
83 ensure_ascii=False).encode("utf-8")]
OLDNEW

Powered by Google App Engine
This is Rietveld