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
= '/usr/share/GeoIP/GeoIPCity.dat'
41 ORG_DB_PATH
= '/usr/share/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>')
74 result
[ip
] = gi
.record_by_addr(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
):
92 result
[ip
] = go
.org_by_addr(ip
)
94 return json_response(result
)
97 if __name__
== "__main__":