├── .github
└── workflows
│ └── test.yml
├── .gitignore
├── LICENSE
├── README.md
├── ipinfo_django
├── __init__.py
├── helpers.py
├── ip_selector
│ ├── __init__.py
│ ├── default.py
│ ├── interface.py
│ └── remote_client.py
└── middleware.py
├── pyproject.toml
├── requirements
├── compile.py
├── py310-django32.txt
├── py310-django40.txt
└── requirements.in
├── scripts
├── ctags.sh
├── fmt.sh
├── publish.sh
└── test.sh
├── setup.py
├── tests
├── __init__.py
├── settings.py
├── test_async_middleware.py
└── urls.py
└── tox.ini
/.github/workflows/test.yml:
--------------------------------------------------------------------------------
1 | ---
2 | name: Unit tests
3 |
4 | on: [push, pull_request]
5 |
6 | jobs:
7 | tests:
8 | runs-on: ubuntu-latest
9 |
10 | strategy:
11 | matrix:
12 | python-version: ['3.10']
13 | django: [32, 40]
14 |
15 | steps:
16 | - uses: actions/checkout@v2
17 | - uses: actions/setup-python@v2
18 | with:
19 | python-version: ${{ matrix.python-version }}
20 |
21 | - name: Install dependencies
22 | run: python -m pip install --upgrade tox
23 |
24 | - name: Test with tox
25 | env:
26 | TOX_ENV: ${{ format('py{0}-django{1}', matrix.python-version, matrix.django) }}
27 | DATABASE_URL: postgres://postgres:postgres@localhost/postgres
28 | run: PYTHONPATH=. tox -e $TOX_ENV
29 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | .vscode/
2 | .vim/
3 | .idea/
4 |
5 | # Byte-compiled / optimized / DLL files
6 | __pycache__/
7 | *.py[cod]
8 | *$py.class
9 |
10 | # C extensions
11 | *.so
12 |
13 | # Distribution / packaging
14 | .Python
15 | build/
16 | develop-eggs/
17 | dist/
18 | downloads/
19 | eggs/
20 | .eggs/
21 | lib/
22 | lib64/
23 | parts/
24 | sdist/
25 | var/
26 | wheels/
27 | *.egg-info/
28 | .installed.cfg
29 | *.egg
30 | MANIFEST
31 |
32 | # PyInstaller
33 | # Usually these files are written by a python script from a template
34 | # before PyInstaller builds the exe, so as to inject date/other infos into it.
35 | *.manifest
36 | *.spec
37 |
38 | # Installer logs
39 | pip-log.txt
40 | pip-delete-this-directory.txt
41 |
42 | # Unit test / coverage reports
43 | htmlcov/
44 | .tox/
45 | .coverage
46 | .coverage.*
47 | .cache
48 | nosetests.xml
49 | coverage.xml
50 | *.cover
51 | .hypothesis/
52 | .pytest_cache/
53 |
54 | # Translations
55 | *.mo
56 | *.pot
57 |
58 | # Django stuff:
59 | *.log
60 | local_settings.py
61 | db.sqlite3
62 |
63 | # Flask stuff:
64 | instance/
65 | .webassets-cache
66 |
67 | # Scrapy stuff:
68 | .scrapy
69 |
70 | # Sphinx documentation
71 | docs/_build/
72 |
73 | # PyBuilder
74 | target/
75 |
76 | # Jupyter Notebook
77 | .ipynb_checkpoints
78 |
79 | # pyenv
80 | .python-version
81 |
82 | # celery beat schedule file
83 | celerybeat-schedule
84 |
85 | # SageMath parsed files
86 | *.sage.py
87 |
88 | # Environments
89 | .env
90 | .venv
91 | env/
92 | venv/
93 | ENV/
94 | env.bak/
95 | venv.bak/
96 |
97 | # Spyder project settings
98 | .spyderproject
99 | .spyproject
100 |
101 | # Rope project settings
102 | .ropeproject
103 |
104 | # mkdocs documentation
105 | /site
106 |
107 | # mypy
108 | .mypy_cache/
109 |
110 | # local test file
111 | test.py
112 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | Apache License
2 | Version 2.0, January 2004
3 | http://www.apache.org/licenses/
4 |
5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6 |
7 | 1. Definitions.
8 |
9 | "License" shall mean the terms and conditions for use, reproduction,
10 | and distribution as defined by Sections 1 through 9 of this document.
11 |
12 | "Licensor" shall mean the copyright owner or entity authorized by
13 | the copyright owner that is granting the License.
14 |
15 | "Legal Entity" shall mean the union of the acting entity and all
16 | other entities that control, are controlled by, or are under common
17 | control with that entity. For the purposes of this definition,
18 | "control" means (i) the power, direct or indirect, to cause the
19 | direction or management of such entity, whether by contract or
20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the
21 | outstanding shares, or (iii) beneficial ownership of such entity.
22 |
23 | "You" (or "Your") shall mean an individual or Legal Entity
24 | exercising permissions granted by this License.
25 |
26 | "Source" form shall mean the preferred form for making modifications,
27 | including but not limited to software source code, documentation
28 | source, and configuration files.
29 |
30 | "Object" form shall mean any form resulting from mechanical
31 | transformation or translation of a Source form, including but
32 | not limited to compiled object code, generated documentation,
33 | and conversions to other media types.
34 |
35 | "Work" shall mean the work of authorship, whether in Source or
36 | Object form, made available under the License, as indicated by a
37 | copyright notice that is included in or attached to the work
38 | (an example is provided in the Appendix below).
39 |
40 | "Derivative Works" shall mean any work, whether in Source or Object
41 | form, that is based on (or derived from) the Work and for which the
42 | editorial revisions, annotations, elaborations, or other modifications
43 | represent, as a whole, an original work of authorship. For the purposes
44 | of this License, Derivative Works shall not include works that remain
45 | separable from, or merely link (or bind by name) to the interfaces of,
46 | the Work and Derivative Works thereof.
47 |
48 | "Contribution" shall mean any work of authorship, including
49 | the original version of the Work and any modifications or additions
50 | to that Work or Derivative Works thereof, that is intentionally
51 | submitted to Licensor for inclusion in the Work by the copyright owner
52 | or by an individual or Legal Entity authorized to submit on behalf of
53 | the copyright owner. For the purposes of this definition, "submitted"
54 | means any form of electronic, verbal, or written communication sent
55 | to the Licensor or its representatives, including but not limited to
56 | communication on electronic mailing lists, source code control systems,
57 | and issue tracking systems that are managed by, or on behalf of, the
58 | Licensor for the purpose of discussing and improving the Work, but
59 | excluding communication that is conspicuously marked or otherwise
60 | designated in writing by the copyright owner as "Not a Contribution."
61 |
62 | "Contributor" shall mean Licensor and any individual or Legal Entity
63 | on behalf of whom a Contribution has been received by Licensor and
64 | subsequently incorporated within the Work.
65 |
66 | 2. Grant of Copyright License. Subject to the terms and conditions of
67 | this License, each Contributor hereby grants to You a perpetual,
68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69 | copyright license to reproduce, prepare Derivative Works of,
70 | publicly display, publicly perform, sublicense, and distribute the
71 | Work and such Derivative Works in Source or Object form.
72 |
73 | 3. Grant of Patent License. Subject to the terms and conditions of
74 | this License, each Contributor hereby grants to You a perpetual,
75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76 | (except as stated in this section) patent license to make, have made,
77 | use, offer to sell, sell, import, and otherwise transfer the Work,
78 | where such license applies only to those patent claims licensable
79 | by such Contributor that are necessarily infringed by their
80 | Contribution(s) alone or by combination of their Contribution(s)
81 | with the Work to which such Contribution(s) was submitted. If You
82 | institute patent litigation against any entity (including a
83 | cross-claim or counterclaim in a lawsuit) alleging that the Work
84 | or a Contribution incorporated within the Work constitutes direct
85 | or contributory patent infringement, then any patent licenses
86 | granted to You under this License for that Work shall terminate
87 | as of the date such litigation is filed.
88 |
89 | 4. Redistribution. You may reproduce and distribute copies of the
90 | Work or Derivative Works thereof in any medium, with or without
91 | modifications, and in Source or Object form, provided that You
92 | meet the following conditions:
93 |
94 | (a) You must give any other recipients of the Work or
95 | Derivative Works a copy of this License; and
96 |
97 | (b) You must cause any modified files to carry prominent notices
98 | stating that You changed the files; and
99 |
100 | (c) You must retain, in the Source form of any Derivative Works
101 | that You distribute, all copyright, patent, trademark, and
102 | attribution notices from the Source form of the Work,
103 | excluding those notices that do not pertain to any part of
104 | the Derivative Works; and
105 |
106 | (d) If the Work includes a "NOTICE" text file as part of its
107 | distribution, then any Derivative Works that You distribute must
108 | include a readable copy of the attribution notices contained
109 | within such NOTICE file, excluding those notices that do not
110 | pertain to any part of the Derivative Works, in at least one
111 | of the following places: within a NOTICE text file distributed
112 | as part of the Derivative Works; within the Source form or
113 | documentation, if provided along with the Derivative Works; or,
114 | within a display generated by the Derivative Works, if and
115 | wherever such third-party notices normally appear. The contents
116 | of the NOTICE file are for informational purposes only and
117 | do not modify the License. You may add Your own attribution
118 | notices within Derivative Works that You distribute, alongside
119 | or as an addendum to the NOTICE text from the Work, provided
120 | that such additional attribution notices cannot be construed
121 | as modifying the License.
122 |
123 | You may add Your own copyright statement to Your modifications and
124 | may provide additional or different license terms and conditions
125 | for use, reproduction, or distribution of Your modifications, or
126 | for any such Derivative Works as a whole, provided Your use,
127 | reproduction, and distribution of the Work otherwise complies with
128 | the conditions stated in this License.
129 |
130 | 5. Submission of Contributions. Unless You explicitly state otherwise,
131 | any Contribution intentionally submitted for inclusion in the Work
132 | by You to the Licensor shall be under the terms and conditions of
133 | this License, without any additional terms or conditions.
134 | Notwithstanding the above, nothing herein shall supersede or modify
135 | the terms of any separate license agreement you may have executed
136 | with Licensor regarding such Contributions.
137 |
138 | 6. Trademarks. This License does not grant permission to use the trade
139 | names, trademarks, service marks, or product names of the Licensor,
140 | except as required for reasonable and customary use in describing the
141 | origin of the Work and reproducing the content of the NOTICE file.
142 |
143 | 7. Disclaimer of Warranty. Unless required by applicable law or
144 | agreed to in writing, Licensor provides the Work (and each
145 | Contributor provides its Contributions) on an "AS IS" BASIS,
146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147 | implied, including, without limitation, any warranties or conditions
148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149 | PARTICULAR PURPOSE. You are solely responsible for determining the
150 | appropriateness of using or redistributing the Work and assume any
151 | risks associated with Your exercise of permissions under this License.
152 |
153 | 8. Limitation of Liability. In no event and under no legal theory,
154 | whether in tort (including negligence), contract, or otherwise,
155 | unless required by applicable law (such as deliberate and grossly
156 | negligent acts) or agreed to in writing, shall any Contributor be
157 | liable to You for damages, including any direct, indirect, special,
158 | incidental, or consequential damages of any character arising as a
159 | result of this License or out of the use or inability to use the
160 | Work (including but not limited to damages for loss of goodwill,
161 | work stoppage, computer failure or malfunction, or any and all
162 | other commercial damages or losses), even if such Contributor
163 | has been advised of the possibility of such damages.
164 |
165 | 9. Accepting Warranty or Additional Liability. While redistributing
166 | the Work or Derivative Works thereof, You may choose to offer,
167 | and charge a fee for, acceptance of support, warranty, indemnity,
168 | or other liability obligations and/or rights consistent with this
169 | License. However, in accepting such obligations, You may act only
170 | on Your own behalf and on Your sole responsibility, not on behalf
171 | of any other Contributor, and only if You agree to indemnify,
172 | defend, and hold each Contributor harmless for any liability
173 | incurred by, or claims asserted against, such Contributor by reason
174 | of your accepting any such warranty or additional liability.
175 |
176 | END OF TERMS AND CONDITIONS
177 |
178 | APPENDIX: How to apply the Apache License to your work.
179 |
180 | To apply the Apache License to your work, attach the following
181 | boilerplate notice, with the fields enclosed by brackets "[]"
182 | replaced with your own identifying information. (Don't include
183 | the brackets!) The text should be enclosed in the appropriate
184 | comment syntax for the file format. We also recommend that a
185 | file or class name and description of purpose be included on the
186 | same "printed page" as the copyright notice for easier
187 | identification within third-party archives.
188 |
189 | Copyright [yyyy] [name of copyright owner]
190 |
191 | Licensed under the Apache License, Version 2.0 (the "License");
192 | you may not use this file except in compliance with the License.
193 | You may obtain a copy of the License at
194 |
195 | http://www.apache.org/licenses/LICENSE-2.0
196 |
197 | Unless required by applicable law or agreed to in writing, software
198 | distributed under the License is distributed on an "AS IS" BASIS,
199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200 | See the License for the specific language governing permissions and
201 | limitations under the License.
202 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # [
](https://ipinfo.io/) IPinfo Django Client Library
2 |
3 | This is the official Django client library for the [IPinfo.io](https://ipinfo.io) IP address API, allowing you to look up your own IP address, or get any of the following details for an IP:
4 |
5 | - [IP to geolocation](https://ipinfo.io/ip-geolocation-api) (city, region, country, postal code, latitude, and longitude)
6 | - [IP to ASN](https://ipinfo.io/asn-api) (ISP or network operator, associated domain name, and type, such as business, hosting, or company)
7 | - [IP to Company](https://ipinfo.io/ip-company-api) (the name and domain of the business that uses the IP address)
8 | - [IP to Carrier](https://ipinfo.io/ip-carrier-api) (the name of the mobile carrier and MNC and MCC for that carrier if the IP is used exclusively for mobile traffic)
9 |
10 | Check all the data we have for your IP address [here](https://ipinfo.io/what-is-my-ip).
11 |
12 | ### Getting Started
13 |
14 | You'll need an IPinfo API access token, which you can get by signing up for a free account at [https://ipinfo.io/signup](https://ipinfo.io/signup).
15 |
16 | The free plan is limited to 50,000 requests per month, and doesn't include some of the data fields such as IP type and company data. To enable all the data fields and additional request volumes see [https://ipinfo.io/pricing](https://ipinfo.io/pricing)
17 |
18 | ⚠️ Note: This library does not currently support our newest free API https://ipinfo.io/lite. If you’d like to use IPinfo Lite, you can call the [endpoint directly](https://ipinfo.io/developers/lite-api) using your preferred HTTP client. Developers are also welcome to contribute support for Lite by submitting a pull request.
19 |
20 | #### Installation
21 |
22 | ```bash
23 | pip install ipinfo_django
24 | ```
25 |
26 | #### Quickstart
27 |
28 | Once configured, `ipinfo_django` will make IP address data accessible within Django's `HttpRequest` object. The following view from the `view.py` file:
29 |
30 | ```python
31 | from django.http import HttpResponse
32 |
33 |
34 | def location(request):
35 | response_string = 'The IP address {} is located at the coordinates {}, which is in the city {}.'.format(
36 | request.ipinfo.ip,
37 | request.ipinfo.loc,
38 | request.ipinfo.city
39 | )
40 |
41 | return HttpResponse(response_string)
42 | ```
43 |
44 | will return the following as an `HttpResponse` object:
45 |
46 | ```python
47 | 'The IP address 216.239.36.21 is located at the coordinates 37.8342,-122.2900, which is in the city Emeryville.'
48 | ```
49 |
50 | To get the details of a user-defined IP, we will import the ipinfo package directly to the `view.py` file:
51 | ```python
52 | from django.shortcuts import render
53 | from django.http import HttpResponse
54 | from django.conf import settings
55 | import ipinfo
56 |
57 |
58 | def get_ip_details(ip_address=None):
59 | ipinfo_token = getattr(settings, "IPINFO_TOKEN", None)
60 | ipinfo_settings = getattr(settings, "IPINFO_SETTINGS", {})
61 | ip_data = ipinfo.getHandler(ipinfo_token, **ipinfo_settings)
62 | ip_data = ip_data.getDetails(ip_address)
63 | return ip_data
64 |
65 | def location(request):
66 | ip_data = get_ip_details('168.156.54.5')
67 | response_string = 'The IP address {} is located at the coordinates {}, which is in the city {}.'.format(ip_data.ip,ip_data.loc,ip_data.city)
68 | return HttpResponse(response_string)
69 | ```
70 |
71 | The above code will print the IP details provided. We can use GET and POST methods to get the details of user-defined IP
72 |
73 | ```python
74 | 'The IP address 168.156.54.5 is located at the coordinates 47.6104,-122.2007, which is in the city Bellevue.'
75 | ```
76 |
77 | ### Setup
78 |
79 | Setup can be accomplished in three steps:
80 |
81 | 1. Install with `pip`
82 |
83 | ```bash
84 | pip install ipinfo_django
85 | ```
86 |
87 | 2. Add `'ipinfo_django.middleware.IPinfoMiddleware'` to `settings.MIDDLEWARE` in `settings.py`:
88 |
89 | ```python
90 | MIDDLEWARE = [
91 | 'django.middleware.security.SecurityMiddleware',
92 | 'django.contrib.sessions.middleware.SessionMiddleware',
93 | ...
94 | 'ipinfo_django.middleware.IPinfoMiddleware',
95 | ]
96 | ```
97 |
98 | 3. Optionally, configure with custom settings in `settings.py`:
99 |
100 | ```python
101 | IPINFO_TOKEN = '123456789abc'
102 | IPINFO_SETTINGS = {
103 | 'cache_options': {
104 | 'ttl':30,
105 | 'maxsize': 128
106 | },
107 | 'countries_file': 'custom_countries.json'
108 | }
109 | IPINFO_FILTER = lambda request: request.scheme == 'http'
110 | IPINFO_IP_SELECTOR = my_custom_ip_selector_implementation
111 | ```
112 |
113 | ### Async support
114 |
115 | `'ipinfo_django.middleware.IPinfoAsyncMiddleware'` can be used under ASGI. This is an async-only middleware that works only when placed in an async middleware chain, that is, a chain of Django middleware which are both async and async capable. For example:
116 |
117 | ```python
118 | MIDDLEWARE = [
119 | 'package_b.middleware.ExampleSyncAndAsyncMiddleware',
120 | 'ipinfo_django.middleware.IPinfoAsyncMiddleware',
121 | 'package_a.middleware.ExampleAsyncMiddleware',
122 | ]
123 | ```
124 |
125 | See [asynchronous-support](https://docs.djangoproject.com/en/4.0/topics/http/middleware/#asynchronous-support) for more.
126 |
127 | ### Details Data
128 |
129 | `HttpRequest.ipinfo` is a `Details` object that contains all fields listed [IPinfo developer docs](https://ipinfo.io/developers/responses#full-response) with a few minor additions. Properties can be accessed directly.
130 |
131 | ```python
132 | >>> request.ipinfo.hostname
133 | cpe-104-175-221-247.socal.res.rr.com
134 | ```
135 |
136 | #### Country Name
137 |
138 | `HttpRequest.ipinfo.country_name` will return the country name, as supplied by the `countries.json` file. See below for instructions on changing that file for use with non-English languages. `HttpRequest.ipinfo.country` will still return country code.
139 |
140 | ```python
141 | >>> request.ipinfo.country
142 | US
143 | >>> request.ipinfo.country_name
144 | United States
145 | ```
146 |
147 | #### IP Address
148 |
149 | `HttpRequest.ipinfo.ip` will return an IP string.
150 |
151 | ```python
152 | >>> request.ipinfo.ip
153 | 104.175.221.247
154 | >>> type(request.ipinfo.ip)
155 |
156 | ```
157 |
158 | #### Longitude and Latitude
159 |
160 | `HttpRequest.ipinfo.latitude` and `HttpRequest.ipinfo.longitude` will return latitude and longitude, respectively, as strings. `HttpRequest.ipinfo.loc` will still return a composite string of both values.
161 |
162 | ```python
163 | >>> request.ipinfo.loc
164 | 34.0293,-118.3570
165 | >>> request.ipinfo.latitude
166 | 34.0293
167 | >>> request.ipinfo.longitude
168 | -118.3570
169 | ```
170 |
171 | #### Accessing all properties
172 |
173 | `HttpRequest.ipinfo.all` will return all details data as a dictionary.
174 |
175 | ```python
176 | >>> request.ipinfo.all
177 | {
178 | 'asn': { 'asn': 'AS20001',
179 | 'domain': 'twcable.com',
180 | 'name': 'Time Warner Cable Internet LLC',
181 | 'route': '104.172.0.0/14',
182 | 'type': 'isp'},
183 | 'city': 'Los Angeles',
184 | 'company': { 'domain': 'twcable.com',
185 | 'name': 'Time Warner Cable Internet LLC',
186 | 'type': 'isp'},
187 | 'country': 'US',
188 | 'country_name': 'United States',
189 | 'hostname': 'cpe-104-175-221-247.socal.res.rr.com',
190 | 'ip': '104.175.221.247',
191 | 'loc': '34.0293,-118.3570',
192 | 'latitude': '34.0293',
193 | 'longitude': '-118.3570',
194 | 'phone': '323',
195 | 'postal': '90016',
196 | 'region': 'California'
197 | }
198 | ```
199 |
200 | ### Authentication
201 |
202 | The IPinfo library can be authenticated with your IPinfo API token, which is set in the `settings.py` file. It also works without an authentication token, but in a more limited capacity. From `settings.py`:
203 |
204 | ```python
205 | IPINFO_TOKEN = '123456789abc'
206 | ```
207 |
208 | ### Caching
209 |
210 | In-memory caching of `details` data is provided by default via the `cachetools `_ library. This uses an LRU (least recently used) cache with a TTL (time to live) by default. This means that values will be cached for the specified duration; if the cache's max size is reached, cache values will be invalidated as necessary, starting with the oldest cached value.
211 |
212 | #### Modifying cache options
213 |
214 | Cache behavior can be modified by setting the `cache_options` key in `settings.IPINFO_SETTINGS`. `cache_options` is a dictionary in which the keys are keyword arguments specified in the `cachetools` library. The nesting of keyword arguments is to prevent name collisions between this library and its dependencies.
215 |
216 | - Default maximum cache size: 4096 (multiples of 2 are recommended to increase efficiency)
217 | - Default TTL: 24 hours (in seconds)
218 |
219 | From `settings.py`:
220 |
221 | ```python
222 | IPINFO_SETTINGS = {
223 | 'cache_options': {
224 | 'ttl': 30,
225 | 'maxsize': 128
226 | }
227 | }
228 | ```
229 |
230 | #### Using a different cache
231 |
232 | It's possible to use a custom cache by creating a child class of the [CacheInterface](https://github.com/ipinfo/python/blob/master/ipinfo/cache/interface.py) class and setting the `cache` value in `settings.IPINFO_SETTINGS`. FYI this is known as [the Strategy Pattern](https://sourcemaking.com/design_patterns/strategy).
233 |
234 | From `settings.py`:
235 |
236 | ```python
237 | IPINFO_SETTINGS = {'cache': my_fancy_custom_cache_object}
238 | ```
239 |
240 | ### Internationalization
241 |
242 | When looking up an IP address, the response object includes a `details.country_name` attribute which includes the country name based on American English. It is possible to return the country name in other languages by setting the `countries_file` keyword argument in `settings.py`.
243 |
244 | The file must be a `.json` file with the following structure:
245 |
246 | ```js
247 | {
248 | "BD": "Bangladesh",
249 | "BE": "Belgium",
250 | "BF": "Burkina Faso",
251 | "BG": "Bulgaria"
252 | // …
253 | }
254 | ```
255 |
256 | From `settings.py`:
257 |
258 | ```python
259 | IPINFO_SETTINGS = {'countries_file': 'custom_countries.json'}
260 | ```
261 |
262 | ### Filtering
263 |
264 | By default, `ipinfo_django` filters out requests that have `bot` or `spider` in the user-agent. Instead of looking up IP address data for these requests, the `HttpRequest.ipinfo` attribute is set to `None`. This is to prevent you from unnecessarily using up requests on non-user traffic. This behavior can be switched off by modifying the `settings.IPINFO_FILTER` object in `settings.py`.
265 |
266 | To turn off filtering:
267 |
268 | ```python
269 | IPINFO_FILTER = None
270 | ```
271 |
272 | To set your own filtering rules, *thereby replacing the default filter*, you can set `settings.IPINFO_FILTER` to your own, custom callable function which satisfies the following rules:
273 |
274 | - Accepts one request.
275 | - Returns *True to filter out, False to allow lookup*
276 |
277 | To use your own filter rules:
278 |
279 | ```python
280 | IPINFO_FILTER = lambda request: request.scheme == 'http'
281 | ```
282 |
283 | ### IP Selection Mechanism
284 |
285 | By default, the IP is used by ignoring the reverse proxies depending on whether we are behind a reverse proxy or not.
286 |
287 | Since the desired IP by your system may be in other locations, the IP selection mechanism is configurable and some alternative built-in options are available.
288 |
289 | #### Using built-in IP selectors
290 |
291 | - Default IP Selector
292 | - Client IP Selector
293 |
294 | ##### Default IP selector
295 |
296 | A [DefaultIPSelector](https://github.com/ipinfo/django/blob/master/ipinfo_django/ip_selector/default.py) object is used by default if no IP selection mechanism is provided. It selects an IP address by trying to extract it from the `X-Forwarded-For` header. It will default to the source IP on the request if the header doesn't exist.
297 |
298 | This selector can be set explicitly by setting the `IPINFO_IP_SELECTOR` in `settings.py` file.
299 |
300 | ```python
301 | from ipinfo_django.ip_selector.default import DefaultIPSelector
302 |
303 | IPINFO_IP_SELECTOR = DefaultIPSelector()
304 | ```
305 |
306 | ##### Client IP selector
307 |
308 | A [ClientIPSelector](https://github.com/ipinfo/django/blob/master/ipinfo_django/ip_selector/remote_client.py) returns the client IP address from the incoming request.
309 |
310 | This selector can be set by setting the `IPINFO_IP_SELECTOR` in `settings.py`file.
311 |
312 | ```python
313 | from ipinfo_django.ip_selector.remote_client import ClientIPSelector
314 |
315 | IPINFO_IP_SELECTOR = ClientIPSelector()
316 | ```
317 |
318 | #### Using a custom IP selector
319 |
320 | In case a custom IP selector is required, you may implement the [IPSelectorInterface](https://github.com/ipinfo/django/blob/master/ipinfo_django/ip_selector/interface.py) and pass the instance to `IPINFO_IP_SELECTOR` in `settings.py` file.
321 |
322 | For example:
323 |
324 | ```python
325 | IPINFO_IP_SELECTOR = my_custom_ip_selector_implementation
326 | ```
327 |
328 | ### Errors
329 |
330 | If there's an error while making a request to IPinfo (e.g. your token was rate
331 | limited, there was a network issue, etc.), then the traceback will be logged
332 | using the built-in Python logger, and `HttpRequest.ipinfo` will be `None`.
333 |
334 | ### Local development and testing
335 |
336 | To test the project locally, install Tox in your Python virtual environment:
337 |
338 | ```bash
339 | pip install tox
340 | ```
341 |
342 | Then, run Tox:
343 |
344 | ```bash
345 | PYTHONPATH=. tox
346 | ```
347 |
348 | ### Other Libraries
349 |
350 | There are official IPinfo client libraries available for many languages including PHP, Go, Java, Ruby, and many popular frameworks such as Django, Rails, and Laravel. There are also many third-party libraries and integrations available for our API.
351 |
352 | ### About IPinfo
353 |
354 | Founded in 2013, IPinfo prides itself on being the most reliable, accurate, and in-depth source of IP address data available anywhere. We process terabytes of data to produce our custom IP geolocation, company, carrier, VPN detection, hosted domains, and IP type data sets. Our API handles over 40 billion requests a month for businesses and developers.
355 |
356 | [](https://ipinfo.io/)
357 |
--------------------------------------------------------------------------------
/ipinfo_django/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ipinfo/django/302ebf81ed446fb4f7ad602eecdf5711298f2389/ipinfo_django/__init__.py
--------------------------------------------------------------------------------
/ipinfo_django/helpers.py:
--------------------------------------------------------------------------------
1 | HTTP_X_FORWARDED_FOR = "HTTP_X_FORWARDED_FOR"
2 | REMOTE_ADDR = "REMOTE_ADDR"
3 |
4 |
5 | def is_bot(request):
6 | """Whether or not the request user-agent self-identifies as a bot"""
7 | lowercase_user_agent = request.META.get("HTTP_USER_AGENT", "").lower()
8 | return "bot" in lowercase_user_agent or "spider" in lowercase_user_agent
9 |
--------------------------------------------------------------------------------
/ipinfo_django/ip_selector/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ipinfo/django/302ebf81ed446fb4f7ad602eecdf5711298f2389/ipinfo_django/ip_selector/__init__.py
--------------------------------------------------------------------------------
/ipinfo_django/ip_selector/default.py:
--------------------------------------------------------------------------------
1 | """
2 | A default iphandler implementation that returns IP to query for depending on whether we are behind a reverse proxy or not.
3 | """
4 |
5 | from .interface import IPSelectorInterface
6 | from ipinfo_django.helpers import HTTP_X_FORWARDED_FOR, REMOTE_ADDR
7 |
8 |
9 | class DefaultIPSelector(IPSelectorInterface):
10 | """Default IP selector which uses IP depending on whether we are behind a reverse proxy or not."""
11 |
12 | def get_ip(self, request):
13 | """Determine what IP to query for depending on whether we are behind a reverse proxy or not."""
14 | x_forwarded_for = request.META.get(HTTP_X_FORWARDED_FOR)
15 | if x_forwarded_for:
16 | return x_forwarded_for.split(",")[0]
17 | return request.META.get(REMOTE_ADDR)
18 |
--------------------------------------------------------------------------------
/ipinfo_django/ip_selector/interface.py:
--------------------------------------------------------------------------------
1 | """
2 | Abstract interface for selecting IP from incoming request.
3 | """
4 |
5 | import abc
6 |
7 |
8 | class IPSelectorInterface(metaclass=abc.ABCMeta):
9 | """Interface for selecting IP."""
10 |
11 | @abc.abstractmethod
12 | def get_ip(self, request):
13 | pass
14 |
--------------------------------------------------------------------------------
/ipinfo_django/ip_selector/remote_client.py:
--------------------------------------------------------------------------------
1 | """
2 | An IP selector implementation returning client IP from REMOTE_ADDR.
3 | """
4 |
5 | from .interface import IPSelectorInterface
6 | from ipinfo_django.helpers import REMOTE_ADDR
7 |
8 |
9 | class ClientIPSelector(IPSelectorInterface):
10 | """Use client IP address from REMOTE_ADDR."""
11 |
12 | def get_ip(self, request):
13 | return request.META.get(REMOTE_ADDR)
14 |
--------------------------------------------------------------------------------
/ipinfo_django/middleware.py:
--------------------------------------------------------------------------------
1 | import logging
2 | import traceback
3 |
4 | import ipinfo
5 | from django.conf import settings
6 |
7 | from ipinfo_django.helpers import is_bot
8 | from ipinfo_django.ip_selector.default import DefaultIPSelector
9 |
10 | LOGGER = logging.getLogger(__name__)
11 |
12 |
13 | class IPinfoMiddleware:
14 | def __init__(self, get_response=None):
15 | """
16 | Initializes class while gettings user settings and creating the cache.
17 | """
18 | self.get_response = get_response
19 | self.filter = getattr(settings, "IPINFO_FILTER", self.is_bot)
20 |
21 | ipinfo_token = getattr(settings, "IPINFO_TOKEN", None)
22 | ipinfo_settings = getattr(settings, "IPINFO_SETTINGS", {})
23 | self.ip_selector = getattr(
24 | settings, "IPINFO_IP_SELECTOR", DefaultIPSelector()
25 | )
26 | self.ipinfo = ipinfo.getHandler(ipinfo_token, **ipinfo_settings)
27 |
28 | def __call__(self, request):
29 | """Middleware hook that acts on and modifies request object."""
30 | try:
31 | if self.filter and self.filter(request):
32 | request.ipinfo = None
33 | else:
34 | request.ipinfo = self.ipinfo.getDetails(
35 | self.ip_selector.get_ip(request)
36 | )
37 | except Exception as exc:
38 | request.ipinfo = None
39 | LOGGER.error(traceback.format_exc())
40 |
41 | response = self.get_response(request)
42 | return response
43 |
44 | def is_bot(self, request):
45 | return is_bot(request)
46 |
47 |
48 | class IPinfoAsyncMiddleware:
49 | sync_capable = False
50 | async_capable = True
51 |
52 | def __init__(self, get_response):
53 | """Initialize class, get settings, and create the cache."""
54 | self.get_response = get_response
55 |
56 | self.filter = getattr(settings, "IPINFO_FILTER", self.is_bot)
57 |
58 | ipinfo_token = getattr(settings, "IPINFO_TOKEN", None)
59 | ipinfo_settings = getattr(settings, "IPINFO_SETTINGS", {})
60 | self.ip_selector = getattr(
61 | settings, "IPINFO_IP_SELECTOR", DefaultIPSelector()
62 | )
63 | self.ipinfo = ipinfo.getHandlerAsync(ipinfo_token, **ipinfo_settings)
64 |
65 | def __call__(self, request):
66 | return self.__acall__(request)
67 |
68 | async def __acall__(self, request):
69 | """Middleware hook that acts on and modifies request object."""
70 | try:
71 | if self.filter and self.filter(request):
72 | request.ipinfo = None
73 | else:
74 | request.ipinfo = await self.ipinfo.getDetails(
75 | self.ip_selector.get_ip(request)
76 | )
77 | except Exception:
78 | request.ipinfo = None
79 | LOGGER.error(traceback.format_exc())
80 |
81 | response = await self.get_response(request)
82 | return response
83 |
84 | def is_bot(self, request):
85 | return is_bot(request)
86 |
--------------------------------------------------------------------------------
/pyproject.toml:
--------------------------------------------------------------------------------
1 | [build-system]
2 | requires = ["setuptools >= 40.6.0", "wheel"]
3 | build-backend = "setuptools.build_meta"
--------------------------------------------------------------------------------
/requirements/compile.py:
--------------------------------------------------------------------------------
1 | import os
2 | import subprocess
3 | import sys
4 | from pathlib import Path
5 |
6 | if __name__ == "__main__":
7 | os.chdir(Path(__file__).parent)
8 | os.environ["CUSTOM_COMPILE_COMMAND"] = "requirements/compile.py"
9 | common_args = ["-m", "piptools", "compile", "-U", "--generate-hashes"] + sys.argv[1:]
10 |
11 | subprocess.run(
12 | [
13 | "python3.10",
14 | *common_args,
15 | "-P",
16 | "Django==3.2",
17 | "-o",
18 | "py310-django32.txt",
19 | ],
20 | check=True,
21 | )
22 |
23 | subprocess.run(
24 | [
25 | "python3.10",
26 | *common_args,
27 | "-P",
28 | "Django==4.0",
29 | "-o",
30 | "py310-django40.txt",
31 | ],
32 | check=True,
33 | )
34 |
--------------------------------------------------------------------------------
/requirements/py310-django32.txt:
--------------------------------------------------------------------------------
1 | #
2 | # This file is autogenerated by pip-compile with python 3.10
3 | # To update, run:
4 | #
5 | # requirements/compile.py
6 | #
7 | asgiref==3.5.2 \
8 | --hash=sha256:1d2880b792ae8757289136f1db2b7b99100ce959b2aa57fd69dab783d05afac4 \
9 | --hash=sha256:4a29362a6acebe09bf1d6640db38c1dc3d9217c68e6f9f6204d72667fc19a424
10 | # via django
11 | attrs==22.1.0 \
12 | --hash=sha256:29adc2665447e5191d0e7c568fde78b21f9672d344281d0c6e1ab085429b22b6 \
13 | --hash=sha256:86efa402f67bf2df34f51a335487cf46b1ec130d02b8d39fd248abfd30da551c
14 | # via pytest
15 | django==3.2 \
16 | --hash=sha256:0604e84c4fb698a5e53e5857b5aea945b2f19a18f25f10b8748dbdf935788927 \
17 | --hash=sha256:21f0f9643722675976004eb683c55d33c05486f94506672df3d6a141546f389d
18 | # via -r requirements.in
19 | iniconfig==1.1.1 \
20 | --hash=sha256:011e24c64b7f47f6ebd835bb12a743f2fbe9a26d4cecaa7f53bc4f35ee9da8b3 \
21 | --hash=sha256:bc3af051d7d14b2ee5ef9969666def0cd1a000e121eaea580d4a313df4b37f32
22 | # via pytest
23 | packaging==21.3 \
24 | --hash=sha256:dd47c42927d89ab911e606518907cc2d3a1f38bbd026385970643f9c5b8ecfeb \
25 | --hash=sha256:ef103e05f519cdc783ae24ea4e2e0f508a9c99b2d4969652eed6a2e1ea5bd522
26 | # via pytest
27 | pluggy==1.0.0 \
28 | --hash=sha256:4224373bacce55f955a878bf9cfa763c1e360858e330072059e10bad68531159 \
29 | --hash=sha256:74134bbf457f031a36d68416e1509f34bd5ccc019f0bcc952c7b909d06b37bd3
30 | # via pytest
31 | py==1.11.0 \
32 | --hash=sha256:51c75c4126074b472f746a24399ad32f6053d1b34b68d2fa41e558e6f4a98719 \
33 | --hash=sha256:607c53218732647dff4acdfcd50cb62615cedf612e72d1724fb1a0cc6405b378
34 | # via pytest
35 | pyparsing==3.0.9 \
36 | --hash=sha256:2b020ecf7d21b687f219b71ecad3631f644a47f01403fa1d1036b0c6416d70fb \
37 | --hash=sha256:5026bae9a10eeaefb61dab2f09052b9f4307d44aee4eda64b309723d8d206bbc
38 | # via packaging
39 | pytest==7.1.2 \
40 | --hash=sha256:13d0e3ccfc2b6e26be000cb6568c832ba67ba32e719443bfe725814d3c42433c \
41 | --hash=sha256:a06a0425453864a270bc45e71f783330a7428defb4230fb5e6a731fde06ecd45
42 | # via
43 | # -r requirements.in
44 | # pytest-asyncio
45 | # pytest-django
46 | pytest-asyncio==0.19.0 \
47 | --hash=sha256:7a97e37cfe1ed296e2e84941384bdd37c376453912d397ed39293e0916f521fa \
48 | --hash=sha256:ac4ebf3b6207259750bc32f4c1d8fcd7e79739edbc67ad0c58dd150b1d072fed
49 | # via -r requirements.in
50 | pytest-django==4.5.2 \
51 | --hash=sha256:c60834861933773109334fe5a53e83d1ef4828f2203a1d6a0fa9972f4f75ab3e \
52 | --hash=sha256:d9076f759bb7c36939dbdd5ae6633c18edfc2902d1a69fdbefd2426b970ce6c2
53 | # via -r requirements.in
54 | pytz==2022.1 \
55 | --hash=sha256:1e760e2fe6a8163bc0b3d9a19c4f84342afa0a2affebfaa84b01b978a02ecaa7 \
56 | --hash=sha256:e68985985296d9a66a881eb3193b0906246245294a881e7c8afe623866ac6a5c
57 | # via django
58 | sqlparse==0.4.2 \
59 | --hash=sha256:0c00730c74263a94e5a9919ade150dfc3b19c574389985446148402998287dae \
60 | --hash=sha256:48719e356bb8b42991bdbb1e8b83223757b93789c00910a616a071910ca4a64d
61 | # via django
62 | tomli==2.0.1 \
63 | --hash=sha256:939de3e7a6161af0c887ef91b7d41a53e7c5a1ca976325f429cb46ea9bc30ecc \
64 | --hash=sha256:de526c12914f0c550d15924c62d72abc48d6fe7364aa87328337a31007fe8a4f
65 | # via pytest
66 |
--------------------------------------------------------------------------------
/requirements/py310-django40.txt:
--------------------------------------------------------------------------------
1 | #
2 | # This file is autogenerated by pip-compile with python 3.10
3 | # To update, run:
4 | #
5 | # requirements/compile.py
6 | #
7 | asgiref==3.5.2 \
8 | --hash=sha256:1d2880b792ae8757289136f1db2b7b99100ce959b2aa57fd69dab783d05afac4 \
9 | --hash=sha256:4a29362a6acebe09bf1d6640db38c1dc3d9217c68e6f9f6204d72667fc19a424
10 | # via django
11 | attrs==22.1.0 \
12 | --hash=sha256:29adc2665447e5191d0e7c568fde78b21f9672d344281d0c6e1ab085429b22b6 \
13 | --hash=sha256:86efa402f67bf2df34f51a335487cf46b1ec130d02b8d39fd248abfd30da551c
14 | # via pytest
15 | django==4.0 \
16 | --hash=sha256:59304646ebc6a77b9b6a59adc67d51ecb03c5e3d63ed1f14c909cdfda84e8010 \
17 | --hash=sha256:d5a8a14da819a8b9237ee4d8c78dfe056ff6e8a7511987be627192225113ee75
18 | # via -r requirements.in
19 | iniconfig==1.1.1 \
20 | --hash=sha256:011e24c64b7f47f6ebd835bb12a743f2fbe9a26d4cecaa7f53bc4f35ee9da8b3 \
21 | --hash=sha256:bc3af051d7d14b2ee5ef9969666def0cd1a000e121eaea580d4a313df4b37f32
22 | # via pytest
23 | packaging==21.3 \
24 | --hash=sha256:dd47c42927d89ab911e606518907cc2d3a1f38bbd026385970643f9c5b8ecfeb \
25 | --hash=sha256:ef103e05f519cdc783ae24ea4e2e0f508a9c99b2d4969652eed6a2e1ea5bd522
26 | # via pytest
27 | pluggy==1.0.0 \
28 | --hash=sha256:4224373bacce55f955a878bf9cfa763c1e360858e330072059e10bad68531159 \
29 | --hash=sha256:74134bbf457f031a36d68416e1509f34bd5ccc019f0bcc952c7b909d06b37bd3
30 | # via pytest
31 | py==1.11.0 \
32 | --hash=sha256:51c75c4126074b472f746a24399ad32f6053d1b34b68d2fa41e558e6f4a98719 \
33 | --hash=sha256:607c53218732647dff4acdfcd50cb62615cedf612e72d1724fb1a0cc6405b378
34 | # via pytest
35 | pyparsing==3.0.9 \
36 | --hash=sha256:2b020ecf7d21b687f219b71ecad3631f644a47f01403fa1d1036b0c6416d70fb \
37 | --hash=sha256:5026bae9a10eeaefb61dab2f09052b9f4307d44aee4eda64b309723d8d206bbc
38 | # via packaging
39 | pytest==7.1.2 \
40 | --hash=sha256:13d0e3ccfc2b6e26be000cb6568c832ba67ba32e719443bfe725814d3c42433c \
41 | --hash=sha256:a06a0425453864a270bc45e71f783330a7428defb4230fb5e6a731fde06ecd45
42 | # via
43 | # -r requirements.in
44 | # pytest-asyncio
45 | # pytest-django
46 | pytest-asyncio==0.19.0 \
47 | --hash=sha256:7a97e37cfe1ed296e2e84941384bdd37c376453912d397ed39293e0916f521fa \
48 | --hash=sha256:ac4ebf3b6207259750bc32f4c1d8fcd7e79739edbc67ad0c58dd150b1d072fed
49 | # via -r requirements.in
50 | pytest-django==4.5.2 \
51 | --hash=sha256:c60834861933773109334fe5a53e83d1ef4828f2203a1d6a0fa9972f4f75ab3e \
52 | --hash=sha256:d9076f759bb7c36939dbdd5ae6633c18edfc2902d1a69fdbefd2426b970ce6c2
53 | # via -r requirements.in
54 | sqlparse==0.4.2 \
55 | --hash=sha256:0c00730c74263a94e5a9919ade150dfc3b19c574389985446148402998287dae \
56 | --hash=sha256:48719e356bb8b42991bdbb1e8b83223757b93789c00910a616a071910ca4a64d
57 | # via django
58 | tomli==2.0.1 \
59 | --hash=sha256:939de3e7a6161af0c887ef91b7d41a53e7c5a1ca976325f429cb46ea9bc30ecc \
60 | --hash=sha256:de526c12914f0c550d15924c62d72abc48d6fe7364aa87328337a31007fe8a4f
61 | # via pytest
62 |
--------------------------------------------------------------------------------
/requirements/requirements.in:
--------------------------------------------------------------------------------
1 | django
2 | pytest
3 | pytest-asyncio
4 | pytest-django
--------------------------------------------------------------------------------
/scripts/ctags.sh:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 |
3 | # Regenerate ctags.
4 |
5 | ctags \
6 | --recurse=yes \
7 | --exclude=node_modules \
8 | --exclude=dist \
9 | --exclude=build \
10 | --exclude=target \
11 | -f .vim/tags \
12 | --tag-relative=never \
13 | --totals=yes \
14 | ./ipinfo_django
15 |
--------------------------------------------------------------------------------
/scripts/fmt.sh:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 |
3 | DIR=`dirname $0`
4 |
5 | # Format the project.
6 |
7 | black -l 79 \
8 | $DIR/../setup.py \
9 | $DIR/../ipinfo_django \
10 | $DIR/../tests
11 |
--------------------------------------------------------------------------------
/scripts/publish.sh:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 |
3 | python setup.py sdist bdist_wheel
4 | twine upload dist/*
5 |
--------------------------------------------------------------------------------
/scripts/test.sh:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 |
3 | PYTHONPATH=. tox
4 |
--------------------------------------------------------------------------------
/setup.py:
--------------------------------------------------------------------------------
1 | from setuptools import setup
2 |
3 | long_description = """
4 | The official Django library for IPinfo.
5 |
6 | IPinfo prides itself on being the most reliable, accurate, and in-depth source of IP address data available anywhere.
7 | We process terabytes of data to produce our custom IP geolocation, company, carrier and IP type data sets.
8 | You can visit our developer docs at https://ipinfo.io/developers.
9 | """
10 |
11 | setup(
12 | name="ipinfo_django",
13 | version="2.0.0",
14 | description="Official Django library for IPinfo",
15 | long_description=long_description,
16 | url="https://github.com/ipinfo/django",
17 | author="IPinfo",
18 | author_email="support@ipinfo.io",
19 | license="Apache License 2.0",
20 | packages=["ipinfo_django", "ipinfo_django.ip_selector"],
21 | install_requires=["django", "ipinfo==4.2.1"],
22 | zip_safe=False,
23 | )
24 |
--------------------------------------------------------------------------------
/tests/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ipinfo/django/302ebf81ed446fb4f7ad602eecdf5711298f2389/tests/__init__.py
--------------------------------------------------------------------------------
/tests/settings.py:
--------------------------------------------------------------------------------
1 | DEBUG = False
2 | SECRET_KEY = "FOR-TESTING-ONLY"
3 |
4 | ROOT_URLCONF = "tests.urls"
5 |
6 | MIDDLEWARE = [
7 | "ipinfo_django.middleware.IPinfoAsyncMiddleware",
8 | ]
9 |
10 | USE_TZ = False
11 |
--------------------------------------------------------------------------------
/tests/test_async_middleware.py:
--------------------------------------------------------------------------------
1 | from http import HTTPStatus
2 | from unittest import mock
3 |
4 | import pytest
5 | from ipinfo.details import Details
6 |
7 |
8 | @pytest.mark.asyncio
9 | async def test_middleware_appends_ip_info(async_client):
10 | with mock.patch("ipinfo.AsyncHandler.getDetails") as mocked_getDetails:
11 | mocked_getDetails.return_value = Details({"ip": "127.0.0.1"})
12 | res = await async_client.get("/test_view/")
13 | assert res.status_code == HTTPStatus.OK
14 | assert b"For testing: 127.0.0.1" in res.content
15 |
16 |
17 | @pytest.mark.asyncio
18 | async def test_middleware_filters(async_client):
19 | res = await async_client.get("/test_view/", USER_AGENT="some bot")
20 | assert res.status_code == HTTPStatus.OK
21 | assert b"Request filtered." in res.content
22 |
23 |
24 | @pytest.mark.asyncio
25 | async def test_middleware_behind_proxy(async_client):
26 | with mock.patch("ipinfo.AsyncHandler.getDetails") as mocked_getDetails:
27 | mocked_getDetails.return_value = Details({"ip": "93.44.186.197"})
28 | res = await async_client.get(
29 | "/test_view/", X_FORWARDED_FOR="93.44.186.197"
30 | )
31 |
32 | mocked_getDetails.assert_called_once_with("93.44.186.197")
33 | assert res.status_code == HTTPStatus.OK
34 | assert b"For testing: 93.44.186.197" in res.content
35 |
36 |
37 | @pytest.mark.asyncio
38 | async def test_middleware_not_behind_proxy(async_client):
39 | with mock.patch("ipinfo.AsyncHandler.getDetails") as mocked_getDetails:
40 | mocked_getDetails.return_value = Details({"ip": "127.0.0.1"})
41 | res = await async_client.get("/test_view/")
42 |
43 | mocked_getDetails.assert_called_once_with("127.0.0.1")
44 | assert res.status_code == HTTPStatus.OK
45 | assert b"For testing: 127.0.0.1" in res.content
46 |
--------------------------------------------------------------------------------
/tests/urls.py:
--------------------------------------------------------------------------------
1 | from django.http import HttpResponse
2 | from django.urls import path
3 |
4 |
5 | async def test_view(request):
6 | ipinfo = getattr(request, "ipinfo", None)
7 |
8 | if ipinfo:
9 | return HttpResponse(f"For testing: {ipinfo.ip}", status=200)
10 |
11 | return HttpResponse("Request filtered.", status=200)
12 |
13 |
14 | urlpatterns = [path("test_view/", test_view)]
15 |
--------------------------------------------------------------------------------
/tox.ini:
--------------------------------------------------------------------------------
1 | [tox]
2 | isolated_build = True
3 | envlist =
4 | py3.10-django{32}
5 | py3.10-django{40}
6 |
7 | [testenv]
8 | commands = pytest {posargs}
9 | passenv = PYTHONPATH
10 |
11 | [testenv:py3.10-django32]
12 | commands = pytest tests/test_async_middleware.py
13 | deps = -rrequirements/py310-django32.txt
14 |
15 | [testenv:py3.10-django40]
16 | commands = pytest tests/test_async_middleware.py
17 | deps = -rrequirements/py310-django40.txt
18 |
19 | [pytest]
20 | DJANGO_SETTINGS_MODULE = tests.settings
21 | python_files = test_*.py
22 |
--------------------------------------------------------------------------------