### Start Django Development Server Source: https://github.com/florimondmanca/djangorestframework-api-key/blob/master/test_project/README.md Starts the Django development server, making the application accessible via a web browser. This is essential for local development and testing the project. ```bash python test_project/manage.py runserver ``` -------------------------------- ### Install djangorestframework-api-key via pip Source: https://github.com/florimondmanca/djangorestframework-api-key/blob/master/docs/guide.md This command installs the `djangorestframework-api-key` library using pip. It is highly recommended to pin the dependency to a specific major version to prevent unexpected breaking changes from future releases. ```bash pip install "djangorestframework-api-key==3.*" ``` -------------------------------- ### Install Project Dependencies Source: https://github.com/florimondmanca/djangorestframework-api-key/blob/master/CONTRIBUTING.md Installs all necessary project dependencies using the `make install` command. This command sets up the development environment for the project. ```Shell make install ``` -------------------------------- ### Serve Documentation Locally Source: https://github.com/florimondmanca/djangorestframework-api-key/blob/master/CONTRIBUTING.md Starts a local server to view the project documentation with hot-reloading capabilities using `make docs-serve`. This is convenient for developing and reviewing documentation changes. ```Shell make docs-serve ``` -------------------------------- ### Example HTTP Authorization Header for Bearer Token API Key Parsing Source: https://github.com/florimondmanca/djangorestframework-api-key/blob/master/docs/guide.md This example illustrates the format of an `Authorization` HTTP header containing an API key prefixed with `Bearer`. This specific format is relevant when customizing `KeyParser` to handle non-default API key extraction patterns in Django REST Framework. ```HTTP Authorization: Bearer ``` -------------------------------- ### Run Django Database Migrations Source: https://github.com/florimondmanca/djangorestframework-api-key/blob/master/test_project/README.md Executes database migrations for the Django project, setting up the necessary database schema. This command typically creates an SQLite database if one doesn't exist. ```bash python test_project/manage.py migrate ``` -------------------------------- ### Install Django REST Framework API Key Source: https://github.com/florimondmanca/djangorestframework-api-key/blob/master/README.md Installs the 'djangorestframework-api-key' library using pip. It is highly recommended to pin the dependency to a specific major version to ensure stability and avoid breaking changes between releases. ```bash pip install "djangorestframework-api-key==3.*" ``` -------------------------------- ### Install Django REST Framework API Key via pip Source: https://github.com/florimondmanca/djangorestframework-api-key/blob/master/docs/index.md Installs the djangorestframework-api-key package using pip. It is highly recommended to pin the dependency to a specific major version (e.g., '3.*') to avoid potential breaking changes in future releases. ```bash pip install "djangorestframework-api-key==3.*" ``` -------------------------------- ### Run Django Migrations for API Key App Source: https://github.com/florimondmanca/djangorestframework-api-key/blob/master/docs/guide.md Execute this bash command to apply the necessary database migrations for `djangorestframework-api-key`. This ensures that all required database tables, such as those for storing API keys, are created or updated correctly. ```bash python manage.py migrate ``` -------------------------------- ### Custom HTTP Header Format for API Key Source: https://github.com/florimondmanca/djangorestframework-api-key/blob/master/docs/guide.md This example shows the format for passing the API key in a custom HTTP header, `X-Api-Key`, as configured by `API_KEY_CUSTOM_HEADER` in Django settings. This allows clients to send the API key via an alternative header. ```HTTP X-Api-Key: ``` -------------------------------- ### Register Custom API Key Model with Django Admin Panel Source: https://github.com/florimondmanca/djangorestframework-api-key/blob/master/docs/guide.md This Python example shows how to integrate a custom API key model, `OrganizationAPIKey`, into the Django administration site. It involves subclassing `APIKeyModelAdmin` and using the `@admin.register` decorator to make the model manageable via the admin interface. ```Python # organizations/admin.py from django.contrib import admin from rest_framework_api_key.admin import APIKeyModelAdmin from .models import OrganizationAPIKey @admin.register(OrganizationAPIKey) class OrganizationAPIKeyModelAdmin(APIKeyModelAdmin): pass ``` -------------------------------- ### Add djangorestframework-api-key to Django INSTALLED_APPS Source: https://github.com/florimondmanca/djangorestframework-api-key/blob/master/docs/guide.md This Python snippet shows how to integrate `djangorestframework-api-key` into a Django project by adding `rest_framework` and `rest_framework_api_key` to the `INSTALLED_APPS` list in your `settings.py` file. This step is crucial for the application to be recognized and used by Django. ```python # settings.py INSTALLED_APPS = [ # ... "rest_framework", "rest_framework_api_key", ] ``` -------------------------------- ### Create API Key with Generated Key Access Source: https://github.com/florimondmanca/djangorestframework-api-key/blob/master/docs/guide.md Shows how to programmatically create an API key and simultaneously obtain access to its generated key using the `APIKey.objects.create_key()` method. This is crucial for providing the key to the client. ```python >>> from rest_framework_api_key.models import APIKey >>> api_key, key = APIKey.objects.create_key(name="my-remote-service") >>> # Proceed with `api_key` and `key`... ``` -------------------------------- ### Create Django Superuser for Admin Access Source: https://github.com/florimondmanca/djangorestframework-api-key/blob/master/test_project/README.md Creates a superuser account for the Django admin site, allowing administrative access. The user will be prompted to enter user information such as username, email, and password. ```bash python test_project/manage.py createsuperuser ``` -------------------------------- ### Generate and Apply Database Migrations for Custom API Key Model Source: https://github.com/florimondmanca/djangorestframework-api-key/blob/master/docs/guide.md Explains the necessary `manage.py` commands to generate and apply database migrations for a newly created custom API key model. This step is crucial for the model to have its own table in the database. ```bash python manage.py makemigrations python manage.py migrate ``` -------------------------------- ### Count Total API Keys Programmatically Source: https://github.com/florimondmanca/djangorestframework-api-key/blob/master/docs/guide.md Demonstrates how to query the total number of API keys using the `APIKey.objects.count()` method in the Django shell. ```python >>> from rest_framework_api_key.models import APIKey >>> APIKey.objects.count() 42 ``` -------------------------------- ### Override API Key Retrieval from Request Source: https://github.com/florimondmanca/djangorestframework-api-key/blob/master/docs/guide.md This example illustrates how to directly override the `get_key()` method within your custom `HasAPIKey` permission class. This method receives the `HttpRequest` object and should return the API key string or `None`, allowing for flexible key retrieval logic, such as fetching from cookies. ```python class HasAPIKey(BaseHasAPIKey): model = APIKey # Or a custom model def get_key(self, request): return request.COOKIES.get("api_key") ``` -------------------------------- ### Apply HasAPIKey Permission to a Specific Django REST Framework View Source: https://github.com/florimondmanca/djangorestframework-api-key/blob/master/docs/guide.md This Python example illustrates how to apply the `HasAPIKey` permission class to an individual Django REST Framework `APIView`. By defining `permission_classes` within the view, you can control access on a per-endpoint basis, allowing for granular security configurations. ```python # views.py from rest_framework.views import APIView from rest_framework_api_key.permissions import HasAPIKey class UserListView(APIView): permission_classes = [HasAPIKey] # ... ``` -------------------------------- ### Customize API Key Model with ForeignKey to Organization Source: https://github.com/florimondmanca/djangorestframework-api-key/blob/master/docs/guide.md Provides an example of extending `AbstractAPIKey` to create a custom API key model (`OrganizationAPIKey`) that links to another Django model (`Organization`) via a `ForeignKey`. This allows storing extra information or associating API keys with specific entities. ```python # organizations/models.py from django.db import models from rest_framework_api_key.models import AbstractAPIKey class Organization(models.Model): name = models.CharField(max_length=128) active = models.BooleanField(default=True) class OrganizationAPIKey(AbstractAPIKey): organization = models.ForeignKey( Organization, on_delete=models.CASCADE, related_name="api_keys", ) ``` -------------------------------- ### Customize Meta Options for AbstractAPIKey Subclass Source: https://github.com/florimondmanca/djangorestframework-api-key/blob/master/docs/guide.md Demonstrates how to customize the `Meta` options for a custom API key model that subclasses `AbstractAPIKey`. It shows inheriting from `AbstractAPIKey.Meta` to set `verbose_name` and `verbose_name_plural`. ```python class OrganizationAPIKey(AbstractAPIKey): # ... class Meta(AbstractAPIKey.Meta): verbose_name = "Organization API key" verbose_name_plural = "Organization API keys" ``` -------------------------------- ### HTTP Authorization Header Format for API Key Source: https://github.com/florimondmanca/djangorestframework-api-key/blob/master/docs/guide.md This snippet illustrates the standard format for including an API key in the `Authorization` HTTP header. Clients must provide their full generated API key prefixed with 'Api-Key' to authenticate requests. ```HTTP Authorization: Api-Key ``` -------------------------------- ### Implement Custom Key Parser Class for Cookies Source: https://github.com/florimondmanca/djangorestframework-api-key/blob/master/docs/guide.md For more complex key parsing algorithms, this snippet shows how to define a dedicated key parser class, such as `CookieKeyParser`. This class must implement a `.get()` method with the same signature as `get_key()`, and is then assigned to the `key_parser` attribute of `HasAPIKey`. ```python class CookieKeyParser: def get(self, request): cookie_name = getattr(settings, "API_KEY_COOKIE_NAME", "api_key") return request.COOKIES.get(cookie_name) class HasAPIKey(BaseHasAPIKey): model = APIKey # Or a custom model key_parser = CookieKeyParser() ``` -------------------------------- ### Customize API Key Parsing with Bearer Token Source: https://github.com/florimondmanca/djangorestframework-api-key/blob/master/docs/guide.md This snippet demonstrates how to implement a custom `KeyParser` to handle API keys transmitted with a 'Bearer' prefix in the Authorization header. It involves subclassing `KeyParser` to define the keyword and then assigning this custom parser to the `key_parser` attribute of `HasAPIKey`. ```python from rest_framework_api_key.models import HasAPIKey from rest_framework_api_key.permissions import BaseHasAPIKey, KeyParser class BearerKeyParser(KeyParser): keyword = "Bearer" class HasAPIKey(BaseHasAPIKey): model = APIKey # Or a custom model key_parser = BearerKeyParser() ``` -------------------------------- ### Set HasAPIKey Permission Globally in Django REST Framework Source: https://github.com/florimondmanca/djangorestframework-api-key/blob/master/docs/guide.md This Python configuration snippet demonstrates how to enforce API key authorization across all Django REST Framework views by setting `HasAPIKey` as a `DEFAULT_PERMISSION_CLASSES` entry in `settings.py`. This provides a project-wide security measure. ```python # settings.py REST_FRAMEWORK = { "DEFAULT_PERMISSION_CLASSES": [ "rest_framework_api_key.permissions.HasAPIKey", ] } ``` -------------------------------- ### Customize API Key Generation Lengths Source: https://github.com/florimondmanca/djangorestframework-api-key/blob/master/docs/guide.md This advanced topic demonstrates how to customize the length of the API key's prefix and secret components. By subclassing `BaseAPIKeyManager` and setting its `key_generator` attribute to a `KeyGenerator` instance with specified `prefix_length` and `secret_key_length`, you can control the generated key format. ```python from rest_framework_api_key.models import BaseAPIKeyManager from rest_framework_api_key.crypto import KeyGenerator class OrganizationAPIKeyManager(BaseAPIKeyManager): key_generator = KeyGenerator(prefix_length=8, secret_key_length=32) # Default values class OrganizationAPIKey(AbstractAPIKey): objects = OrganizationAPIKeyManager() # ... ``` -------------------------------- ### Retrieve APIKey Instance from Request Key in Django REST Framework View Source: https://github.com/florimondmanca/djangorestframework-api-key/blob/master/docs/guide.md Illustrates how to retrieve an `APIKey` instance from an incoming request's API key within a Django REST Framework view. It uses `APIKey.objects.get_from_key()` to find the associated API key object and then a related project. ```python from rest_framework.views import APIView from rest_framework_api_key.models import APIKey from rest_framework_api_key.permissions import HasAPIKey from .models import Project class ProjectListView(APIView): permission_classes = [HasAPIKey] def get(self, request): """Retrieve a project based on the request API key.""" key = request.META["HTTP_AUTHORIZATION"].split()[1] api_key = APIKey.objects.get_from_key(key) project = Project.objects.get(api_key=api_key) ``` -------------------------------- ### Combine HasAPIKey with other Django REST Framework Permissions Source: https://github.com/florimondmanca/djangorestframework-api-key/blob/master/docs/guide.md This Python snippet shows how to compose `HasAPIKey` with other Django REST Framework permission classes, such as `IsAuthenticated`, using bitwise operators. This allows for complex authorization behaviors, like requiring either a valid API key OR user authentication for access. ```python from rest_framework.permissions import IsAuthenticated from rest_framework_api_key.permissions import HasAPIKey # ... permission_classes = [HasAPIKey | IsAuthenticated] ``` -------------------------------- ### Configure Custom API Key Header in Django Settings Source: https://github.com/florimondmanca/djangorestframework-api-key/blob/master/docs/guide.md This Python configuration allows you to specify a custom HTTP header for API key transmission instead of the default `Authorization` header. Setting `API_KEY_CUSTOM_HEADER` in `settings.py` is beneficial when the `Authorization` header is already utilized by another authentication scheme. ```python # settings.py API_KEY_CUSTOM_HEADER = "HTTP_X_API_KEY" ``` -------------------------------- ### Manually Validate API Key using APIKey Manager Source: https://github.com/florimondmanca/djangorestframework-api-key/blob/master/docs/guide.md This Python code demonstrates how to programmatically validate a raw API key string using the `APIKey.objects.is_valid()` method. This functionality is particularly useful for validating API keys in contexts outside of standard Django views, such as within Django Channels WebSocket consumers. ```python from rest_framework_api_key.permissions import APIKey # this should be a string containing only the API key - remove any additional text like "Api-Key" if present raw_key = "XXXXXXXX.XXXXXXXXXX" is_valid_key = APIKey.objects.is_valid(raw_key) ``` -------------------------------- ### Customize Django Admin List Display and Search for API Keys Source: https://github.com/florimondmanca/djangorestframework-api-key/blob/master/docs/guide.md This Python code illustrates how to extend the default `list_display` and `search_fields` attributes within a Django `APIKeyModelAdmin` subclass. It adds the `organization__name` field to both the list view and search functionality, allowing administrators to easily view and find API keys by their associated organization's name while retaining original search behavior. ```Python list_display = [*APIKeyModelAdmin.list_display, "organization__name"] search_fields = [*APIKeyModelAdmin.search_fields, "organization__name"] ``` -------------------------------- ### Filter Usable API Keys by Active Organization in Django Manager Source: https://github.com/florimondmanca/djangorestframework-api-key/blob/master/docs/guide.md This Python snippet demonstrates how to extend `BaseAPIKeyManager` to restrict usable API keys. By overriding `get_usable_keys`, it filters keys associated with active organizations, while still leveraging the parent implementation to exclude revoked keys. This ensures only valid and actively linked API keys are considered. ```Python class OrganizationAPIKeyManager(BaseAPIKeyManager): def get_usable_keys(self): return super().get_usable_keys().filter(organization__active=True) ``` -------------------------------- ### Create Custom Django REST Framework API Key Permission Class Source: https://github.com/florimondmanca/djangorestframework-api-key/blob/master/docs/guide.md This Python snippet demonstrates how to define a custom permission class for Django REST Framework API keys. By subclassing `BaseHasAPIKey` and setting the `.model` attribute to `OrganizationAPIKey`, it enables validation of API keys against a specific custom API key model instead of the default one. ```Python # organizations/permissions.py from rest_framework_api_key.permissions import BaseHasAPIKey from .models import OrganizationAPIKey class HasOrganizationAPIKey(BaseHasAPIKey): model = OrganizationAPIKey ``` -------------------------------- ### Build Project Documentation Source: https://github.com/florimondmanca/djangorestframework-api-key/blob/master/CONTRIBUTING.md Compiles and builds the project's documentation into static files using `make docs`. This command prepares the documentation for deployment or local viewing. ```Shell make docs ``` -------------------------------- ### Deploy Project Documentation Source: https://github.com/florimondmanca/djangorestframework-api-key/blob/master/CONTRIBUTING.md Deploys the project's documentation to its hosting environment using `make docs-deploy`. This command is typically used by maintainers after a new release or significant documentation updates. ```Shell make docs-deploy ``` -------------------------------- ### Run Project Tests Source: https://github.com/florimondmanca/djangorestframework-api-key/blob/master/CONTRIBUTING.md Executes the test suite for the project using the `make test` command. This ensures that all functionalities are working correctly and helps verify changes. ```Shell make test ``` -------------------------------- ### Check Code Style Compliance Source: https://github.com/florimondmanca/djangorestframework-api-key/blob/master/CONTRIBUTING.md Runs checks to verify that the project's code adheres to the defined style guidelines using `make check`. This command identifies any style violations without modifying the code. ```Shell make check ``` -------------------------------- ### Auto-format Code Style Source: https://github.com/florimondmanca/djangorestframework-api-key/blob/master/CONTRIBUTING.md Applies automatic code formatting rules to the project's codebase using `make format`. This helps maintain a consistent code style across the project. ```Shell make format ``` -------------------------------- ### Run database migrations for Django REST Framework API Key Source: https://github.com/florimondmanca/djangorestframework-api-key/blob/master/README.md Executes Django database migrations to create the necessary tables and schema for the 'djangorestframework-api-key' models in your project's database. ```bash python manage.py migrate ``` -------------------------------- ### Add rest_framework_api_key to Django INSTALLED_APPS Source: https://github.com/florimondmanca/djangorestframework-api-key/blob/master/docs/index.md Configures the Django project by adding 'rest_framework' and 'rest_framework_api_key' to the INSTALLED_APPS list in the settings.py file. This step is essential to enable the Django REST Framework and the API key functionalities within your application. ```python # settings.py INSTALLED_APPS = [ # ... "rest_framework", "rest_framework_api_key", ] ``` -------------------------------- ### Run Django Migrations for API Key App Source: https://github.com/florimondmanca/djangorestframework-api-key/blob/master/docs/upgrade/1.0.md After upgrading the `djangorestframework-api-key` package, this command applies the latest database migrations for the application. This step is essential to create or update the database tables according to the new schema defined in version 1.0, completing the upgrade process. ```bash python manage.py migrate rest_framework_api_key ``` -------------------------------- ### Run Django Migrations for API Key Models Source: https://github.com/florimondmanca/djangorestframework-api-key/blob/master/docs/index.md Executes Django database migrations to create or update the necessary database tables and schema for the djangorestframework-api-key models. This command ensures that the API key management system is properly set up in your database. ```bash python manage.py migrate ``` -------------------------------- ### Python Project Dependencies for Django REST Framework API Key Source: https://github.com/florimondmanca/djangorestframework-api-key/blob/master/requirements.txt This snippet lists the required Python packages for the djangorestframework-api-key project. It includes core Django components, database drivers (PostgreSQL), packaging tools (twine, wheel), and development/testing utilities (black, mypy, pytest, ruff). Specific versions are provided to ensure compatibility and reproducibility of the development environment. ```Python -e . # Django environment. # django[argon2,bcrypt] # See tools/install_django.sh djangorestframework==3.14.* dj-database-url django-dotenv # PostgreSQL testing. psycopg2-binary # Packaging. twine wheel # Tooling. black==23.9.1 django-test-migrations==1.3.0 mkdocs==1.5.2 mkdocs-material==9.3.1 pymdown-extensions==10.3 mypy==1.5.1 pytest==7.4.2 pytest-django==4.5.2 pytest-cov ruff==0.0.289 ``` -------------------------------- ### Configure Django REST Framework API Key in settings Source: https://github.com/florimondmanca/djangorestframework-api-key/blob/master/README.md Adds 'rest_framework' and 'rest_framework_api_key' to the INSTALLED_APPS list in your Django settings.py file. This step is necessary to enable the application within your Django project. ```python # settings.py INSTALLED_APPS = [ # ... "rest_framework", "rest_framework_api_key", ] ``` -------------------------------- ### Generate Django Migrations Source: https://github.com/florimondmanca/djangorestframework-api-key/blob/master/CONTRIBUTING.md Updates or generates new Django database migrations for the project using `make migrations`. This is useful when database schema changes occur and helps keep the database in sync. ```Shell make migrations ``` -------------------------------- ### Upgrade djangorestframework-api-key Package Source: https://github.com/florimondmanca/djangorestframework-api-key/blob/master/docs/upgrade/1.0.md This command upgrades the `djangorestframework-api-key` Python package to the latest 1.0.x version using pip. It ensures that your project utilizes the new API key generation and validation scheme introduced in version 1.0, which is a prerequisite for running the new migrations. ```bash pip install "djangorestframework-api-key==1.0.*" ``` -------------------------------- ### Migrate Built-in Django REST Framework API Key Model Source: https://github.com/florimondmanca/djangorestframework-api-key/blob/master/docs/upgrade/1.4.md Applies the database migration provided by the `rest_framework_api_key` package. This migration adds and populates the `prefix` and `hashed_key` fields to the built-in `APIKey` model, which is essential for the 1.4 upgrade. ```bash python manage.py migrate rest_framework_api_key ``` -------------------------------- ### Apply Custom Django REST Framework API Key Model Migration Source: https://github.com/florimondmanca/djangorestframework-api-key/blob/master/docs/upgrade/1.4.md Executes a manually created database migration for a custom API key model that derives from `AbstractAPIKey`. This step is required if you use a custom model and assumes the migration script has been copied to your application's `migrations/` directory. ```bash python manage.py migrate ``` -------------------------------- ### Reset Django Migrations for API Key App Source: https://github.com/florimondmanca/djangorestframework-api-key/blob/master/docs/upgrade/1.0.md This command resets the migrations for the `rest_framework_api_key` Django application to their initial state (zero). This is a critical step before upgrading to a new major version that introduces incompatible schema changes, as it prepares the database for new migrations. Be aware that this action will destroy all existing API keys associated with the application. ```bash python manage.py migrate rest_framework_api_key zero ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.