Python django.conf.settings.REST_FRAMEWORK Examples

The following are 8 code examples of django.conf.settings.REST_FRAMEWORK(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module django.conf.settings , or try the search function .
Example #1
Source File: test_api.py    From normandy with Mozilla Public License 2.0 5 votes vote down vote up
def test_apis_makes_a_reasonable_number_of_db_queries(endpoint, Factory, client, settings):
    # Naive versions of this view could easily make several queries
    # per item, which is very slow. Make sure that isn't the case.
    Factory.create_batch(100)
    queries = CaptureQueriesContext(connection)

    with queries:
        res = client.get(endpoint)
        assert res.status_code == 200

    # Pagination naturally makes one query per item in the page. Anything
    # under `page_size * 2` isn't doing any additional queries per recipe.
    page_size = settings.REST_FRAMEWORK["PAGE_SIZE"]

    assert len(queries) < page_size * 2, queries 
Example #2
Source File: test_rrsets.py    From desec-stack with MIT License 5 votes vote down vote up
def test_retrieve_my_rr_sets_filter(self):
        response = self.client.get_rr_sets(self.my_rr_set_domain.name, query='?cursor=')
        self.assertStatus(response, status.HTTP_200_OK)
        expected_number_of_rrsets = min(len(self._test_rr_sets()), settings.REST_FRAMEWORK['PAGE_SIZE'])
        self.assertEqual(len(response.data), expected_number_of_rrsets)

        for subname in self.SUBNAMES:
            response = self.client.get_rr_sets(self.my_rr_set_domain.name, subname=subname)
            self.assertStatus(response, status.HTTP_200_OK)
            self.assertRRSetsCount(response.data, [dict(subname=subname)],
                                   count=len(self._test_rr_sets(subname=subname)))

        for type_ in self.ALLOWED_TYPES:
            response = self.client.get_rr_sets(self.my_rr_set_domain.name, type=type_)
            self.assertStatus(response, status.HTTP_200_OK) 
Example #3
Source File: utils.py    From lexpredict-contraxsuite with GNU Affero General Public License v3.0 5 votes vote down vote up
def get_api_module(app_name):
    module_path_str = 'apps.{app_name}.api.{api_version}'.format(
        app_name=app_name,
        api_version=settings.REST_FRAMEWORK['DEFAULT_VERSION']
    )
    return importlib.import_module(module_path_str) 
Example #4
Source File: test_throttles.py    From course-discovery with GNU Affero General Public License v3.0 5 votes vote down vote up
def setUp(self):
        super(RateLimitingExceededTest, self).setUp()

        self.url = reverse('api_docs')
        self.user = UserFactory()
        self.client.login(username=self.user.username, password=USER_PASSWORD)
        self.default_rate_patcher = mock.patch.dict(
            settings.REST_FRAMEWORK['DEFAULT_THROTTLE_RATES'],
            {'user': '10/hour'}
        )
        self.default_rate_patcher.start() 
Example #5
Source File: test_settings.py    From richie with MIT License 5 votes vote down vote up
def test_configuration_restframework_htaccess(self, _mock_list):
        """The search API endpoint should work behind an htaccess."""
        # First, check that API calls were broken with the default DRF configuration
        # What was happening is that DRF defines Basic Authentication as a fallback by default
        # and our query has a basic auth header with the username and password of the htaccess
        # defined in nginx. Django was trying to authenticate a user with these credentials,
        # which of course failed.
        with override_settings(
            REST_FRAMEWORK={
                **settings.REST_FRAMEWORK,
                "DEFAULT_AUTHENTICATION_CLASSES": DEFAULTS[
                    "DEFAULT_AUTHENTICATION_CLASSES"
                ],
            }
        ):
            authentication_classes = api_settings.DEFAULT_AUTHENTICATION_CLASSES

        # The authentication classes are loaded before settings are overriden so we need
        # to mock them on the APIView
        with mock.patch(
            "rest_framework.views.APIView.authentication_classes",
            new_callable=mock.PropertyMock,
            return_value=authentication_classes,
        ):
            response = self.client.get(
                "/api/v1.0/courses/",
                HTTP_AUTHORIZATION="Basic dXNlcm5hbWU6cGFzc3dvcmQ=",
            )
        self.assertEqual(response.status_code, 403)

        # Check that the project configuration solves it
        response = self.client.get(
            "/api/v1.0/courses/", HTTP_AUTHORIZATION="Basic dXNlcm5hbWU6cGFzc3dvcmQ="
        )
        self.assertEqual(response.status_code, 200) 
Example #6
Source File: adapters.py    From drf-schema-adapter with MIT License 5 votes vote down vote up
def get_metadata_from_viewset(self, viewset):

        if isinstance(viewset, dict):
            output = viewset
        else:
            MetadataClass = import_string(django_settings.REST_FRAMEWORK['DEFAULT_METADATA_CLASS'])
            output = MetadataClass().determine_metadata(None, viewset)

        return output 
Example #7
Source File: adapters.py    From drf-schema-adapter with MIT License 5 votes vote down vote up
def rebuild_index(self):
        MetadataClass = import_string(django_settings.REST_FRAMEWORK['DEFAULT_METADATA_CLASS'])
        context = {}
        directory = os.path.join(django_settings.BASE_DIR, settings.FRONT_APPLICATION_PATH,
                                 'app', 'data')
        context['items'] = self.walk_dir(directory, True)
        context['root_metadata'] = self.render(
            MetadataClass().determine_metadata(None, 'APIRootView')
        ).decode('utf-8')
        self.write_file(context, directory, 'index.js', self.index_template_name, True) 
Example #8
Source File: test_rrsets.py    From desec-stack with MIT License 4 votes vote down vote up
def test_retrieve_my_rr_sets_pagination(self):
        def convert_links(links):
            mapping = {}
            for link in links.split(', '):
                _url, label = link.split('; ')
                label = re.search('rel="(.*)"', label).group(1)
                _url = _url[1:-1]
                assert label not in mapping
                mapping[label] = _url
            return mapping

        def assertPaginationResponse(response, expected_length, expected_directional_links=[]):
            self.assertStatus(response, status.HTTP_200_OK)
            self.assertEqual(len(response.data), expected_length)

            _links = convert_links(response['Link'])
            self.assertEqual(len(_links), len(expected_directional_links) + 1)  # directional links, plus "first"
            self.assertTrue(_links['first'].endswith('/?cursor='))
            for directional_link in expected_directional_links:
                self.assertEqual(_links['first'].find('/?cursor='), _links[directional_link].find('/?cursor='))
                self.assertTrue(len(_links[directional_link]) > len(_links['first']))

        # Prepare extra records so that we get three pages (total: n + 1)
        n = int(settings.REST_FRAMEWORK['PAGE_SIZE'] * 2.5)
        RRset.objects.bulk_create(
            [RRset(domain=self.my_domain, subname=str(i), ttl=123, type='A') for i in range(n)]
        )

        # No pagination
        response = self.client.get_rr_sets(self.my_domain.name)
        self.assertStatus(response, status.HTTP_400_BAD_REQUEST)
        self.assertEqual(response.data['detail'],
                         f'Pagination required. You can query up to {settings.REST_FRAMEWORK["PAGE_SIZE"]} items at a time ({n+1} total). '
                         'Please use the `first` page link (see Link header).')
        links = convert_links(response['Link'])
        self.assertEqual(len(links), 1)
        self.assertTrue(links['first'].endswith('/?cursor='))

        # First page
        url = links['first']
        response = self.client.get(url)
        assertPaginationResponse(response, settings.REST_FRAMEWORK['PAGE_SIZE'], ['next'])

        # Next
        url = convert_links(response['Link'])['next']
        response = self.client.get(url)
        assertPaginationResponse(response, settings.REST_FRAMEWORK['PAGE_SIZE'], ['next', 'prev'])
        data_next = response.data.copy()

        # Next-next (last) page
        url = convert_links(response['Link'])['next']
        response = self.client.get(url)
        assertPaginationResponse(response, n/5 + 1, ['prev'])

        # Prev
        url = convert_links(response['Link'])['prev']
        response = self.client.get(url)
        assertPaginationResponse(response, settings.REST_FRAMEWORK['PAGE_SIZE'], ['next', 'prev'])

        # Make sure that one step forward equals two steps forward and one step back
        self.assertEqual(response.data, data_next)