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
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 ###############################################################################
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.
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'
45 gc
= GeoIP
.open(COUNTRY_DB_PATH
, GeoIP
.GEOIP_MEMORY_CACHE
)
50 gi
= GeoIP
.open(CITY_DB_PATH
, GeoIP
.GEOIP_MEMORY_CACHE
)
55 go
= GeoIP
.open(ORG_DB_PATH
, GeoIP
.GEOIP_MEMORY_CACHE
)
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'
67 @application.route('/geoip/<ips>')
70 result
= {ip
: gi
.record_by_addr(ip
) for ip
in ips
.split('+')}
74 'country_code': gc
.country_code_by_addr(ip
),
75 'country_name': gc
.country_name_by_addr(ip
),
76 } for ip
in ips
.split('+')
81 return json_response(result
)
84 @application.route('/org/<ips>')
85 def get_organizations(ips
):
87 return json_response({ip
: go
.org_by_addr(ip
) for ip
in ips
.split('+')})
89 return json_response({})
92 if __name__
== "__main__":