Skip to content
This repository has been archived by the owner on Jun 3, 2024. It is now read-only.

Commit

Permalink
Add CORS support
Browse files Browse the repository at this point in the history
  • Loading branch information
GuillaumeGomez committed Jul 26, 2019
1 parent bb10d50 commit 25097c2
Show file tree
Hide file tree
Showing 5 changed files with 60 additions and 3 deletions.
15 changes: 15 additions & 0 deletions idunn/api/places.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import logging
from elasticsearch import Elasticsearch
from apistar.exceptions import BadRequest, NotFound
from apistar.http import Response

from idunn import settings
from idunn.utils import prometheus
Expand All @@ -10,6 +11,7 @@
from idunn.api.pages_jaunes import pj_source
from .closest import get_closest_place


logger = logging.getLogger(__name__)


Expand All @@ -20,11 +22,13 @@ def validate_verbosity(verbosity):
})
return verbosity


def validate_lang(lang):
if not lang:
return settings['DEFAULT_LANGUAGE']
return lang.lower()


def get_place(id, es: Elasticsearch, indices: IndexNames, lang=None, type=None, verbosity=DEFAULT_VERBOSITY) -> Place:
"""Main handler that returns the requested place"""
verbosity = validate_verbosity(verbosity)
Expand Down Expand Up @@ -60,3 +64,14 @@ def get_place_latlon(lat: float, lon: float, es: Elasticsearch, lang=None, verbo
closest_place = None
place = Latlon(lat, lon, closest_address=closest_place)
return place.load_place(lang, verbosity)


def handle_option(id, es: Elasticsearch, indices: IndexNames, lang=None, type=None, verbosity=DEFAULT_VERBOSITY):
if settings.get('ENABLE_OPTION_REQUESTS', False) is True:
headers = {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Headers': '*',
'Access-Control-Allow-Methods': 'GET',
}
return Response('', headers=headers)
return Response('', status_code=405)
9 changes: 7 additions & 2 deletions idunn/api/urls.py
Original file line number Diff line number Diff line change
@@ -1,19 +1,23 @@
import os

from apistar import Route
from apistar_prometheus import expose_metrics, expose_metrics_multiprocess

from .pois import get_poi
from .places import get_place, get_place_latlon
from .places import get_place, get_place_latlon, handle_option
from .status import get_status
from .places_list import get_places_bbox, get_events_bbox
from .categories import get_all_categories
from .closest import closest_address


def get_metric_handler(settings):
"""Select the prometheus multiprocess mode or not"""
if settings['PROMETHEUS_MULTIPROC']:
return expose_metrics_multiprocess
return expose_metrics


def get_api_urls(settings):
"""Defines all endpoints
and handlers to build response
Expand All @@ -29,10 +33,11 @@ def get_api_urls(settings):
# Werkzeug syntax is used to allow negative floats
Route('/places/latlon:<float(signed=True):lat>:<float(signed=True):lon>', 'GET', handler=get_place_latlon),
Route('/places/{id}', 'GET', handler=get_place),
Route('/places', 'GET', handler=get_places_bbox),

Route('/categories', 'GET', handler=get_all_categories),

Route('/places', 'GET', handler=get_places_bbox),
Route('/places/{id}', 'OPTIONS', handler=handle_option),

# Werkzeug syntax is used to allow negative floats
Route('/reverse/<float(signed=True):lat>:<float(signed=True):lon>', 'GET', handler=closest_address),
Expand Down
2 changes: 2 additions & 0 deletions idunn/utils/default_settings.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -65,3 +65,5 @@ PJ_ES_QUERY_TEMPLATE: "pagesjaunes_query"

# kuzzle Cluster
KUZZLE_CLUSTER_URL:

ENABLE_OPTION_REQUESTS: False
36 changes: 36 additions & 0 deletions tests/test_api.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
from app import app
from apistar.test import TestClient
import pytest
from .utils import override_settings


def test_basic_query():
client = TestClient(app)
Expand All @@ -22,6 +25,7 @@ def test_basic_query():
assert resp['blocks'][1]['type'] == 'phone'
assert resp['blocks'][0]['is_24_7'] == False


def test_lang():
client = TestClient(app)
response = client.get(
Expand All @@ -42,6 +46,7 @@ def test_lang():
assert resp['blocks'][1]['type'] == 'phone'
assert resp['blocks'][0]['is_24_7'] == False


def test_contact_phone():
"""
The louvre museum has the tag 'contact:phone'
Expand All @@ -66,6 +71,7 @@ def test_contact_phone():
assert resp['blocks'][1]['international_format'] == '+33 1 40 20 52 29'
assert resp['blocks'][1]['local_format'] == '01 40 20 52 29'


def test_block_null():
"""
The query corresponding to POI id 'osm:way:55984117' doesn't contain any 'opening_hour' block (the block is null).
Expand Down Expand Up @@ -101,12 +107,14 @@ def test_unknow_poi():
"message": "poi 'an_unknown_poi_id' not found"
}


def test_schema():
client = TestClient(app)
response = client.get(url='http://localhost/schema')

assert response.status_code == 200 # for the moment we check just that the schema is not empty


def test_services_and_information():
"""
Test that the services_and_information block
Expand Down Expand Up @@ -148,6 +156,7 @@ def test_services_and_information():
}
]


def test_exc_scenario():
"""
A scenario with 2 consecutive requests that used to cause unhandled errors
Expand All @@ -158,3 +167,30 @@ def test_exc_scenario():
assert response.status_code == 400
response = client.get('http://localhost/v1/abcdef')
assert response.status_code == 404


@pytest.fixture(scope="function")
def options_test_with_options():
with override_settings({'ENABLE_OPTION_REQUESTS': True}):
yield


def test_options_requests(options_test_with_options):
client = TestClient(app)
response = client.options(
url=f'http://localhost/v1/places/35460343',
)

assert response.status_code == 200
assert response.headers.get('Access-Control-Allow-Origin') == '*'
assert response.headers.get('Access-Control-Allow-Headers') == '*'
assert response.headers.get('Access-Control-Allow-Methods') == 'GET'


def test_options_requests_disabled():
client = TestClient(app)
response = client.options(
url=f'http://localhost/v1/places/35460343',
)

assert response.status_code == 405
1 change: 0 additions & 1 deletion tests/test_kuzzle.py
Original file line number Diff line number Diff line change
Expand Up @@ -102,4 +102,3 @@ def test_kuzzle_event_nok():


assert response.status_code == 501

0 comments on commit 25097c2

Please sign in to comment.