Accept '/r/foo' everywhere: part 2
[reddit.git] / scripts / geoip_service.py
blob473257126d212e8b5c123d0b49297800eabebf6f
1 #!/usr/bin/python
2 # The contents of this file are subject to the Common Public Attribution
3 # License Version 1.0. (the "License"); you may not use this file except in
4 # compliance with the License. You may obtain a copy of the License at
5 # http://code.reddit.com/LICENSE. The License is based on the Mozilla Public
6 # License Version 1.1, but Sections 14 and 15 have been added to cover use of
7 # software over a computer network and provide for limited attribution for the
8 # Original Developer. In addition, Exhibit A has been modified to be consistent
9 # with Exhibit B.
11 # Software distributed under the License is distributed on an "AS IS" basis,
12 # WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for
13 # the specific language governing rights and limitations under the License.
15 # The Original Code is reddit.
17 # The Original Developer is the Initial Developer. The Initial Developer of
18 # the Original Code is reddit Inc.
20 # All portions of the code written by reddit are Copyright (c) 2006-2015 reddit
21 # Inc. All Rights Reserved.
22 ###############################################################################
23 """
24 This is a tiny Flask app used for geoip lookups against a maxmind database.
26 If you are using this service be sure to set `geoip_location` in your ini file.
28 """
30 import json
32 import GeoIP
33 from flask import Flask, make_response
35 application = Flask(__name__)
37 # SET THESE PATHS TO YOUR MAXMIND GEOIP LEGACY DATABASES
38 # http://dev.maxmind.com/geoip/legacy/geolite/
39 COUNTRY_DB_PATH = '/usr/share/GeoIP/GeoIP.dat'
40 CITY_DB_PATH = '/usr/share/GeoIP/GeoIPCity.dat'
41 ORG_DB_PATH = '/usr/share/GeoIP/GeoIPOrg.dat'
44 try:
45 gc = GeoIP.open(COUNTRY_DB_PATH, GeoIP.GEOIP_MEMORY_CACHE)
46 except:
47 gc = None
49 try:
50 gi = GeoIP.open(CITY_DB_PATH, GeoIP.GEOIP_MEMORY_CACHE)
51 except:
52 gi = None
54 try:
55 go = GeoIP.open(ORG_DB_PATH, GeoIP.GEOIP_MEMORY_CACHE)
56 except:
57 go = None
60 def json_response(result):
61 json_output = json.dumps(result, ensure_ascii=False, encoding='iso-8859-1')
62 response = make_response(json_output.encode('utf-8'), 200)
63 response.headers['Content-Type'] = 'application/json; charset=utf-8'
64 return response
67 @application.route('/geoip/<ips>')
68 def get_record(ips):
69 result = {}
70 ips = ips.split('+')
72 if gi:
73 for ip in ips:
74 result[ip] = gi.record_by_addr(ip)
75 elif gc:
76 for ip in ips:
77 result[ip] = {
78 'country_code': gc.country_code_by_addr(ip),
79 'country_name': gc.country_name_by_addr(ip),
82 return json_response(result)
85 @application.route('/org/<ips>')
86 def get_organizations(ips):
87 result = {}
88 ips = ips.split('+')
90 if go:
91 for ip in ips:
92 result[ip] = go.org_by_addr(ip)
94 return json_response(result)
97 if __name__ == "__main__":
98 application.run()