Inbox.set_unread: "to" argument is not optional
[reddit.git] / scripts / geoip_service.py
blob86aac8e720e3627e8681e55b116e20c96bd07c0c
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 = '/var/lib/GeoIP/GeoIPCity.dat'
41 ORG_DB_PATH = '/var/lib/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 if gi:
70 result = {ip: gi.record_by_addr(ip) for ip in ips.split('+')}
71 elif gc:
72 result = {
73 ip : {
74 'country_code': gc.country_code_by_addr(ip),
75 'country_name': gc.country_name_by_addr(ip),
76 } for ip in ips.split('+')
78 else:
79 result = {}
81 return json_response(result)
84 @application.route('/org/<ips>')
85 def get_organizations(ips):
86 if go:
87 return json_response({ip: go.org_by_addr(ip) for ip in ips.split('+')})
88 else:
89 return json_response({})
92 if __name__ == "__main__":
93 application.run()