Commit 88056517 authored by Bruno Martin's avatar Bruno Martin
Browse files

django cities api

parent 7da74ee5
from rest_framework.serializers import ModelSerializer
from cities_light.models import City, Region, Country
class CitySerializer(ModelSerializer):
class Meta:
model = City
exclude = ('slug',)
class RegionSerializer(ModelSerializer):
class Meta:
model = Region
exclude = ('slug',)
class CountrySerializer(ModelSerializer):
class Meta:
model = Country
fields = '__all__'
from django.conf.urls import include, url
from rest_framework import routers
from cities_api import views
router = routers.DefaultRouter()
router.register(r'cities', views.CityModelViewSet, base_name='cities-light-api-city')
router.register(r'countries', views.CountryModelViewSet,
base_name='cities-light-api-country')
router.register(r'regions', views.RegionModelViewSet,
base_name='cities-light-api-region')
app_name = 'cities_api'
urlpatterns = [
url(r'^', include(router.urls)),
url(
r'^search/cep/(?P<cep>[0-9]+)/$',
view=views.address_search,
name='address-search'),
url(
r'^autocomplete/city/$',
views.CityAutocomplete.as_view(),
name='city-autocomplete',
),
]
import json
import requests
from dal import autocomplete
from django.conf import settings
from django_filters.rest_framework import DjangoFilterBackend
from rest_framework import viewsets, relations
from cities_light.models import City, Region, Country
from rest_framework.decorators import permission_classes, api_view
from rest_framework.permissions import AllowAny
from rest_framework.response import Response
from .serializers import CountrySerializer, CitySerializer, RegionSerializer
class CitiesLightListModelViewSet(viewsets.ReadOnlyModelViewSet):
def get_queryset(self):
"""
Allows a GET param, 'q', to be used against name_ascii.
"""
queryset = super(CitiesLightListModelViewSet, self).get_queryset()
if self.request.GET.get('q', None):
return queryset.filter(name_ascii__icontains=self.request.GET['q'])
return queryset
class CityAutocomplete(autocomplete.Select2QuerySetView):
def get_queryset(self):
if not self.request.user.is_authenticated():
return City.objects.none()
qs = City.objects.all()
state = self.forwarded.get('state', None)
if state:
qs = qs.filter(region=state)
if self.q:
qs = qs.filter(name__istartswith=self.q)
return qs
class CountryModelViewSet(CitiesLightListModelViewSet):
serializer_class = CountrySerializer
queryset = Country.objects.all()
class RegionModelViewSet(CitiesLightListModelViewSet):
serializer_class = RegionSerializer
queryset = Region.objects.all()
filter_backends = (DjangoFilterBackend,)
filter_fields = ('name',)
def get_queryset(self):
queryset = super(RegionModelViewSet, self).get_queryset()
if self.request.GET.get('uf', None):
return queryset.filter(alternate_names__contains=self.request.GET['uf'])
return queryset
class CityModelViewSet(CitiesLightListModelViewSet):
"""
ListRetrieveView for City.
"""
serializer_class = CitySerializer
queryset = City.objects.all()
filter_backends = (DjangoFilterBackend,)
filter_fields = ('region',)
def get_queryset(self):
"""
Allows a GET param, 'q', to be used against search_names.
"""
queryset = super(CitiesLightListModelViewSet, self).get_queryset()
if self.request.GET.get('q', None):
return queryset.filter(
search_names__icontains=self.request.GET['q'])
return queryset
@api_view(http_method_names=['GET'])
@permission_classes((AllowAny, ))
def address_search(request, cep, *args, **kwargs):
address_req = requests.get(settings.CEP_ABERTO_URL + '/ceps.json?cep=%s' % cep,
headers={'Authorization': 'Token token=%s' % settings.CEP_ABERTO_API_KEY})
try:
return Response(address_req.json(), status=address_req.status_code)
except json.decoder.JSONDecodeError:
return Response(address_req._content, status=address_req.status_code)
......@@ -38,6 +38,9 @@ DJANGO_APPS = [
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.flatpages',
'dal',
'dal_select2',
# Admin
'django.contrib.admin',
]
......
......@@ -18,6 +18,9 @@ urlpatterns = [
# Docs
url(r'^api/docs/', include_docs_urls(title='base_django_project API Docs', public=False)),
# Address utilities
url(r'^api/address/', include('base_django_project.cities_api.urls', namespace='cities')),
# User management
url(r'^api/profile/', include('base_django_project.users.urls', namespace='users')),
url(r'^rest-auth/facebook/$', FacebookLogin.as_view(), name='fb_login'),
......
......@@ -42,7 +42,10 @@ django-filter==2.0.0
djangorestframework==3.9.1
django-rest-auth[with_social]==0.9.3
django-cors-headers==1.2.0
django-cities-light~=3.5
django-autocomplete-light==3.2.10
# libs needed by django-rest-framework api auto documentations
coreapi==2.3.3
......
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment