├── airports ├── __init__.py ├── tests │ ├── __init__.py │ ├── settings.py │ ├── test_models.py │ └── test_management.py ├── management │ ├── __init__.py │ └── commands │ │ ├── __init__.py │ │ └── airports.py ├── migrations │ ├── __init__.py │ ├── 0004_alter_airport_id.py │ ├── 0003_auto_20190321_1026.py │ ├── 0005_auto_20211222_0812.py │ ├── 0002_auto_20190225_0210.py │ └── 0001_initial.py ├── locale │ └── ru │ │ └── LC_MESSAGES │ │ ├── django.mo │ │ └── django.po ├── apps.py ├── admin.py └── models.py ├── example ├── .gitignore ├── templates │ └── .gitkeep ├── requirements.txt ├── manage.py ├── urls.py ├── README.rst └── settings.py ├── docs ├── authors.rst ├── readme.rst ├── contributing.rst ├── history.rst ├── modules.rst ├── airports.management.rst ├── usage.rst ├── airports.migrations.rst ├── index.rst ├── airports.management.commands.rst ├── airports.rst ├── installation.rst ├── Makefile ├── make.bat └── conf.py ├── logo.png ├── setup.py ├── MANIFEST.in ├── AUTHORS.rst ├── .coveragerc ├── .github └── ISSUE_TEMPLATE.md ├── CHANGES.rst ├── tox.ini ├── .travis.yml ├── LICENSE ├── Makefile ├── setup.cfg ├── .gitignore ├── README.rst ├── PYPIREADME.rst └── CONTRIBUTING.rst /airports/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /airports/tests/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /example/.gitignore: -------------------------------------------------------------------------------- 1 | data/ 2 | -------------------------------------------------------------------------------- /example/templates/.gitkeep: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /airports/management/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /airports/migrations/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /airports/management/commands/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /docs/authors.rst: -------------------------------------------------------------------------------- 1 | .. include:: ../AUTHORS.rst 2 | -------------------------------------------------------------------------------- /docs/readme.rst: -------------------------------------------------------------------------------- 1 | .. include:: ../README.rst 2 | -------------------------------------------------------------------------------- /docs/contributing.rst: -------------------------------------------------------------------------------- 1 | .. include:: ../CONTRIBUTING.rst 2 | -------------------------------------------------------------------------------- /docs/history.rst: -------------------------------------------------------------------------------- 1 | .. :changelog: 2 | 3 | .. include:: ../CHANGES.rst 4 | -------------------------------------------------------------------------------- /logo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bashu/django-airports/HEAD/logo.png -------------------------------------------------------------------------------- /example/requirements.txt: -------------------------------------------------------------------------------- 1 | django>3.2,<3.3 2 | django-cities>=0.5 3 | requests 4 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | from setuptools import setup 3 | 4 | setup() 5 | -------------------------------------------------------------------------------- /docs/modules.rst: -------------------------------------------------------------------------------- 1 | airports 2 | ======== 3 | 4 | .. toctree:: 5 | :maxdepth: 4 6 | 7 | airports 8 | -------------------------------------------------------------------------------- /airports/locale/ru/LC_MESSAGES/django.mo: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bashu/django-airports/HEAD/airports/locale/ru/LC_MESSAGES/django.mo -------------------------------------------------------------------------------- /MANIFEST.in: -------------------------------------------------------------------------------- 1 | include AUTHORS.rst 2 | include CHANGES.rst 3 | include README.rst 4 | include LICENSE 5 | recursive-exclude example * 6 | recursive-include airports/locale *.po *.mo 7 | -------------------------------------------------------------------------------- /airports/apps.py: -------------------------------------------------------------------------------- 1 | from django.apps import AppConfig 2 | 3 | 4 | class AirportsConfig(AppConfig): 5 | name = "airports" 6 | default_auto_field = "django.db.models.AutoField" 7 | -------------------------------------------------------------------------------- /AUTHORS.rst: -------------------------------------------------------------------------------- 1 | Authors 2 | ======= 3 | 4 | * Basil Shubin 5 | * Antonio Ercole De Luca 6 | 7 | Contributors 8 | ------------ 9 | 10 | None yet. Why not be the first? 11 | -------------------------------------------------------------------------------- /.coveragerc: -------------------------------------------------------------------------------- 1 | [run] 2 | omit = */migrations/*,*__init__* 3 | source = airports 4 | 5 | [report] 6 | exclude_lines = 7 | pragma: no cover 8 | def __repr__ 9 | raise AssertionError 10 | raise NotImplementedError 11 | if __name__ == .__main__.: 12 | # -*- coding: utf-8 -*- 13 | pass 14 | [run] 15 | -------------------------------------------------------------------------------- /docs/airports.management.rst: -------------------------------------------------------------------------------- 1 | airports.management package 2 | =========================== 3 | 4 | Subpackages 5 | ----------- 6 | 7 | .. toctree:: 8 | 9 | airports.management.commands 10 | 11 | Module contents 12 | --------------- 13 | 14 | .. automodule:: airports.management 15 | :members: 16 | :undoc-members: 17 | :show-inheritance: 18 | -------------------------------------------------------------------------------- /airports/admin.py: -------------------------------------------------------------------------------- 1 | from django.contrib import admin 2 | 3 | from .models import Airport 4 | 5 | 6 | class AirportAdmin(admin.ModelAdmin): 7 | list_display = ("id", "name", "iata", "icao", "city", "region", "country") 8 | search_fields = ("name", "iata", "icao") 9 | list_filter = ("country",) 10 | raw_id_fields = ["city", "region", "country"] 11 | 12 | 13 | admin.site.register(Airport, AirportAdmin) 14 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE.md: -------------------------------------------------------------------------------- 1 | * django-airports version: 2 | * Django version: 3 | * Python version: 4 | * Operating System: 5 | 6 | ### Description 7 | 8 | Describe what you were trying to get done. 9 | Tell us what happened, what went wrong, and what you expected to happen. 10 | 11 | ### What I Did 12 | 13 | ``` 14 | Paste the command(s) you ran and the output. 15 | If there was a crash, please include the traceback here. 16 | ``` 17 | -------------------------------------------------------------------------------- /example/manage.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | import os 3 | import sys 4 | 5 | if __name__ == "__main__": 6 | os.environ.setdefault("DJANGO_SETTINGS_MODULE", "example.settings") 7 | 8 | from django.core.management import execute_from_command_line 9 | 10 | # Allow starting the app without installing the module. 11 | sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.realpath(__file__)))) 12 | 13 | execute_from_command_line(sys.argv) 14 | -------------------------------------------------------------------------------- /docs/usage.rst: -------------------------------------------------------------------------------- 1 | ===== 2 | Usage 3 | ===== 4 | 5 | Requirements (Ubuntu 16.04):: 6 | 7 | sudo apt-get install -y libsqlite3-mod-spatialite binutils libproj-dev gdal-bin 8 | 9 | Install django-airports:: 10 | 11 | pip install django-airports 12 | 13 | Add it to your `INSTALLED_APPS`: 14 | 15 | .. code-block:: python 16 | 17 | INSTALLED_APPS = ( 18 | ... 19 | 'cities', 20 | 'airports', 21 | 'django.contrib.gis', 22 | ... 23 | ) 24 | -------------------------------------------------------------------------------- /docs/airports.migrations.rst: -------------------------------------------------------------------------------- 1 | airports.migrations package 2 | =========================== 3 | 4 | Submodules 5 | ---------- 6 | 7 | airports.migrations.0001_initial module 8 | --------------------------------------- 9 | 10 | .. automodule:: airports.migrations.0001_initial 11 | :members: 12 | :undoc-members: 13 | :show-inheritance: 14 | 15 | 16 | Module contents 17 | --------------- 18 | 19 | .. automodule:: airports.migrations 20 | :members: 21 | :undoc-members: 22 | :show-inheritance: 23 | -------------------------------------------------------------------------------- /CHANGES.rst: -------------------------------------------------------------------------------- 1 | Changes 2 | ------- 3 | 4 | 1.0.3 (2021-12-22) 5 | ~~~~~~~~~~~~~~~~~~ 6 | 7 | * Fixed broken release. 8 | 9 | 1.0.2 (2021-12-22) 10 | ~~~~~~~~~~~~~~~~~~ 11 | 12 | * Include missing .mo files. 13 | 14 | 1.0.1 (2021-12-22) 15 | ~~~~~~~~~~~~~~~~~~ 16 | 17 | * Added ru translation. 18 | * Renamed city_name field to municipality, local field to local_code. 19 | 20 | 1.0.0 (2021-12-21) 21 | ~~~~~~~~~~~~~~~~~~ 22 | 23 | * Added Django 3+ support. 24 | * Dropped Python 2.7 support. 25 | * Dropped Django 1.10 / 1.11 support. 26 | -------------------------------------------------------------------------------- /docs/index.rst: -------------------------------------------------------------------------------- 1 | .. complexity documentation master file, created by 2 | sphinx-quickstart on Tue Jul 9 22:26:36 2013. 3 | You can adapt this file completely to your liking, but it should at least 4 | contain the root `toctree` directive. 5 | 6 | Welcome to django-airports's documentation! 7 | ================================================================= 8 | 9 | Contents: 10 | 11 | .. toctree:: 12 | :maxdepth: 2 13 | 14 | readme 15 | installation 16 | usage 17 | contributing 18 | authors 19 | history 20 | -------------------------------------------------------------------------------- /airports/migrations/0004_alter_airport_id.py: -------------------------------------------------------------------------------- 1 | # Generated by Django 3.2.10 on 2021-12-17 10:34 2 | 3 | from django.db import migrations, models 4 | 5 | 6 | class Migration(migrations.Migration): 7 | 8 | dependencies = [ 9 | ("airports", "0003_auto_20190321_1026"), 10 | ] 11 | 12 | operations = [ 13 | migrations.AlterField( 14 | model_name="airport", 15 | name="id", 16 | field=models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name="ID"), 17 | ), 18 | ] 19 | -------------------------------------------------------------------------------- /tox.ini: -------------------------------------------------------------------------------- 1 | [tox] 2 | distribute = False 3 | envlist = 4 | py{36,37,38,39}-dj{22,30,31,32} 5 | skip_missing_interpreters = True 6 | 7 | [travis] 8 | python = 9 | 3.6: py36 10 | 3.7: py37 11 | 3.8: py38 12 | 3.9: py39 13 | 14 | [testenv] 15 | usedevelop = True 16 | extras = test 17 | setenv = 18 | DJANGO_SETTINGS_MODULE = airports.tests.settings 19 | deps = 20 | dj22: Django>=2.2,<2.3 21 | dj30: Django>=3.0,<3.1 22 | dj31: Django>=3.1,<3.2 23 | dj32: Django>=3.2,<3.3 24 | commands = pytest --cov --cov-append --cov-report= 25 | -------------------------------------------------------------------------------- /docs/airports.management.commands.rst: -------------------------------------------------------------------------------- 1 | airports.management.commands package 2 | ==================================== 3 | 4 | Submodules 5 | ---------- 6 | 7 | airports.management.commands.airports module 8 | -------------------------------------------- 9 | 10 | .. automodule:: airports.management.commands.airports 11 | :members: 12 | :undoc-members: 13 | :show-inheritance: 14 | 15 | 16 | Module contents 17 | --------------- 18 | 19 | .. automodule:: airports.management.commands 20 | :members: 21 | :undoc-members: 22 | :show-inheritance: 23 | -------------------------------------------------------------------------------- /docs/airports.rst: -------------------------------------------------------------------------------- 1 | airports package 2 | ================ 3 | 4 | Submodules 5 | ---------- 6 | 7 | airports.apps module 8 | -------------------- 9 | 10 | .. automodule:: airports.apps 11 | :members: 12 | :undoc-members: 13 | :show-inheritance: 14 | 15 | airports.models module 16 | ---------------------- 17 | 18 | .. automodule:: airports.models 19 | :members: 20 | :undoc-members: 21 | :show-inheritance: 22 | 23 | Module contents 24 | --------------- 25 | 26 | .. automodule:: airports 27 | :members: 28 | :undoc-members: 29 | :show-inheritance: 30 | -------------------------------------------------------------------------------- /airports/migrations/0003_auto_20190321_1026.py: -------------------------------------------------------------------------------- 1 | # Generated by Django 2.1.7 on 2019-03-21 17:26 2 | 3 | from django.db import migrations, models 4 | 5 | 6 | class Migration(migrations.Migration): 7 | 8 | dependencies = [ 9 | ("airports", "0002_auto_20190225_0210"), 10 | ] 11 | 12 | operations = [ 13 | migrations.AlterModelOptions( 14 | name="airport", 15 | options={"ordering": ["id"]}, 16 | ), 17 | migrations.RenameField( 18 | model_name="airport", 19 | old_name="airport_id", 20 | new_name="id", 21 | ), 22 | ] 23 | -------------------------------------------------------------------------------- /docs/installation.rst: -------------------------------------------------------------------------------- 1 | ============ 2 | Installation 3 | ============ 4 | Requirements (Ubuntu 16.04):: 5 | 6 | sudo apt-get install -y libsqlite3-mod-spatialite binutils libproj-dev gdal-bin 7 | 8 | 9 | $ easy_install django-airports 10 | 11 | Or, if you have virtualenvwrapper installed:: 12 | 13 | $ mkvirtualenv django-airports 14 | $ pip install django-airports 15 | 16 | Install django-airports:: 17 | 18 | pip install django-airports 19 | 20 | 21 | Add it to your `INSTALLED_APPS`: 22 | 23 | .. code-block:: python 24 | 25 | INSTALLED_APPS = ( 26 | ... 27 | 'cities', 28 | 'airports', 29 | 'django.contrib.gis', 30 | ... 31 | ) 32 | 33 | -------------------------------------------------------------------------------- /airports/migrations/0005_auto_20211222_0812.py: -------------------------------------------------------------------------------- 1 | # Generated by Django 3.2.10 on 2021-12-22 08:12 2 | 3 | import django.contrib.gis.db.models.fields 4 | import django.core.validators 5 | from django.db import migrations, models 6 | 7 | 8 | class Migration(migrations.Migration): 9 | 10 | dependencies = [ 11 | ('airports', '0004_alter_airport_id'), 12 | ] 13 | 14 | operations = [ 15 | migrations.RenameField( 16 | model_name="airport", 17 | old_name="city_name", 18 | new_name="municipality", 19 | ), 20 | migrations.RenameField( 21 | model_name="airport", 22 | old_name="local", 23 | new_name="local_code", 24 | ), 25 | ] 26 | -------------------------------------------------------------------------------- /example/urls.py: -------------------------------------------------------------------------------- 1 | """example URL Configuration 2 | 3 | The `urlpatterns` list routes URLs to views. For more information please see: 4 | https://docs.djangoproject.com/en/1.9/topics/http/urls/ 5 | Examples: 6 | Function views 7 | 1. Add an import: from my_app import views 8 | 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') 9 | Class-based views 10 | 1. Add an import: from other_app.views import Home 11 | 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home') 12 | Including another URLconf 13 | 1. Import the include() function: from django.conf.urls import url, include 14 | 2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls')) 15 | """ 16 | from django.contrib import admin 17 | from django.urls import path 18 | 19 | urlpatterns = [ 20 | path("admin/", admin.site.urls), 21 | ] 22 | -------------------------------------------------------------------------------- /example/README.rst: -------------------------------------------------------------------------------- 1 | Example 2 | ======= 3 | 4 | Your database must support spatial queries, see the `GeoDjango documentation `_ for details and setup instructions. 5 | 6 | To run the example application, make sure you have the required 7 | 8 | packages installed. You can do this using following commands : 9 | 10 | .. code-block:: bash 11 | 12 | mkvirtualenv example 13 | pip install -r example/requirements.txt 14 | 15 | This assumes you already have ``virtualenv`` and ``virtualenvwrapper`` 16 | installed and configured. 17 | 18 | Next, you can setup the django instance using : 19 | 20 | .. code-block:: bash 21 | 22 | python example/manage.py migrate 23 | python example/manage.py airports 24 | 25 | And run it : 26 | 27 | .. code-block:: bash 28 | 29 | python example/manage.py runserver 30 | 31 | Good luck! 32 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | # Config file for automatic testing at travis-ci.org 2 | dist: xenial 3 | language: python 4 | cache: pip 5 | sudo: false 6 | 7 | python: 8 | - "3.6" 9 | - "3.7" 10 | - "3.8" 11 | - "3.9" 12 | 13 | addons: 14 | apt: 15 | sources: 16 | - sourceline: ppa:ubuntugis/ppa 17 | packages: 18 | - gdal-bin 19 | - libgdal-dev 20 | - libproj-dev 21 | - spatialite-bin 22 | - python3-dev 23 | - libsqlite3-mod-spatialite 24 | 25 | before_install: 26 | - python3 -m pip install --upgrade --no-cache-dir setuptools==57.5.0 27 | 28 | install: 29 | # install python gdal package (version must match installed GDAL lib) 30 | - CPLUS_INCLUDE_PATH=/usr/include/gdal C_INCLUDE_PATH=/usr/include/gdal CFLAGS=-I/usr/include/gdal pip install GDAL==2.2.4 31 | 32 | # other dependencies 33 | - pip install tox-travis 34 | 35 | script: 36 | - tox 37 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2014-2021 Basil Shubin 4 | Copyright (c) 2018, Antonio Ercole De Luca 5 | 6 | Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: 7 | 8 | The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. 9 | 10 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 11 | 12 | 13 | 14 | 15 | -------------------------------------------------------------------------------- /airports/tests/settings.py: -------------------------------------------------------------------------------- 1 | # Build paths inside the project like this: os.path.join(BASE_DIR, ...) 2 | import os 3 | 4 | BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) 5 | 6 | SECRET_KEY = "DUMMY_SECRET_KEY" 7 | 8 | INTERNAL_IPS = [] 9 | 10 | # Application definition 11 | 12 | PROJECT_APPS = ["airports.tests", "airports"] 13 | 14 | INSTALLED_APPS = [ 15 | "django.contrib.auth", 16 | "django.contrib.contenttypes", 17 | "django.contrib.staticfiles", 18 | "django.contrib.gis", 19 | "cities", 20 | ] + PROJECT_APPS 21 | 22 | SPATIALITE_LIBRARY_PATH = os.getenv("SPATIALITE_LIBRARY_PATH", "mod_spatialite") 23 | 24 | TEMPLATES = [ 25 | { 26 | "BACKEND": "django.template.backends.django.DjangoTemplates", 27 | "DIRS": [], 28 | "APP_DIRS": True, 29 | "OPTIONS": { 30 | "context_processors": [ 31 | "django.contrib.auth.context_processors.auth", 32 | "django.template.context_processors.debug", 33 | "django.template.context_processors.i18n", 34 | "django.template.context_processors.media", 35 | "django.template.context_processors.request", 36 | "django.template.context_processors.static", 37 | "django.template.context_processors.tz", 38 | "django.contrib.messages.context_processors.messages", 39 | ], 40 | }, 41 | }, 42 | ] 43 | 44 | # Database 45 | # https://docs.djangoproject.com/en/1.8/ref/settings/#databases 46 | 47 | DATABASES = {"default": {"ENGINE": "django.contrib.gis.db.backends.spatialite", "NAME": ":memory:"}} 48 | 49 | # Static files (CSS, JavaScript, Images) 50 | # https://docs.djangoproject.com/en/1.8/howto/static-files/ 51 | 52 | STATIC_URL = "/static/" 53 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | .PHONY: clean-pyc clean-build docs help 2 | .DEFAULT_GOAL := help 3 | define BROWSER_PYSCRIPT 4 | import os, webbrowser, sys 5 | try: 6 | from urllib import pathname2url 7 | except: 8 | from urllib.request import pathname2url 9 | 10 | webbrowser.open("file://" + pathname2url(os.path.abspath(sys.argv[1]))) 11 | endef 12 | export BROWSER_PYSCRIPT 13 | BROWSER := python -c "$$BROWSER_PYSCRIPT" 14 | 15 | help: 16 | @perl -nle'print $& if m{^[a-zA-Z_-]+:.*?## .*$$}' $(MAKEFILE_LIST) | sort | awk 'BEGIN {FS = ":.*?## "}; {printf "\033[36m%-25s\033[0m %s\n", $$1, $$2}' 17 | 18 | clean: clean-build clean-pyc 19 | 20 | clean-build: ## remove build artifacts 21 | rm -fr build/ 22 | rm -fr dist/ 23 | rm -fr *.egg-info 24 | 25 | clean-pyc: ## remove Python file artifacts 26 | find . -name '*.pyc' -exec rm -f {} + 27 | find . -name '*.pyo' -exec rm -f {} + 28 | find . -name '*~' -exec rm -f {} + 29 | 30 | lint: ## check style with flake8 31 | flake8 airports 32 | 33 | test: ## run tests quickly with the default Python 34 | python setup.py test 35 | 36 | test-all: ## run tests on every Python version with tox 37 | tox 38 | 39 | coverage: ## check code coverage quickly with the default Python 40 | coverage run --source airports setup.py test 41 | coverage report -m 42 | coverage html 43 | open htmlcov/index.html 44 | 45 | docs: ## generate Sphinx HTML documentation, including API docs 46 | rm -f docs/django-airports.rst 47 | rm -f docs/modules.rst 48 | sphinx-apidoc -o docs/ airports 49 | $(MAKE) -C docs clean 50 | $(MAKE) -C docs html 51 | $(BROWSER) docs/_build/html/index.html 52 | 53 | release: clean ## package and upload a release 54 | python setup.py sdist bdist_wheel 55 | twine upload 'dist/*' --verbose 56 | 57 | sdist: clean ## package 58 | python setup.py sdist 59 | ls -l dist 60 | -------------------------------------------------------------------------------- /setup.cfg: -------------------------------------------------------------------------------- 1 | [metadata] 2 | name = django-airports 3 | version = 1.0.3 4 | description = "It's like django-cities, but django-airports" 5 | long_description = file: PYPIREADME.rst, CHANGES.rst 6 | long_description_content_type = text/x-rst 7 | author = Basil Shubin 8 | author_email = basil.shubin@gmail.com 9 | url = https://github.com/bashu/django-airports 10 | download_url = https://github.com/bashu/django-airports 11 | license = MIT License 12 | classifiers = 13 | Development Status :: 5 - Production/Stable 14 | Environment :: Web Environment 15 | Intended Audience :: Developers 16 | License :: OSI Approved :: MIT License 17 | Operating System :: OS Independent 18 | Programming Language :: Python 19 | Programming Language :: Python :: 3 :: Only 20 | Programming Language :: Python :: 3.6 21 | Programming Language :: Python :: 3.7 22 | Programming Language :: Python :: 3.8 23 | Programming Language :: Python :: 3.9 24 | Framework :: Django 25 | Framework :: Django :: 2.2 26 | Framework :: Django :: 3.0 27 | Framework :: Django :: 3.1 28 | Framework :: Django :: 3.2 29 | Topic :: Internet :: WWW/HTTP 30 | Topic :: Internet :: WWW/HTTP :: Dynamic Content 31 | Topic :: Software Development :: Libraries :: Python Modules 32 | 33 | [options] 34 | zip_safe = False 35 | include_package_data = True 36 | packages = find: 37 | install_requires = 38 | django-cities>=0.5 39 | requests 40 | 41 | [options.packages.find] 42 | exclude = example* 43 | 44 | [options.extras_require] 45 | develop = 46 | tox 47 | django 48 | pytest-django 49 | pytest 50 | test = 51 | pytest-django 52 | pytest-cov 53 | pytest 54 | 55 | [bdist_wheel] 56 | # No longer universal (Python 3 only) but leaving this section in here will 57 | # trigger zest to build a wheel. 58 | universal = 0 59 | 60 | [flake8] 61 | # Some sane defaults for the code style checker flake8 62 | # black compatibility 63 | max-line-length = 88 64 | # E203 and W503 have edge cases handled by black 65 | extend-ignore = E203, W503 66 | exclude = 67 | .tox 68 | build 69 | dist 70 | .eggs 71 | 72 | [tool:pytest] 73 | DJANGO_SETTINGS_MODULE = airports.tests.settings 74 | -------------------------------------------------------------------------------- /airports/models.py: -------------------------------------------------------------------------------- 1 | from django.contrib.gis.db import models 2 | from django.core.validators import MinLengthValidator 3 | from django.db.models import Manager as GeoManager 4 | from django.utils.encoding import force_str 5 | from django.utils.translation import gettext_lazy as _ 6 | 7 | 8 | class Airport(models.Model): 9 | name = models.CharField(_("name"), max_length=100, help_text=_("The official airport name, including \"Airport\", \"Airstrip\", etc.")) 10 | municipality = models.CharField(_("municipality"), null=True, blank=True, max_length=100, help_text=_("The primary municipality that the airport serves (when available). Note that this is not necessarily the municipality where the airport is physically located.")) 11 | 12 | iata = models.CharField(_("IATA/FAA code"), null=True, blank=True, max_length=3, validators=[MinLengthValidator(3)], help_text=("The three-letter IATA code for the airport (if it has one).")) 13 | icao = models.CharField(_("ICAO code"), null=True, blank=True, max_length=4, validators=[MinLengthValidator(4)]) 14 | ident = models.CharField(_("identifier"), null=True, blank=True, max_length=12, help_text=_("The text identifier used in the OurAirports URL")) 15 | local_code = models.CharField(_("local country code"), null=True, blank=True, max_length=12, help_text=_("The local country code for the airport")) 16 | type = models.CharField(_("type"), max_length=16, default="", help_text=_("The type of the airport. Allowed values are \"closed_airport\", \"heliport\", \"large_airport\", \"medium_airport\", \"seaplane_base\", and \"small_airport\".")) 17 | 18 | altitude = models.FloatField(_("altitude"), default=0, help_text=_("The airport elevation MSL in feet (not metres).")) 19 | location = models.PointField(_("coordinates")) 20 | 21 | country = models.ForeignKey("cities.Country", on_delete=models.DO_NOTHING, null=True) 22 | region = models.ForeignKey("cities.Region", on_delete=models.DO_NOTHING, null=True) 23 | city = models.ForeignKey("cities.City", on_delete=models.DO_NOTHING, null=True) 24 | 25 | objects = GeoManager() 26 | 27 | class Meta: # pylint: disable=C1001 28 | ordering = ["id"] 29 | 30 | def __str__(self): 31 | return force_str(self.name) 32 | -------------------------------------------------------------------------------- /airports/migrations/0002_auto_20190225_0210.py: -------------------------------------------------------------------------------- 1 | # Generated by Django 2.1.7 on 2019-02-25 10:10 2 | 3 | import django.core.validators 4 | import django.db.models.deletion 5 | from django.db import migrations, models 6 | 7 | 8 | class Migration(migrations.Migration): 9 | 10 | dependencies = [ 11 | ("cities", "0011_auto_20180108_0706"), 12 | ("airports", "0001_initial"), 13 | ] 14 | 15 | operations = [ 16 | migrations.AddField( 17 | model_name="airport", 18 | name="city_name", 19 | field=models.CharField(blank=True, max_length=100, null=True, verbose_name="city name"), 20 | ), 21 | migrations.AddField( 22 | model_name="airport", 23 | name="ident", 24 | field=models.CharField(blank=True, max_length=12, null=True, verbose_name="ident code"), 25 | ), 26 | migrations.AddField( 27 | model_name="airport", 28 | name="local", 29 | field=models.CharField(blank=True, max_length=12, null=True, verbose_name="local code"), 30 | ), 31 | migrations.AddField( 32 | model_name="airport", 33 | name="region", 34 | field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.DO_NOTHING, to="cities.Region"), 35 | ), 36 | migrations.AddField( 37 | model_name="airport", 38 | name="type", 39 | field=models.CharField(default="", max_length=16), 40 | ), 41 | migrations.AlterField( 42 | model_name="airport", 43 | name="iata", 44 | field=models.CharField( 45 | blank=True, 46 | max_length=3, 47 | null=True, 48 | validators=[django.core.validators.MinLengthValidator(3)], 49 | verbose_name="IATA/FAA code", 50 | ), 51 | ), 52 | migrations.AlterField( 53 | model_name="airport", 54 | name="icao", 55 | field=models.CharField( 56 | blank=True, 57 | max_length=4, 58 | null=True, 59 | validators=[django.core.validators.MinLengthValidator(4)], 60 | verbose_name="ICAO code", 61 | ), 62 | ), 63 | ] 64 | -------------------------------------------------------------------------------- /airports/locale/ru/LC_MESSAGES/django.po: -------------------------------------------------------------------------------- 1 | # SOME DESCRIPTIVE TITLE. 2 | # Copyright (C) YEAR THE PACKAGE'S COPYRIGHT HOLDER 3 | # This file is distributed under the same license as the PACKAGE package. 4 | # FIRST AUTHOR , YEAR. 5 | # 6 | msgid "" 7 | msgstr "" 8 | "Project-Id-Version: \n" 9 | "Report-Msgid-Bugs-To: \n" 10 | "POT-Creation-Date: 2021-12-22 15:38+0700\n" 11 | "PO-Revision-Date: 2021-12-22 15:42+0700\n" 12 | "Language: ru\n" 13 | "MIME-Version: 1.0\n" 14 | "Content-Type: text/plain; charset=UTF-8\n" 15 | "Content-Transfer-Encoding: 8bit\n" 16 | "Plural-Forms: nplurals=4; plural=(n%10==1 && n%100!=11 ? 0 : n%10>=2 && n" 17 | "%10<=4 && (n%100<12 || n%100>14) ? 1 : n%10==0 || (n%10>=5 && n%10<=9) || (n" 18 | "%100>=11 && n%100<=14)? 2 : 3);\n" 19 | "Last-Translator: Basil S. \n" 20 | "Language-Team: \n" 21 | "X-Generator: Poedit 2.4.2\n" 22 | 23 | #: models.py:9 24 | msgid "name" 25 | msgstr "название" 26 | 27 | #: models.py:9 28 | msgid "The official airport name, including \"Airport\", \"Airstrip\", etc." 29 | msgstr "" 30 | 31 | #: models.py:10 32 | msgid "municipality" 33 | msgstr "муниципалитет" 34 | 35 | #: models.py:10 36 | msgid "" 37 | "The primary municipality that the airport serves (when available). Note that " 38 | "this is not necessarily the municipality where the airport is physically " 39 | "located." 40 | msgstr "" 41 | 42 | #: models.py:12 43 | msgid "IATA/FAA code" 44 | msgstr "код ИАТА" 45 | 46 | #: models.py:13 47 | msgid "ICAO code" 48 | msgstr "код ИКАО" 49 | 50 | #: models.py:14 51 | msgid "identifier" 52 | msgstr "идентификатор" 53 | 54 | #: models.py:14 55 | msgid "The text identifier used in the OurAirports URL" 56 | msgstr "" 57 | 58 | #: models.py:15 59 | msgid "local country code" 60 | msgstr "местный код аэропорта" 61 | 62 | #: models.py:15 63 | msgid "The local country code for the airport" 64 | msgstr "" 65 | 66 | #: models.py:16 67 | msgid "type" 68 | msgstr "тип" 69 | 70 | #: models.py:16 71 | msgid "" 72 | "The type of the airport. Allowed values are \"closed_airport\", \"heliport" 73 | "\", \"large_airport\", \"medium_airport\", \"seaplane_base\", and " 74 | "\"small_airport\"." 75 | msgstr "" 76 | 77 | #: models.py:18 78 | msgid "altitude" 79 | msgstr "высота" 80 | 81 | #: models.py:18 82 | msgid "The airport elevation MSL in feet (not metres)." 83 | msgstr "" 84 | 85 | #: models.py:19 86 | msgid "coordinates" 87 | msgstr "координаты" 88 | -------------------------------------------------------------------------------- /airports/migrations/0001_initial.py: -------------------------------------------------------------------------------- 1 | # Generated by Django 2.0.3 on 2018-03-14 18:17 2 | 3 | import django.contrib.gis.db.models.fields 4 | import django.core.validators 5 | import django.db.models.deletion 6 | from django.conf import settings 7 | from django.db import migrations, models 8 | 9 | 10 | class Migration(migrations.Migration): 11 | 12 | initial = True 13 | 14 | dependencies = [ 15 | migrations.swappable_dependency(settings.CITIES_COUNTRY_MODEL), 16 | migrations.swappable_dependency(settings.CITIES_CITY_MODEL), 17 | ] 18 | 19 | operations = [ 20 | migrations.CreateModel( 21 | name="Airport", 22 | fields=[ 23 | ("airport_id", models.PositiveIntegerField(editable=False, primary_key=True, serialize=False)), 24 | ("name", models.CharField(max_length=100, verbose_name="name")), 25 | ( 26 | "iata", 27 | models.CharField( 28 | blank=True, 29 | max_length=3, 30 | validators=[django.core.validators.MinLengthValidator(3)], 31 | verbose_name="IATA/FAA code", 32 | ), 33 | ), 34 | ( 35 | "icao", 36 | models.CharField( 37 | blank=True, 38 | max_length=4, 39 | validators=[django.core.validators.MinLengthValidator(4)], 40 | verbose_name="ICAO code", 41 | ), 42 | ), 43 | ("altitude", models.FloatField(default=0, verbose_name="altitude")), 44 | ("location", django.contrib.gis.db.models.fields.PointField(srid=4326, verbose_name="location")), 45 | ( 46 | "city", 47 | models.ForeignKey( 48 | null=True, on_delete=django.db.models.deletion.DO_NOTHING, to=settings.CITIES_CITY_MODEL 49 | ), 50 | ), 51 | ( 52 | "country", 53 | models.ForeignKey( 54 | null=True, on_delete=django.db.models.deletion.DO_NOTHING, to=settings.CITIES_COUNTRY_MODEL 55 | ), 56 | ), 57 | ], 58 | options={ 59 | "ordering": ["airport_id"], 60 | }, 61 | ), 62 | ] 63 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | build/ 12 | develop-eggs/ 13 | dist/ 14 | downloads/ 15 | eggs/ 16 | .eggs/ 17 | lib/ 18 | lib64/ 19 | parts/ 20 | sdist/ 21 | var/ 22 | wheels/ 23 | pip-wheel-metadata/ 24 | share/python-wheels/ 25 | *.egg-info/ 26 | .installed.cfg 27 | *.egg 28 | MANIFEST 29 | 30 | # PyInstaller 31 | # Usually these files are written by a python script from a template 32 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 33 | *.manifest 34 | *.spec 35 | 36 | # Installer logs 37 | pip-log.txt 38 | pip-delete-this-directory.txt 39 | 40 | # Unit test / coverage reports 41 | htmlcov/ 42 | .tox/ 43 | .nox/ 44 | .coverage 45 | .coverage.* 46 | .cache 47 | nosetests.xml 48 | coverage.xml 49 | *.cover 50 | *.py,cover 51 | .hypothesis/ 52 | .pytest_cache/ 53 | 54 | # Translations 55 | *.pot 56 | 57 | # Django stuff: 58 | *.log 59 | local_settings.py 60 | db.sqlite3 61 | db.sqlite3-journal 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 | # IPython 80 | profile_default/ 81 | ipython_config.py 82 | 83 | # pyenv 84 | .python-version 85 | 86 | # pipenv 87 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. 88 | # However, in case of collaboration, if having platform-specific dependencies or dependencies 89 | # having no cross-platform support, pipenv may install dependencies that don't work, or not 90 | # install all needed dependencies. 91 | #Pipfile.lock 92 | 93 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow 94 | __pypackages__/ 95 | 96 | # Celery stuff 97 | celerybeat-schedule 98 | celerybeat.pid 99 | 100 | # SageMath parsed files 101 | *.sage.py 102 | 103 | # Environments 104 | .env 105 | .venv 106 | env/ 107 | venv/ 108 | ENV/ 109 | env.bak/ 110 | venv.bak/ 111 | 112 | # Spyder project settings 113 | .spyderproject 114 | .spyproject 115 | 116 | # Rope project settings 117 | .ropeproject 118 | 119 | # mkdocs documentation 120 | /site 121 | 122 | # mypy 123 | .mypy_cache/ 124 | .dmypy.json 125 | dmypy.json 126 | 127 | # Pyre type checker 128 | .pyre/ 129 | -------------------------------------------------------------------------------- /README.rst: -------------------------------------------------------------------------------- 1 | django-airports 2 | =============== 3 | 4 | .. image:: https://img.shields.io/pypi/v/django-airports.svg 5 | :target: https://pypi.python.org/pypi/django-airports/ 6 | 7 | .. image:: https://img.shields.io/pypi/dm/django-airports.svg 8 | :target: https://pypi.python.org/pypi/django-airports/ 9 | 10 | .. image:: https://img.shields.io/github/license/bashu/django-airports.svg 11 | :target: https://pypi.python.org/pypi/django-airports/ 12 | 13 | .. image:: https://app.travis-ci.com/bashu/django-airports.svg?branch=develop 14 | :target: https://app.travis-ci.com/bashu/django-airports 15 | 16 | Provides airports' related models and data (from `OurAirports `_) that can be used in django projects, inspired by `django-cities `_ 17 | 18 | Authored by `Basil Shubin `_, and some great 19 | `contributors `_. 20 | 21 | .. raw:: html 22 | 23 |

24 | 25 |

26 | 27 | Installation 28 | ------------ 29 | 30 | First install the module, preferably in a virtual environment. It can be installed from PyPI: 31 | 32 | .. code-block:: shell 33 | 34 | pip install django-airports 35 | 36 | Requirements 37 | ~~~~~~~~~~~~ 38 | 39 | You must have *django-cities* installed and configured, see the 40 | `django-cities `_ documentation for details and setup instructions. 41 | 42 | Setup 43 | ----- 44 | 45 | First make sure the database support spatial queries, see the `GeoDjango documentation `_ for details and setup instructions. 46 | 47 | You'll need to add ``airports`` to ``INSTALLED_APPS`` in your projects ``settings.py`` file: 48 | 49 | .. code-block:: python 50 | 51 | INSTALLED_APPS += [ 52 | 'airports', 53 | ] 54 | 55 | Then run ``./manage.py migrate`` to create the required database tables. 56 | 57 | Import data 58 | ----------- 59 | 60 | After you have configured all settings, run 61 | 62 | .. code-block:: shell 63 | 64 | python manage.py airports 65 | 66 | The ``airports`` manage command has options, see ``airports --help`` output. 67 | 68 | Second run will update the DB with the latest data from the source csv file. 69 | 70 | Contributing 71 | ------------ 72 | 73 | If you like this module, forked it, or would like to improve it, please let us know! 74 | Pull requests are welcome too. :-) 75 | 76 | License 77 | ------- 78 | 79 | ``django-airports`` is released under the MIT license. 80 | -------------------------------------------------------------------------------- /PYPIREADME.rst: -------------------------------------------------------------------------------- 1 | django-airports 2 | =============== 3 | 4 | .. image:: https://img.shields.io/pypi/v/django-airports.svg 5 | :target: https://pypi.python.org/pypi/django-airports/ 6 | 7 | .. image:: https://img.shields.io/pypi/dm/django-airports.svg 8 | :target: https://pypi.python.org/pypi/django-airports/ 9 | 10 | .. image:: https://img.shields.io/github/license/bashu/django-airports.svg 11 | :target: https://pypi.python.org/pypi/django-airports/ 12 | 13 | .. image:: https://app.travis-ci.com/bashu/django-airports.svg?branch=develop 14 | :target: https://app.travis-ci.com/bashu/django-airports 15 | 16 | Provides airports' related models and data (from `OurAirports `_) that can be used in django projects, inspired by `django-cities `_ 17 | 18 | Authored by `Basil Shubin `_, and some great 19 | `contributors `_. 20 | 21 | .. image:: https://raw.githubusercontent.com/bashu/django-airports/develop/logo.png 22 | :target: https://raw.githubusercontent.com/bashu/django-airports/develop/logo.png 23 | :align: center 24 | :width: 600px 25 | 26 | Installation 27 | ------------ 28 | 29 | First install the module, preferably in a virtual environment. It can be installed from PyPI: 30 | 31 | .. code-block:: shell 32 | 33 | pip install django-airports 34 | 35 | Requirements 36 | ~~~~~~~~~~~~ 37 | 38 | You must have *django-cities* installed and configured, see the 39 | `django-cities `_ documentation for details and setup instructions. 40 | 41 | Setup 42 | ----- 43 | 44 | First make sure the database support spatial queries, see the `GeoDjango documentation `_ for details and setup instructions. 45 | 46 | You'll need to add ``airports`` to ``INSTALLED_APPS`` in your projects ``settings.py`` file: 47 | 48 | .. code-block:: python 49 | 50 | INSTALLED_APPS += [ 51 | 'airports', 52 | ] 53 | 54 | Then run ``./manage.py migrate`` to create the required database tables. 55 | 56 | Import data 57 | ----------- 58 | 59 | After you have configured all settings, run 60 | 61 | .. code-block:: shell 62 | 63 | python manage.py airports 64 | 65 | The ``airports`` manage command has options, see ``airports --help`` output. 66 | 67 | Second run will update the DB with the latest data from the source csv file. 68 | 69 | Contributing 70 | ------------ 71 | 72 | If you like this module, forked it, or would like to improve it, please let us know! 73 | Pull requests are welcome too. :-) 74 | 75 | License 76 | ------- 77 | 78 | ``django-airports`` is released under the MIT license. 79 | -------------------------------------------------------------------------------- /airports/tests/test_models.py: -------------------------------------------------------------------------------- 1 | from cities.models import City, Country, Region 2 | from django.contrib.gis.geos import Point 3 | from django.test import TestCase 4 | 5 | from airports.management.commands.airports import create_airport, get_location_info 6 | 7 | 8 | class AirportTests(TestCase): 9 | def setUp(self): 10 | self.country = Country( 11 | slug="United-States", 12 | name="United States", 13 | code="US", 14 | code3="USA", 15 | population=310232863, 16 | area=9629091, 17 | currency="USD", 18 | currency_name="Dollar", 19 | currency_symbol="$", 20 | language_codes="en-US,es-US,haw,fr", 21 | phone="1", 22 | tld="us", 23 | capital="Washington", 24 | ) 25 | self.country.save() 26 | self.region = Region( 27 | slug="California_US.CA", 28 | name="California", 29 | name_std="California", 30 | code="CA", 31 | country=self.country, 32 | ) 33 | self.region.save() 34 | self.city = City( 35 | slug="5323401-Alpine", 36 | name="Alpine", 37 | name_std="Alpine", 38 | country=self.country, 39 | region=self.region, 40 | location=Point(-116.76641, 32.83505), 41 | population=14236, 42 | elevation=559, 43 | kind="PPL", 44 | timezone="America/Los_Angeles", 45 | ) 46 | self.city.save() 47 | self.id = 8227 48 | self.airport_defaults = dict( 49 | name="On the Rocks Airport", 50 | municipality="Alpine", 51 | iata=None, 52 | icao="1CA6", 53 | local_code="1CA6", 54 | ident="1CA6", 55 | altitude=0.0, 56 | longitude=-116.7229995727539, 57 | latitude=32.76509857177734, 58 | country=self.country, 59 | region=self.region, 60 | city=self.city, 61 | type="small_airport", 62 | ) 63 | 64 | def test_create_airport(self): 65 | country, region, city = get_location_info("Alpine", None, None, -116.7229995727539, 32.76509857177734) 66 | self.assertIsNotNone(country) 67 | self.assertIsNotNone(region) 68 | self.assertIsNotNone(city) 69 | airport = create_airport(id=self.id, **self.airport_defaults) 70 | self.assertIsNotNone(airport) 71 | 72 | def test_create_airport_no_name(self): 73 | country, region, city = get_location_info("", None, None, -116.7229995727539, 32.76509857177734) 74 | self.assertIsNotNone(country) 75 | self.assertIsNotNone(region) 76 | self.assertIsNotNone(city) 77 | defaults = self.airport_defaults 78 | defaults["name"] = "" 79 | airport = create_airport(id=self.id, **defaults) 80 | self.assertIsNotNone(airport) 81 | self.assertEqual(airport.name, "Alpine") 82 | 83 | def test_create_airport_no_municipality(self): 84 | country, region, city = get_location_info("", None, None, -116.7229995727539, 32.76509857177734) 85 | self.assertIsNotNone(country) 86 | self.assertIsNotNone(region) 87 | self.assertIsNotNone(city) 88 | defaults = self.airport_defaults 89 | defaults["name"] = "" 90 | defaults["municipality"] = "" 91 | airport = create_airport(id=self.id, **defaults) 92 | self.assertIsNotNone(airport) 93 | self.assertEqual(airport.name, "Alpine") 94 | -------------------------------------------------------------------------------- /CONTRIBUTING.rst: -------------------------------------------------------------------------------- 1 | ============ 2 | Contributing 3 | ============ 4 | 5 | Contributions are welcome, and they are greatly appreciated! Every 6 | little bit helps, and credit will always be given. 7 | 8 | You can contribute in many ways: 9 | 10 | Types of Contributions 11 | ---------------------- 12 | 13 | Report Bugs 14 | ~~~~~~~~~~~ 15 | 16 | Report bugs at https://github.com/bashu/django-airports/issues. 17 | 18 | If you are reporting a bug, please include: 19 | 20 | * Your operating system name and version. 21 | * Any details about your local setup that might be helpful in troubleshooting. 22 | * Detailed steps to reproduce the bug. 23 | 24 | Fix Bugs 25 | ~~~~~~~~ 26 | 27 | Look through the GitHub issues for bugs. Anything tagged with "bug" 28 | is open to whoever wants to implement it. 29 | 30 | Implement Features 31 | ~~~~~~~~~~~~~~~~~~ 32 | 33 | Look through the GitHub issues for features. Anything tagged with "feature" 34 | is open to whoever wants to implement it. 35 | 36 | Write Documentation 37 | ~~~~~~~~~~~~~~~~~~~ 38 | 39 | django-airports could always use more documentation, whether as part of the 40 | official django-airports docs, in docstrings, or even on the web in blog posts, 41 | articles, and such. 42 | 43 | Submit Feedback 44 | ~~~~~~~~~~~~~~~ 45 | 46 | The best way to send feedback is to file an issue at https://github.com/bashu/django-airports/issues. 47 | 48 | If you are proposing a feature: 49 | 50 | * Explain in detail how it would work. 51 | * Keep the scope as narrow as possible, to make it easier to implement. 52 | * Remember that this is a volunteer-driven project, and that contributions 53 | are welcome :) 54 | 55 | Get Started! 56 | ------------ 57 | 58 | Ready to contribute? Here's how to set up `django-airports` for local development. 59 | 60 | 1. Fork the `django-airports` repo on GitHub. 61 | 2. Clone your fork locally:: 62 | 63 | $ git clone git@github.com:your_name_here/django-airports.git 64 | 65 | 3. Install your local copy into a virtualenv. Assuming you have virtualenvwrapper installed, this is how you set up your fork for local development:: 66 | 67 | $ mkvirtualenv django-airports 68 | $ cd django-airports/ 69 | $ python setup.py develop 70 | 71 | 4. Create a branch for local development:: 72 | 73 | $ git checkout -b name-of-your-bugfix-or-feature 74 | 75 | Now you can make your changes locally. 76 | 77 | 5. When you're done making changes, check that your changes pass flake8 and the 78 | tests, including testing other Python versions with tox:: 79 | 80 | $ flake8 airports 81 | $ python setup.py test 82 | $ tox 83 | 84 | To get flake8 and tox, just pip install them into your virtualenv. 85 | 86 | 6. Commit your changes and push your branch to GitHub:: 87 | 88 | $ git add . 89 | $ git commit -m "Your detailed description of your changes." 90 | $ git push origin name-of-your-bugfix-or-feature 91 | 92 | 7. Submit a pull request through the GitHub website. 93 | 94 | Pull Request Guidelines 95 | ----------------------- 96 | 97 | Before you submit a pull request, check that it meets these guidelines: 98 | 99 | 1. The pull request should include tests. 100 | 2. If the pull request adds functionality, the docs should be updated. Put 101 | your new functionality into a function with a docstring, and add the 102 | feature to the list in README.rst. 103 | 3. The pull request should work for Python 2.6, 2.7, and 3.3, and for PyPy. Check 104 | https://travis-ci.org/bashu/django-airports/pull_requests 105 | and make sure that the tests pass for all supported Python versions. 106 | 107 | Tips 108 | ---- 109 | 110 | To run a subset of tests:: 111 | 112 | $ python -m unittest tests.test_airports 113 | -------------------------------------------------------------------------------- /example/settings.py: -------------------------------------------------------------------------------- 1 | """ 2 | Django settings for example project. 3 | 4 | Generated by Cookiecutter Django Package 5 | 6 | For more information on this file, see 7 | https://docs.djangoproject.com/en/1.9/topics/settings/ 8 | 9 | For the full list of settings and their values, see 10 | https://docs.djangoproject.com/en/1.9/ref/settings/ 11 | """ 12 | 13 | import os 14 | 15 | # Build paths inside the project like this: os.path.join(BASE_DIR, ...) 16 | BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) 17 | 18 | # Quick-start development settings - unsuitable for production 19 | # See https://docs.djangoproject.com/en/1.9/howto/deployment/checklist/ 20 | 21 | # SECURITY WARNING: keep the secret key used in production secret! 22 | SECRET_KEY = "YOUR_SECRET_KEY" 23 | 24 | # SECURITY WARNING: don't run with debug turned on in production! 25 | DEBUG = True 26 | 27 | ALLOWED_HOSTS = [] 28 | 29 | # Application definition 30 | 31 | PROJECT_APPS = [ 32 | "airports", 33 | ] 34 | 35 | INSTALLED_APPS = [ 36 | "django.contrib.admin", 37 | "django.contrib.auth", 38 | "django.contrib.contenttypes", 39 | "django.contrib.sessions", 40 | "django.contrib.messages", 41 | "django.contrib.staticfiles", 42 | "django.contrib.gis", 43 | # if your app has other dependencies that need to be added to the site 44 | # they should be added here 45 | "cities", 46 | ] + PROJECT_APPS 47 | 48 | SPATIALITE_LIBRARY_PATH = os.getenv("SPATIALITE_LIBRARY_PATH", "mod_spatialite") 49 | 50 | MIDDLEWARE = [ 51 | "django.contrib.sessions.middleware.SessionMiddleware", 52 | "django.middleware.common.CommonMiddleware", 53 | "django.middleware.csrf.CsrfViewMiddleware", 54 | "django.contrib.auth.middleware.AuthenticationMiddleware", 55 | # 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 56 | "django.contrib.messages.middleware.MessageMiddleware", 57 | "django.middleware.clickjacking.XFrameOptionsMiddleware", 58 | # 'django.middleware.security.SecurityMiddleware', 59 | ] 60 | 61 | ROOT_URLCONF = "example.urls" 62 | 63 | TEMPLATES = [ 64 | { 65 | "BACKEND": "django.template.backends.django.DjangoTemplates", 66 | "DIRS": [ 67 | os.path.join(BASE_DIR, "templates"), 68 | ], 69 | "APP_DIRS": True, 70 | "OPTIONS": { 71 | "context_processors": [ 72 | "django.template.context_processors.debug", 73 | "django.template.context_processors.request", 74 | "django.contrib.auth.context_processors.auth", 75 | "django.contrib.messages.context_processors.messages", 76 | ], 77 | }, 78 | }, 79 | ] 80 | 81 | # Database 82 | # https://docs.djangoproject.com/en/1.9/ref/settings/#databases 83 | 84 | DATABASES = { 85 | "default": {"ENGINE": "django.contrib.gis.db.backends.spatialite", "NAME": os.path.join(BASE_DIR, "db.sqlite3")} 86 | } 87 | 88 | FIXTURE_DIRS = [ 89 | os.path.join(BASE_DIR, "fixtures"), 90 | ] 91 | 92 | # Internationalization 93 | # https://docs.djangoproject.com/en/1.9/topics/i18n/ 94 | 95 | LANGUAGE_CODE = "en-us" 96 | 97 | TIME_ZONE = "UTC" 98 | 99 | USE_I18N = True 100 | 101 | USE_L10N = True 102 | 103 | USE_TZ = True 104 | 105 | # Static files (CSS, JavaScript, Images) 106 | # https://docs.djangoproject.com/en/1.8/howto/static-files/ 107 | 108 | # Absolute filesystem path to the directory that will hold user-uploaded files. 109 | MEDIA_ROOT = os.path.join(BASE_DIR, "media") 110 | 111 | # URL that handles the media served from MEDIA_ROOT. Make sure to use a 112 | # trailing slash. 113 | MEDIA_URL = "/media/" 114 | 115 | STATIC_ROOT = os.path.join(BASE_DIR, "staticfiles") 116 | 117 | STATIC_URL = "/static/" 118 | 119 | # django-cities 120 | 121 | CITIES_DATA_DIR = os.path.join(BASE_DIR, "data") 122 | -------------------------------------------------------------------------------- /airports/tests/test_management.py: -------------------------------------------------------------------------------- 1 | from cities.models import City, Country, Region 2 | from django.contrib.gis.geos import Point 3 | from django.test import TestCase 4 | 5 | from airports.management.commands.airports import get_location_info 6 | from airports.models import Airport 7 | 8 | 9 | class ManagementCommandTests(TestCase): 10 | def setUp(self): 11 | self.country = Country( 12 | slug="United-States", 13 | name="United States", 14 | code="US", 15 | code3="USA", 16 | population=310232863, 17 | area=9629091, 18 | currency="USD", 19 | currency_name="Dollar", 20 | currency_symbol="$", 21 | language_codes="en-US,es-US,haw,fr", 22 | phone="1", 23 | tld="us", 24 | capital="Washington", 25 | ) 26 | self.country.save() 27 | self.region = Region( 28 | slug="California_US.CA", 29 | name="California", 30 | name_std="California", 31 | code="CA", 32 | country=self.country, 33 | ) 34 | self.region.save() 35 | self.city = City( 36 | slug="5323401-Alpine", 37 | name="Alpine", 38 | name_std="Alpine", 39 | country=self.country, 40 | region=self.region, 41 | location=Point(-116.76641, 32.83505), 42 | population=14236, 43 | elevation=559, 44 | kind="PPL", 45 | timezone="America/Los_Angeles", 46 | ) 47 | self.city.save() 48 | self.airport = Airport( 49 | id=8227, 50 | name="On the Rocks Airport", 51 | municipality="Alpine", 52 | iata=None, 53 | icao="1CA6", 54 | local_code="1CA6", 55 | ident="1CA6", 56 | altitude=0.0, 57 | location=Point(-116.7229995727539, 32.76509857177734), 58 | country=self.country, 59 | region=self.region, 60 | city=self.city, 61 | type="small_airport", 62 | ) 63 | self.airport.save() 64 | 65 | def assert_location_tuple(self, country, region, city): 66 | self.assertEqual(country, self.country) 67 | self.assertEqual(region, self.region) 68 | self.assertEqual(city, self.city) 69 | 70 | def test_get_location_info_name(self): 71 | country, region, city = get_location_info("Alpine", None, None, -116.7229995727539, 32.76509857177734) 72 | self.assert_location_tuple(country, region, city) 73 | 74 | def test_get_location_info_wrong_name(self): 75 | country, region, city = get_location_info("Wrong Name", None, None, -116.7229995727539, 32.76509857177734) 76 | self.assert_location_tuple(country, region, city) 77 | 78 | def test_get_location_info_fix_name(self): 79 | country, region, city = get_location_info("", None, None, -116.7229995727539, 32.76509857177734) 80 | self.assert_location_tuple(country, region, city) 81 | 82 | def test_get_location_info_missing_name(self): 83 | country, region, city = get_location_info("", None, None, -116.7229995727539, 32.76509857177734) 84 | self.assert_location_tuple(country, region, city) 85 | 86 | def test_get_location_info_country(self): 87 | country, region, city = get_location_info("", self.country, None, -116.7229995727539, 32.76509857177734) 88 | self.assert_location_tuple(country, region, city) 89 | 90 | def test_get_location_info_country_region(self): 91 | country, region, city = get_location_info("", self.country, self.region, -116.7229995727539, 32.76509857177734) 92 | self.assert_location_tuple(country, region, city) 93 | 94 | def test_get_location_info_country_region_bad_coords(self): 95 | country, region, city = get_location_info("", self.country, self.region, -116.7, 38.0) 96 | self.assertEqual(country, self.country) 97 | self.assertEqual(region, self.region) 98 | self.assertIsNone(city) 99 | 100 | def test_get_location_info_country_bad_coords(self): 101 | country, region, city = get_location_info("", self.country, None, -106.0, 32.0) 102 | self.assertEqual(country, self.country) 103 | self.assertIsNone(region) 104 | self.assertIsNone(city) 105 | -------------------------------------------------------------------------------- /docs/Makefile: -------------------------------------------------------------------------------- 1 | # Makefile for Sphinx documentation 2 | # 3 | 4 | # You can set these variables from the command line. 5 | SPHINXOPTS = 6 | SPHINXBUILD = sphinx-build 7 | PAPER = 8 | BUILDDIR = _build 9 | 10 | # User-friendly check for sphinx-build 11 | ifeq ($(shell which $(SPHINXBUILD) >/dev/null 2>&1; echo $$?), 1) 12 | $(error The '$(SPHINXBUILD)' command was not found. Make sure you have Sphinx installed, then set the SPHINXBUILD environment variable to point to the full path of the '$(SPHINXBUILD)' executable. Alternatively you can add the directory with the executable to your PATH. If you don't have Sphinx installed, grab it from http://sphinx-doc.org/) 13 | endif 14 | 15 | # Internal variables. 16 | PAPEROPT_a4 = -D latex_paper_size=a4 17 | PAPEROPT_letter = -D latex_paper_size=letter 18 | ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . 19 | # the i18n builder cannot share the environment and doctrees with the others 20 | I18NSPHINXOPTS = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . 21 | 22 | .PHONY: help clean html dirhtml singlehtml pickle json htmlhelp qthelp devhelp epub latex latexpdf text man changes linkcheck doctest gettext 23 | 24 | help: 25 | @echo "Please use \`make ' where is one of" 26 | @echo " html to make standalone HTML files" 27 | @echo " dirhtml to make HTML files named index.html in directories" 28 | @echo " singlehtml to make a single large HTML file" 29 | @echo " pickle to make pickle files" 30 | @echo " json to make JSON files" 31 | @echo " htmlhelp to make HTML files and a HTML help project" 32 | @echo " qthelp to make HTML files and a qthelp project" 33 | @echo " devhelp to make HTML files and a Devhelp project" 34 | @echo " epub to make an epub" 35 | @echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter" 36 | @echo " latexpdf to make LaTeX files and run them through pdflatex" 37 | @echo " latexpdfja to make LaTeX files and run them through platex/dvipdfmx" 38 | @echo " text to make text files" 39 | @echo " man to make manual pages" 40 | @echo " texinfo to make Texinfo files" 41 | @echo " info to make Texinfo files and run them through makeinfo" 42 | @echo " gettext to make PO message catalogs" 43 | @echo " changes to make an overview of all changed/added/deprecated items" 44 | @echo " xml to make Docutils-native XML files" 45 | @echo " pseudoxml to make pseudoxml-XML files for display purposes" 46 | @echo " linkcheck to check all external links for integrity" 47 | @echo " doctest to run all doctests embedded in the documentation (if enabled)" 48 | 49 | clean: 50 | rm -rf $(BUILDDIR)/* 51 | 52 | html: 53 | $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html 54 | @echo 55 | @echo "Build finished. The HTML pages are in $(BUILDDIR)/html." 56 | 57 | dirhtml: 58 | $(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml 59 | @echo 60 | @echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml." 61 | 62 | singlehtml: 63 | $(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml 64 | @echo 65 | @echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml." 66 | 67 | pickle: 68 | $(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle 69 | @echo 70 | @echo "Build finished; now you can process the pickle files." 71 | 72 | json: 73 | $(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json 74 | @echo 75 | @echo "Build finished; now you can process the JSON files." 76 | 77 | htmlhelp: 78 | $(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp 79 | @echo 80 | @echo "Build finished; now you can run HTML Help Workshop with the" \ 81 | ".hhp project file in $(BUILDDIR)/htmlhelp." 82 | 83 | qthelp: 84 | $(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp 85 | @echo 86 | @echo "Build finished; now you can run "qcollectiongenerator" with the" \ 87 | ".qhcp project file in $(BUILDDIR)/qthelp, like this:" 88 | @echo "# qcollectiongenerator $(BUILDDIR)/qthelp/complexity.qhcp" 89 | @echo "To view the help file:" 90 | @echo "# assistant -collectionFile $(BUILDDIR)/qthelp/complexity.qhc" 91 | 92 | devhelp: 93 | $(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp 94 | @echo 95 | @echo "Build finished." 96 | @echo "To view the help file:" 97 | @echo "# mkdir -p $$HOME/.local/share/devhelp/complexity" 98 | @echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/complexity" 99 | @echo "# devhelp" 100 | 101 | epub: 102 | $(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub 103 | @echo 104 | @echo "Build finished. The epub file is in $(BUILDDIR)/epub." 105 | 106 | latex: 107 | $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex 108 | @echo 109 | @echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex." 110 | @echo "Run \`make' in that directory to run these through (pdf)latex" \ 111 | "(use \`make latexpdf' here to do that automatically)." 112 | 113 | latexpdf: 114 | $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex 115 | @echo "Running LaTeX files through pdflatex..." 116 | $(MAKE) -C $(BUILDDIR)/latex all-pdf 117 | @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." 118 | 119 | latexpdfja: 120 | $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex 121 | @echo "Running LaTeX files through platex and dvipdfmx..." 122 | $(MAKE) -C $(BUILDDIR)/latex all-pdf-ja 123 | @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." 124 | 125 | text: 126 | $(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text 127 | @echo 128 | @echo "Build finished. The text files are in $(BUILDDIR)/text." 129 | 130 | man: 131 | $(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man 132 | @echo 133 | @echo "Build finished. The manual pages are in $(BUILDDIR)/man." 134 | 135 | texinfo: 136 | $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo 137 | @echo 138 | @echo "Build finished. The Texinfo files are in $(BUILDDIR)/texinfo." 139 | @echo "Run \`make' in that directory to run these through makeinfo" \ 140 | "(use \`make info' here to do that automatically)." 141 | 142 | info: 143 | $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo 144 | @echo "Running Texinfo files through makeinfo..." 145 | make -C $(BUILDDIR)/texinfo info 146 | @echo "makeinfo finished; the Info files are in $(BUILDDIR)/texinfo." 147 | 148 | gettext: 149 | $(SPHINXBUILD) -b gettext $(I18NSPHINXOPTS) $(BUILDDIR)/locale 150 | @echo 151 | @echo "Build finished. The message catalogs are in $(BUILDDIR)/locale." 152 | 153 | changes: 154 | $(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes 155 | @echo 156 | @echo "The overview file is in $(BUILDDIR)/changes." 157 | 158 | linkcheck: 159 | $(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck 160 | @echo 161 | @echo "Link check complete; look for any errors in the above output " \ 162 | "or in $(BUILDDIR)/linkcheck/output.txt." 163 | 164 | doctest: 165 | $(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest 166 | @echo "Testing of doctests in the sources finished, look at the " \ 167 | "results in $(BUILDDIR)/doctest/output.txt." 168 | 169 | xml: 170 | $(SPHINXBUILD) -b xml $(ALLSPHINXOPTS) $(BUILDDIR)/xml 171 | @echo 172 | @echo "Build finished. The XML files are in $(BUILDDIR)/xml." 173 | 174 | pseudoxml: 175 | $(SPHINXBUILD) -b pseudoxml $(ALLSPHINXOPTS) $(BUILDDIR)/pseudoxml 176 | @echo 177 | @echo "Build finished. The pseudo-XML files are in $(BUILDDIR)/pseudoxml." 178 | -------------------------------------------------------------------------------- /docs/make.bat: -------------------------------------------------------------------------------- 1 | @ECHO OFF 2 | 3 | REM Command file for Sphinx documentation 4 | 5 | if "%SPHINXBUILD%" == "" ( 6 | set SPHINXBUILD=sphinx-build 7 | ) 8 | set BUILDDIR=_build 9 | set ALLSPHINXOPTS=-d %BUILDDIR%/doctrees %SPHINXOPTS% . 10 | set I18NSPHINXOPTS=%SPHINXOPTS% . 11 | if NOT "%PAPER%" == "" ( 12 | set ALLSPHINXOPTS=-D latex_paper_size=%PAPER% %ALLSPHINXOPTS% 13 | set I18NSPHINXOPTS=-D latex_paper_size=%PAPER% %I18NSPHINXOPTS% 14 | ) 15 | 16 | if "%1" == "" goto help 17 | 18 | if "%1" == "help" ( 19 | :help 20 | echo.Please use `make ^` where ^ is one of 21 | echo. html to make standalone HTML files 22 | echo. dirhtml to make HTML files named index.html in directories 23 | echo. singlehtml to make a single large HTML file 24 | echo. pickle to make pickle files 25 | echo. json to make JSON files 26 | echo. htmlhelp to make HTML files and a HTML help project 27 | echo. qthelp to make HTML files and a qthelp project 28 | echo. devhelp to make HTML files and a Devhelp project 29 | echo. epub to make an epub 30 | echo. latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter 31 | echo. text to make text files 32 | echo. man to make manual pages 33 | echo. texinfo to make Texinfo files 34 | echo. gettext to make PO message catalogs 35 | echo. changes to make an overview over all changed/added/deprecated items 36 | echo. xml to make Docutils-native XML files 37 | echo. pseudoxml to make pseudoxml-XML files for display purposes 38 | echo. linkcheck to check all external links for integrity 39 | echo. doctest to run all doctests embedded in the documentation if enabled 40 | goto end 41 | ) 42 | 43 | if "%1" == "clean" ( 44 | for /d %%i in (%BUILDDIR%\*) do rmdir /q /s %%i 45 | del /q /s %BUILDDIR%\* 46 | goto end 47 | ) 48 | 49 | 50 | %SPHINXBUILD% 2> nul 51 | if errorlevel 9009 ( 52 | echo. 53 | echo.The 'sphinx-build' command was not found. Make sure you have Sphinx 54 | echo.installed, then set the SPHINXBUILD environment variable to point 55 | echo.to the full path of the 'sphinx-build' executable. Alternatively you 56 | echo.may add the Sphinx directory to PATH. 57 | echo. 58 | echo.If you don't have Sphinx installed, grab it from 59 | echo.http://sphinx-doc.org/ 60 | exit /b 1 61 | ) 62 | 63 | if "%1" == "html" ( 64 | %SPHINXBUILD% -b html %ALLSPHINXOPTS% %BUILDDIR%/html 65 | if errorlevel 1 exit /b 1 66 | echo. 67 | echo.Build finished. The HTML pages are in %BUILDDIR%/html. 68 | goto end 69 | ) 70 | 71 | if "%1" == "dirhtml" ( 72 | %SPHINXBUILD% -b dirhtml %ALLSPHINXOPTS% %BUILDDIR%/dirhtml 73 | if errorlevel 1 exit /b 1 74 | echo. 75 | echo.Build finished. The HTML pages are in %BUILDDIR%/dirhtml. 76 | goto end 77 | ) 78 | 79 | if "%1" == "singlehtml" ( 80 | %SPHINXBUILD% -b singlehtml %ALLSPHINXOPTS% %BUILDDIR%/singlehtml 81 | if errorlevel 1 exit /b 1 82 | echo. 83 | echo.Build finished. The HTML pages are in %BUILDDIR%/singlehtml. 84 | goto end 85 | ) 86 | 87 | if "%1" == "pickle" ( 88 | %SPHINXBUILD% -b pickle %ALLSPHINXOPTS% %BUILDDIR%/pickle 89 | if errorlevel 1 exit /b 1 90 | echo. 91 | echo.Build finished; now you can process the pickle files. 92 | goto end 93 | ) 94 | 95 | if "%1" == "json" ( 96 | %SPHINXBUILD% -b json %ALLSPHINXOPTS% %BUILDDIR%/json 97 | if errorlevel 1 exit /b 1 98 | echo. 99 | echo.Build finished; now you can process the JSON files. 100 | goto end 101 | ) 102 | 103 | if "%1" == "htmlhelp" ( 104 | %SPHINXBUILD% -b htmlhelp %ALLSPHINXOPTS% %BUILDDIR%/htmlhelp 105 | if errorlevel 1 exit /b 1 106 | echo. 107 | echo.Build finished; now you can run HTML Help Workshop with the ^ 108 | .hhp project file in %BUILDDIR%/htmlhelp. 109 | goto end 110 | ) 111 | 112 | if "%1" == "qthelp" ( 113 | %SPHINXBUILD% -b qthelp %ALLSPHINXOPTS% %BUILDDIR%/qthelp 114 | if errorlevel 1 exit /b 1 115 | echo. 116 | echo.Build finished; now you can run "qcollectiongenerator" with the ^ 117 | .qhcp project file in %BUILDDIR%/qthelp, like this: 118 | echo.^> qcollectiongenerator %BUILDDIR%\qthelp\complexity.qhcp 119 | echo.To view the help file: 120 | echo.^> assistant -collectionFile %BUILDDIR%\qthelp\complexity.ghc 121 | goto end 122 | ) 123 | 124 | if "%1" == "devhelp" ( 125 | %SPHINXBUILD% -b devhelp %ALLSPHINXOPTS% %BUILDDIR%/devhelp 126 | if errorlevel 1 exit /b 1 127 | echo. 128 | echo.Build finished. 129 | goto end 130 | ) 131 | 132 | if "%1" == "epub" ( 133 | %SPHINXBUILD% -b epub %ALLSPHINXOPTS% %BUILDDIR%/epub 134 | if errorlevel 1 exit /b 1 135 | echo. 136 | echo.Build finished. The epub file is in %BUILDDIR%/epub. 137 | goto end 138 | ) 139 | 140 | if "%1" == "latex" ( 141 | %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex 142 | if errorlevel 1 exit /b 1 143 | echo. 144 | echo.Build finished; the LaTeX files are in %BUILDDIR%/latex. 145 | goto end 146 | ) 147 | 148 | if "%1" == "latexpdf" ( 149 | %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex 150 | cd %BUILDDIR%/latex 151 | make all-pdf 152 | cd %BUILDDIR%/.. 153 | echo. 154 | echo.Build finished; the PDF files are in %BUILDDIR%/latex. 155 | goto end 156 | ) 157 | 158 | if "%1" == "latexpdfja" ( 159 | %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex 160 | cd %BUILDDIR%/latex 161 | make all-pdf-ja 162 | cd %BUILDDIR%/.. 163 | echo. 164 | echo.Build finished; the PDF files are in %BUILDDIR%/latex. 165 | goto end 166 | ) 167 | 168 | if "%1" == "text" ( 169 | %SPHINXBUILD% -b text %ALLSPHINXOPTS% %BUILDDIR%/text 170 | if errorlevel 1 exit /b 1 171 | echo. 172 | echo.Build finished. The text files are in %BUILDDIR%/text. 173 | goto end 174 | ) 175 | 176 | if "%1" == "man" ( 177 | %SPHINXBUILD% -b man %ALLSPHINXOPTS% %BUILDDIR%/man 178 | if errorlevel 1 exit /b 1 179 | echo. 180 | echo.Build finished. The manual pages are in %BUILDDIR%/man. 181 | goto end 182 | ) 183 | 184 | if "%1" == "texinfo" ( 185 | %SPHINXBUILD% -b texinfo %ALLSPHINXOPTS% %BUILDDIR%/texinfo 186 | if errorlevel 1 exit /b 1 187 | echo. 188 | echo.Build finished. The Texinfo files are in %BUILDDIR%/texinfo. 189 | goto end 190 | ) 191 | 192 | if "%1" == "gettext" ( 193 | %SPHINXBUILD% -b gettext %I18NSPHINXOPTS% %BUILDDIR%/locale 194 | if errorlevel 1 exit /b 1 195 | echo. 196 | echo.Build finished. The message catalogs are in %BUILDDIR%/locale. 197 | goto end 198 | ) 199 | 200 | if "%1" == "changes" ( 201 | %SPHINXBUILD% -b changes %ALLSPHINXOPTS% %BUILDDIR%/changes 202 | if errorlevel 1 exit /b 1 203 | echo. 204 | echo.The overview file is in %BUILDDIR%/changes. 205 | goto end 206 | ) 207 | 208 | if "%1" == "linkcheck" ( 209 | %SPHINXBUILD% -b linkcheck %ALLSPHINXOPTS% %BUILDDIR%/linkcheck 210 | if errorlevel 1 exit /b 1 211 | echo. 212 | echo.Link check complete; look for any errors in the above output ^ 213 | or in %BUILDDIR%/linkcheck/output.txt. 214 | goto end 215 | ) 216 | 217 | if "%1" == "doctest" ( 218 | %SPHINXBUILD% -b doctest %ALLSPHINXOPTS% %BUILDDIR%/doctest 219 | if errorlevel 1 exit /b 1 220 | echo. 221 | echo.Testing of doctests in the sources finished, look at the ^ 222 | results in %BUILDDIR%/doctest/output.txt. 223 | goto end 224 | ) 225 | 226 | if "%1" == "xml" ( 227 | %SPHINXBUILD% -b xml %ALLSPHINXOPTS% %BUILDDIR%/xml 228 | if errorlevel 1 exit /b 1 229 | echo. 230 | echo.Build finished. The XML files are in %BUILDDIR%/xml. 231 | goto end 232 | ) 233 | 234 | if "%1" == "pseudoxml" ( 235 | %SPHINXBUILD% -b pseudoxml %ALLSPHINXOPTS% %BUILDDIR%/pseudoxml 236 | if errorlevel 1 exit /b 1 237 | echo. 238 | echo.Build finished. The pseudo-XML files are in %BUILDDIR%/pseudoxml. 239 | goto end 240 | ) 241 | 242 | :end 243 | -------------------------------------------------------------------------------- /docs/conf.py: -------------------------------------------------------------------------------- 1 | # 2 | # complexity documentation build configuration file, created by 3 | # sphinx-quickstart on Tue Jul 9 22:26:36 2013. 4 | # 5 | # This file is execfile()d with the current directory set to its containing dir. 6 | # 7 | # Note that not all possible configuration values are present in this 8 | # autogenerated file. 9 | # 10 | # All configuration values have a default; values that are commented out 11 | # serve to show the default. 12 | 13 | import os 14 | import sys 15 | 16 | # If extensions (or modules to document with autodoc) are in another directory, 17 | # add these directories to sys.path here. If the directory is relative to the 18 | # documentation root, use os.path.abspath to make it absolute, like shown here. 19 | # sys.path.insert(0, os.path.abspath('.')) 20 | 21 | cwd = os.getcwd() 22 | parent = os.path.dirname(cwd) 23 | sys.path.append(parent) 24 | 25 | # -- General configuration ----------------------------------------------------- 26 | 27 | # If your documentation needs a minimal Sphinx version, state it here. 28 | # needs_sphinx = '1.0' 29 | 30 | # Add any Sphinx extension module names here, as strings. They can be extensions 31 | # coming with Sphinx (named 'sphinx.ext.*') or your custom ones. 32 | extensions = ["sphinx.ext.autodoc", "sphinx.ext.viewcode"] 33 | 34 | # Add any paths that contain templates here, relative to this directory. 35 | templates_path = ["_templates"] 36 | 37 | # The suffix of source filenames. 38 | source_suffix = ".rst" 39 | 40 | # The encoding of source files. 41 | # source_encoding = 'utf-8-sig' 42 | 43 | # The master toctree document. 44 | master_doc = "index" 45 | 46 | # General information about the project. 47 | project = "django-airports" 48 | copyright = "2018, Antonio Ercole De Luca" 49 | 50 | # The version info for the project you're documenting, acts as replacement for 51 | # |version| and |release|, also used in various other places throughout the 52 | # built documents. 53 | # 54 | # The short X.Y version. 55 | version = "1.0" 56 | # The full version, including alpha/beta/rc tags. 57 | release = "1.0.3" 58 | 59 | # The language for content autogenerated by Sphinx. Refer to documentation 60 | # for a list of supported languages. 61 | # language = None 62 | 63 | # There are two options for replacing |today|: either, you set today to some 64 | # non-false value, then it is used: 65 | # today = '' 66 | # Else, today_fmt is used as the format for a strftime call. 67 | # today_fmt = '%B %d, %Y' 68 | 69 | # List of patterns, relative to source directory, that match files and 70 | # directories to ignore when looking for source files. 71 | exclude_patterns = ["_build"] 72 | 73 | # The reST default role (used for this markup: `text`) to use for all documents. 74 | # default_role = None 75 | 76 | # If true, '()' will be appended to :func: etc. cross-reference text. 77 | # add_function_parentheses = True 78 | 79 | # If true, the current module name will be prepended to all description 80 | # unit titles (such as .. function::). 81 | # add_module_names = True 82 | 83 | # If true, sectionauthor and moduleauthor directives will be shown in the 84 | # output. They are ignored by default. 85 | # show_authors = False 86 | 87 | # The name of the Pygments (syntax highlighting) style to use. 88 | pygments_style = "sphinx" 89 | 90 | # A list of ignored prefixes for module index sorting. 91 | # modindex_common_prefix = [] 92 | 93 | # If true, keep warnings as "system message" paragraphs in the built documents. 94 | # keep_warnings = False 95 | 96 | 97 | # -- Options for HTML output --------------------------------------------------- 98 | 99 | # The theme to use for HTML and HTML Help pages. See the documentation for 100 | # a list of builtin themes. 101 | html_theme = "default" 102 | 103 | # Theme options are theme-specific and customize the look and feel of a theme 104 | # further. For a list of options available for each theme, see the 105 | # documentation. 106 | # html_theme_options = {} 107 | 108 | # Add any paths that contain custom themes here, relative to this directory. 109 | # html_theme_path = [] 110 | 111 | # The name for this set of Sphinx documents. If None, it defaults to 112 | # " v documentation". 113 | # html_title = None 114 | 115 | # A shorter title for the navigation bar. Default is the same as html_title. 116 | # html_short_title = None 117 | 118 | # The name of an image file (relative to this directory) to place at the top 119 | # of the sidebar. 120 | # html_logo = None 121 | 122 | # The name of an image file (within the static path) to use as favicon of the 123 | # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 124 | # pixels large. 125 | # html_favicon = None 126 | 127 | # Add any paths that contain custom static files (such as style sheets) here, 128 | # relative to this directory. They are copied after the builtin static files, 129 | # so a file named "default.css" will overwrite the builtin "default.css". 130 | html_static_path = ["_static"] 131 | 132 | # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, 133 | # using the given strftime format. 134 | # html_last_updated_fmt = '%b %d, %Y' 135 | 136 | # If true, SmartyPants will be used to convert quotes and dashes to 137 | # typographically correct entities. 138 | # html_use_smartypants = True 139 | 140 | # Custom sidebar templates, maps document names to template names. 141 | # html_sidebars = {} 142 | 143 | # Additional templates that should be rendered to pages, maps page names to 144 | # template names. 145 | # html_additional_pages = {} 146 | 147 | # If false, no module index is generated. 148 | # html_domain_indices = True 149 | 150 | # If false, no index is generated. 151 | # html_use_index = True 152 | 153 | # If true, the index is split into individual pages for each letter. 154 | # html_split_index = False 155 | 156 | # If true, links to the reST sources are added to the pages. 157 | # html_show_sourcelink = True 158 | 159 | # If true, "Created using Sphinx" is shown in the HTML footer. Default is True. 160 | # html_show_sphinx = True 161 | 162 | # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. 163 | # html_show_copyright = True 164 | 165 | # If true, an OpenSearch description file will be output, and all pages will 166 | # contain a tag referring to it. The value of this option must be the 167 | # base URL from which the finished HTML is served. 168 | # html_use_opensearch = '' 169 | 170 | # This is the file name suffix for HTML files (e.g. ".xhtml"). 171 | # html_file_suffix = None 172 | 173 | # Output file base name for HTML help builder. 174 | htmlhelp_basename = "django-airportsdoc" 175 | 176 | 177 | # -- Options for LaTeX output -------------------------------------------------- 178 | 179 | latex_elements = { 180 | # The paper size ('letterpaper' or 'a4paper'). 181 | #'papersize': 'letterpaper', 182 | # The font size ('10pt', '11pt' or '12pt'). 183 | #'pointsize': '10pt', 184 | # Additional stuff for the LaTeX preamble. 185 | #'preamble': '', 186 | } 187 | 188 | # Grouping the document tree into LaTeX files. List of tuples 189 | # (source start file, target name, title, author, documentclass [howto/manual]). 190 | latex_documents = [ 191 | ("index", "django-airports.tex", "django-airports Documentation", "Antonio Ercole De Luca", "manual"), 192 | ] 193 | 194 | # The name of an image file (relative to this directory) to place at the top of 195 | # the title page. 196 | # latex_logo = None 197 | 198 | # For "manual" documents, if this is true, then toplevel headings are parts, 199 | # not chapters. 200 | # latex_use_parts = False 201 | 202 | # If true, show page references after internal links. 203 | # latex_show_pagerefs = False 204 | 205 | # If true, show URL addresses after external links. 206 | # latex_show_urls = False 207 | 208 | # Documents to append as an appendix to all manuals. 209 | # latex_appendices = [] 210 | 211 | # If false, no module index is generated. 212 | # latex_domain_indices = True 213 | 214 | 215 | # -- Options for manual page output -------------------------------------------- 216 | 217 | # One entry per manual page. List of tuples 218 | # (source start file, name, description, authors, manual section). 219 | man_pages = [("index", "django-airports", "django-airports Documentation", ["Antonio Ercole De Luca"], 1)] 220 | 221 | # If true, show URL addresses after external links. 222 | # man_show_urls = False 223 | 224 | 225 | # -- Options for Texinfo output ------------------------------------------------ 226 | 227 | # Grouping the document tree into Texinfo files. List of tuples 228 | # (source start file, target name, title, author, 229 | # dir menu entry, description, category) 230 | texinfo_documents = [ 231 | ( 232 | "index", 233 | "django-airports", 234 | "django-airports Documentation", 235 | "Antonio Ercole De Luca", 236 | "django-airports", 237 | "One line description of project.", 238 | "Miscellaneous", 239 | ), 240 | ] 241 | 242 | # Documents to append as an appendix to all manuals. 243 | # texinfo_appendices = [] 244 | 245 | # If false, no module index is generated. 246 | # texinfo_domain_indices = True 247 | 248 | # How to display URL addresses: 'footnote', 'no', or 'inline'. 249 | # texinfo_show_urls = 'footnote' 250 | 251 | # If true, do not generate a @detailmenu in the "Top" node's menu. 252 | # texinfo_no_detailmenu = False 253 | -------------------------------------------------------------------------------- /airports/management/commands/airports.py: -------------------------------------------------------------------------------- 1 | """ 2 | Download airports file from ourairports.org, and import to database. 3 | The airports csv file fieldnames are these: 4 | fieldnames = ( 5 | 'id', 'ident', 'type', 'name', 'latitude_deg', 'longitude_deg', 6 | 'elevation_ft', 'continent', 'iso_country', 'iso_region', 7 | 'municipality', 'scheduled_service', 'gps_code', 'iata_code', 8 | 'local_code', 'home_link', 'wikipedia_link', 'keywords', 9 | ) 10 | 11 | To deal with region codes in different systems we are also downloading 12 | a file that we can use to correllate ISO-3166-2, Fips and GN region (aka 13 | administrative division) codes. 14 | This gives us a pretty good ability to correlate the airport regions with 15 | cities.Region objects. Somewhat annoyingly, the geonames data uses a mix 16 | of ISO-3166-2 and Fips codes. This is mainly a performance gain, since 17 | we can also derive the region from the city that we find using distance 18 | search. 19 | """ 20 | 21 | import csv 22 | import logging 23 | import os 24 | import pprint 25 | import re 26 | import sys 27 | from collections import defaultdict 28 | from optparse import make_option 29 | 30 | import django 31 | import requests 32 | from cities.models import City, Country, Region 33 | from django.contrib.gis.db.models.functions import Distance 34 | from django.contrib.gis.geos import Point 35 | from django.core.management import call_command 36 | from django.core.management.base import BaseCommand, CommandError 37 | from django.db.models import Q 38 | from tqdm import tqdm 39 | 40 | from ...models import Airport 41 | 42 | ENDPOINT_URL = "http://ourairports.com/data/airports.csv" 43 | DIVISIONS_URL = "https://raw.githubusercontent.com/Tigrov/geoname-divisions/master/result/divisions.csv" 44 | 45 | # Maximum distance used to filter out too-distant cities. 46 | MAX_DISTANCE_KM = 200 47 | 48 | APP_DIR = os.path.normpath(os.path.join(os.path.dirname(os.path.realpath(__file__)), "..", "..")) 49 | 50 | logger = logging.getLogger("airports") 51 | 52 | 53 | class Command(BaseCommand): 54 | data_dir = os.path.join(APP_DIR, "data") 55 | 56 | help = "Imports airport data from CSV into DB, complementing it with country/city information" 57 | if django.VERSION < (1, 8): 58 | option_list = BaseCommand.option_list + ( 59 | make_option("--flush", action="store_true", default=False, help="Flush airports data."), 60 | make_option("--force", action="store_true", default=False, help="Force update of existing airports."), 61 | ) 62 | 63 | def add_arguments(self, parser): 64 | parser.add_argument("--flush", action="store_true", default=False, help="Flush airports data.") 65 | parser.add_argument("--force", action="store_true", default=False, help="Force update of existing airports.") 66 | 67 | def handle(self, *args, **options): 68 | logger.info("Checking countries and cities") 69 | if City.objects.all().count() == 0 or Country.objects.all().count() == 0: 70 | call_command("cities", "--import", "country,city,alt_name") 71 | 72 | self.options = options 73 | 74 | if self.options["flush"] is True: 75 | self.flush_airports() 76 | else: 77 | divisions_file = self.download(DIVISIONS_URL, filename="divisions.dat") 78 | with open(divisions_file) as f: 79 | importer = DivisionImporter(stdout=self.stdout, stderr=self.stderr) 80 | self.divisions = importer.get_divisions(f) 81 | 82 | airport_file = self.download(ENDPOINT_URL, filename="airports.dat") 83 | with open(airport_file, encoding="utf-8") as f: 84 | self.stdout.flush() 85 | try: 86 | importer = DataImporter( 87 | divisions=self.divisions, force=self.options["force"], stdout=self.stdout, stderr=self.stderr 88 | ) 89 | except Exception as e: 90 | raise CommandError(f"Can not continue processing: {e}") 91 | 92 | importer.start(f) 93 | 94 | def download(self, url, filename="airports.dat"): 95 | logger.info("Downloading: " + filename) 96 | response = requests.get(url, data={}) 97 | 98 | if response.status_code != 200: 99 | response.raise_for_status() 100 | 101 | # The requests module guesses the encoding, and in this case it 102 | # is guessing wrong, so we force it to utf-8. 103 | response.encoding = "utf-8" 104 | 105 | try: 106 | filepath = os.path.join(self.data_dir, filename) 107 | if not os.path.exists(self.data_dir): 108 | os.makedirs(self.data_dir) 109 | 110 | fobj = open(filepath, "wt") 111 | fobj.write(response.text) 112 | fobj.close() 113 | 114 | return filepath 115 | 116 | except OSError as e: 117 | raise CommandError(f"Can not open file: {e}") 118 | 119 | def flush_airports(self): 120 | logger.info("Flushing airports data") 121 | Airport.objects.all().delete() 122 | 123 | 124 | class DivisionImporter: 125 | def __init__(self, division_file=None, stdout=sys.stdout, stderr=sys.stderr): 126 | self.stdout = stdout 127 | self.stderr = stderr 128 | 129 | def get_divisions(self, f): 130 | division_dict = defaultdict(dict) 131 | dialect = csv.Sniffer().sniff(f.read(1024)) 132 | f.seek(0) 133 | reader = csv.DictReader(f, dialect=dialect) 134 | 135 | for row in tqdm(list(reader), desc="Processing Divisions"): 136 | country_code = row["ISO-3166-1"] 137 | region_code = row["ISO-3166-2"] 138 | fips = row["Fips"] 139 | GN = row["GN"] 140 | division_dict[country_code][region_code] = dict(fips=fips, GN=GN) 141 | 142 | return division_dict 143 | 144 | 145 | class DataImporter: 146 | def __init__(self, divisions=None, force=False, stdout=sys.stdout, stderr=sys.stderr): 147 | self.stdout = stdout 148 | self.stderr = stderr 149 | self.divisions = divisions 150 | self.force = force 151 | 152 | def start(self, f): 153 | regex_delete = re.compile(r"(^delete|deleted|\[DELETE\])", re.IGNORECASE) 154 | regex_ring = re.compile(r"Powerful Magic Ring", re.IGNORECASE) 155 | regex_region = re.compile(r"[-/]") 156 | 157 | dialect = csv.Sniffer().sniff(f.read(1024)) 158 | f.seek(0) 159 | 160 | reader = csv.DictReader(f, dialect=dialect) 161 | 162 | for row in tqdm(list(reader), desc="Importing Airports"): 163 | id = row["id"] 164 | longitude = float(row["longitude_deg"]) 165 | latitude = float(row["latitude_deg"]) 166 | municipality = row["municipality"] or None 167 | row_country_code = row["iso_country"] 168 | country_code, region_code = regex_region.split(row["iso_region"].strip(), 1) 169 | 170 | name = row["name"].strip() or None 171 | type = row["type"].strip() or None 172 | ident = row["ident"].strip() or None 173 | local_code = row["local_code"].strip() or None 174 | iata = row["iata_code"].strip() or None 175 | icao = row["gps_code"].strip() or None 176 | 177 | altitude = row["elevation_ft"].strip() 178 | 179 | # Filter out ones we know we don't need, including SPAM entries. 180 | if ( 181 | (latitude == 0 and longitude == 0) 182 | or 183 | # type == 'closed' or 184 | country_code.startswith("ZZ") 185 | or regex_ring.search(name) 186 | or regex_delete.match(name) 187 | ): 188 | continue 189 | 190 | if not Airport.objects.filter(id=id).exists() or self.force: 191 | try: 192 | country = Country.objects.get(code=country_code) 193 | except Country.DoesNotExist: 194 | # That's bad! But still recoverable by reverse geocoding 195 | logger.error(f"Bad country_code: {row_country_code} == {country_code}") 196 | country = None 197 | 198 | # First try to find region by given region_code. This is a lot faster 199 | # than looking it up based on its coordinates, which is our fallback. 200 | try: 201 | region = Region.objects.get(country=country, code=region_code) 202 | except Region.DoesNotExist: 203 | try: 204 | assert self.divisions 205 | fips_code = self.divisions[country_code][region_code]["fips"] 206 | gn_code = self.divisions[country_code][region_code]["GN"] 207 | regions = Region.objects.filter(Q(country=country) & (Q(code=fips_code) | Q(code=gn_code))) 208 | assert regions.count() == 1 209 | region = regions.first() 210 | except (AssertionError, KeyError, Region.DoesNotExist): 211 | # Unable to parse the region code, but may be able to figure it 212 | # out by using the coordinates. 213 | logger.debug("Bad region_code: {}".format(row["iso_region"])) 214 | region = None 215 | 216 | country, region, city = get_location_info(municipality, country, region, longitude, latitude) 217 | 218 | if city is None: 219 | logger.debug(f"Airport: {name}: Cannot find city: {municipality}.") 220 | 221 | airport = create_airport( 222 | id=id, 223 | altitude=altitude, 224 | city=city, 225 | municipality=municipality, 226 | country=country, 227 | iata=iata, 228 | icao=icao, 229 | ident=ident, 230 | local_code=local_code, 231 | longitude=longitude, 232 | latitude=latitude, 233 | name=name, 234 | region=region, 235 | type=type, 236 | ) 237 | 238 | 239 | def create_airport( 240 | id=None, 241 | type=None, 242 | altitude=None, 243 | name=None, 244 | city=None, 245 | municipality=None, 246 | region=None, 247 | country=None, 248 | iata=None, 249 | icao=None, 250 | ident=None, 251 | local_code=None, 252 | latitude=None, 253 | longitude=None, 254 | ): 255 | 256 | """ 257 | Get or create an Airport. 258 | 259 | :param id: 260 | :param type: 261 | :param longitude: 262 | :param latitude: 263 | :param name: 264 | :param municipality: 265 | :param iata: 266 | :param icao: 267 | :param ident: 268 | :param local_code: 269 | :param altitude: 270 | :param city: 271 | :param region: 272 | :param country: 273 | :return: 274 | """ 275 | 276 | location = Point(longitude, latitude, srid=4326) 277 | 278 | name = name or municipality or getattr(city, "name", "UNKNOWN") 279 | 280 | try: 281 | # Convert altitude to meters 282 | altitude = round(altitude * 0.3048, 2) 283 | except TypeError: 284 | altitude = 0.0 285 | 286 | defaults = dict( 287 | altitude=altitude, 288 | city=city, 289 | municipality=municipality, 290 | country=country, 291 | iata=iata, 292 | icao=icao, 293 | ident=ident, 294 | local_code=local_code, 295 | location=location, 296 | name=name, 297 | region=region, 298 | type=type, 299 | ) 300 | 301 | try: 302 | airport, created = Airport.objects.update_or_create(id=id, defaults=defaults) 303 | if created: 304 | logger.debug(f"Added airport: {airport}") 305 | return airport 306 | 307 | except Exception as e: 308 | logger.error("{}: id={}\n{}".format(e, id, pprint.pformat(defaults))) 309 | 310 | return None 311 | 312 | 313 | def get_location_info(name, country, region, longitude, latitude): 314 | """ 315 | Get location info for an airport given incomplete information. 316 | 317 | :param name: 318 | :param country: 319 | :param region: 320 | :param longitude: 321 | :param latitude: 322 | :return: (country, region, city) 323 | """ 324 | 325 | if country: 326 | if region: 327 | filtered_cities = City.objects.filter(region=region) 328 | else: 329 | filtered_cities = City.objects.filter(country=country) 330 | else: 331 | filtered_cities = City.objects.all() 332 | 333 | qs = filtered_cities.filter(name_std__iexact=name) 334 | if qs.count() == 1: 335 | city = qs.first() 336 | return city.country, city.region, city 337 | 338 | qs = filtered_cities.filter(Q(name__iexact=name) | Q(alt_names__name__iexact=name)) 339 | if qs.count() == 1: 340 | city = qs.first() 341 | return city.country, city.region, city 342 | 343 | # If we didn't find the city by name, return the city in the same country/region 344 | # which is closest to the given lng/lat. 345 | point = Point(longitude, latitude, srid=4326) 346 | 347 | qs = ( 348 | filtered_cities.annotate(distance=Distance("location", point)) 349 | .filter(distance__lte=MAX_DISTANCE_KM * 1000) 350 | .order_by("distance") 351 | ) 352 | 353 | if qs.count() >= 1: 354 | city = qs.first() 355 | return city.country, city.region, city 356 | 357 | return country, region, None 358 | --------------------------------------------------------------------------------