Skip to content

Commit

Permalink
Add a CNAME -> slug API endpoint
Browse files Browse the repository at this point in the history
  • Loading branch information
ericholscher committed Aug 2, 2014
1 parent 7fc4e19 commit 3cada1d
Show file tree
Hide file tree
Showing 3 changed files with 54 additions and 0 deletions.
20 changes: 20 additions & 0 deletions readthedocs/core/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,9 @@
import os
import shutil

from dns import resolver
from urlparse import urlparse

from django.conf import settings

log = logging.getLogger(__name__)
Expand Down Expand Up @@ -123,3 +126,20 @@ def make_latest(project):
verbose_name='latest',
identifier=branch,
)


def clean_url(url):
parsed = urlparse(url)
if parsed.scheme:
scheme, netloc = parsed.scheme, parsed.netloc
elif parsed.netloc:
scheme, netloc = "http", parsed.netloc
else:
scheme, netloc = "http", parsed.path
return netloc

def cname_to_slug(host):
answer = [ans for ans in resolver.query(host, 'CNAME')][0]
domain = answer.target.to_unicode()
slug = domain.split('.')[0]
return slug
1 change: 1 addition & 0 deletions readthedocs/restapi/urls.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
urlpatterns = patterns(
'',
url(r'^', include(router.urls)),
url(r'cname/', 'restapi.views.core_views.cname', name='cname'),
url(r'footer_html/', 'restapi.views.footer_views.footer_html', name='footer_html'),
url(r'quick_search/', 'restapi.views.search_views.quick_search', name='quick_search'),
url(r'index_search/', 'restapi.views.search_views.index_search', name='index_search'),
Expand Down
33 changes: 33 additions & 0 deletions readthedocs/restapi/views/core_views.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
from rest_framework import decorators, permissions, status
from rest_framework.renderers import JSONPRenderer, JSONRenderer, BrowsableAPIRenderer
from rest_framework.response import Response

from core.utils import clean_url, cname_to_slug
from projects.models import Project

@decorators.api_view(['GET'])
@decorators.permission_classes((permissions.AllowAny,))
@decorators.renderer_classes((JSONRenderer, JSONPRenderer, BrowsableAPIRenderer))
def cname(request):
"""
Get the slug that a particular hostname resolves to.
This is useful for debugging your DNS settings,
or for getting the backing project name on Read the Docs for a URL.
Example::
GET https://readthedocs.org/api/v2/cname/?host=docs.python-requests.org
This will return information about ``docs.python-requests.org``
"""
host = request.GET.get('host')
if not host:
return Response({'error': 'host GET arg required'}, status=status.HTTP_400_BAD_REQUEST)
host = clean_url(host)
slug = cname_to_slug(host)
return Response({
'host': host,
'slug': slug,
})


0 comments on commit 3cada1d

Please sign in to comment.