Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

docs: rewrite single-tenant docs to be pydantic2 first #153

Merged
merged 5 commits into from
Oct 4, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions .flake8
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,8 @@ ignore=
D401
# Type annotation for `self`
TYP101
TYP102 # for cls
# for cls
TYP102
# Missing docstring in __init__
D107
# Missing docstring in public package
Expand Down Expand Up @@ -46,5 +47,4 @@ exclude =
.idea,
__pycache__,
tests/*,
venv,
manage.py
venv
26 changes: 5 additions & 21 deletions .github/workflows/testing.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -9,35 +9,19 @@ jobs:
- uses: actions/checkout@v3
- uses: actions/setup-python@v4
with:
python-version: 3.11
- uses: actions/cache@v3.3.1
with:
path: |
~/.cache/pip
~/.cache/pre-commit
key: ${{ runner.os }}-${{ steps.setup-python.outputs.python-version }}-pip-
restore-keys: |
${{ runner.os }}-${{ steps.setup-python.outputs.python-version }}-pip-
${{ runner.os }}-${{ steps.setup-python.outputs.python-version }}-
python-version: 3.12
- run: python -m pip install pre-commit
- run: pre-commit run --all-files
test:
needs: linting
runs-on: ubuntu-latest
strategy:
fail-fast: false
matrix:
python-version: [ "3.8.17", "3.11.4", "3.12.0-beta.4" ]
fastapi-version: [ "0.68.0", "0.86.0", "0.95.0", "0.100.1"]
pydantic-version: [ "1.10.12", "2.1.1"]
python-version: [ "3.11.4", "3.12.0" ]
fastapi-version: [ "0.103.2"]
pydantic-version: [ "1.10.13", "2.4.2"]
exclude:
# Don't test python 3.12 on old FastAPI versions
- python-version: "3.12.0-beta.4"
fastapi-version: "0.68.0"
- python-version: "3.12.0-beta.4"
fastapi-version: "0.86.0"
- fastapi-version: "0.68.0"
pydantic-version: "2.1.1"
- fastapi-version: "0.86.0"
pydantic-version: "2.1.1"
- fastapi-version: "0.95.0"
Expand Down Expand Up @@ -66,7 +50,7 @@ jobs:
- name: Install package
run: poetry install --no-interaction
- name: Remove pydantic-settings
if: matrix.pydantic-version == '1.10.12'
if: matrix.pydantic-version == '1.10.13'
run: |
source .venv/bin/activate
poetry remove pydantic-settings
Expand Down
26 changes: 12 additions & 14 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
exclude: README.md
repos:
- repo: https://github.com/ambv/black
rev: '22.10.0'
rev: '23.9.1'
hooks:
- id: black
args: ['--quiet']
- repo: https://github.com/pre-commit/pre-commit-hooks
rev: v4.3.0
rev: v4.4.0
hooks:
- id: check-case-conflict
- id: end-of-file-fixer
Expand All @@ -15,24 +15,22 @@ repos:
- id: check-json
- id: check-merge-conflict
- id: detect-private-key
- id: double-quote-string-fixer
- repo: https://github.com/pycqa/flake8
rev: 3.9.2
rev: 6.1.0
hooks:
- id: flake8
additional_dependencies: [
'flake8-bugbear==22.3.23', # Looks for likely bugs and design problems
'flake8-comprehensions==3.8.0', # Looks for unnecessary generator functions that can be converted to list comprehensions
'flake8-deprecated==1.3', # Looks for method deprecations
'flake8-use-fstring==1.3', # Enforces use of f-strings over .format and %s
'flake8-print==4.0.0', # Checks for print statements
'flake8-docstrings==1.6.0', # Verifies that all functions/methods have docstrings
'flake8-type-annotations==0.1.0', # Looks for misconfigured type annotations
'flake8-annotations==2.8.0', # Enforces type annotation
'flake8-bugbear==23.9.16', # Looks for likely bugs and design problems
'flake8-comprehensions==3.14.0', # Looks for unnecessary generator functions that can be converted to list comprehensions
'flake8-deprecated==2.1', # Looks for method deprecations
'flake8-use-fstring==1.4', # Enforces use of f-strings over .format and %s
'flake8-print==5.0.0', # Checks for print statements
'flake8-docstrings==1.7.0', # Verifies that all functions/methods have docstrings
'flake8-annotations==3.0.1', # Enforces type annotation
]
args: ['--enable-extensions=G']
- repo: https://github.com/asottile/pyupgrade
rev: v3.2.1
rev: v3.14.0
hooks:
- id: pyupgrade
args: ["--py36-plus"]
Expand All @@ -41,7 +39,7 @@ repos:
hooks:
- id: isort
- repo: https://github.com/pre-commit/mirrors-mypy
rev: "v0.990"
rev: "v1.5.1"
hooks:
- id: mypy
exclude: "test_*"
Expand Down
66 changes: 27 additions & 39 deletions docs/docs/single-tenant/fastapi_configuration.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -49,16 +49,15 @@ You need to run the application on the configured port in Azure AD for the next
First, add your settings to the application. We'll need these later. The way I've set it up will look for a `.env`-file
to populate your settings, but you can also just set a `default` value directly.

```python {1,5,8-18,20} title="main.py"
from typing import Union

```python {3-4,7-16,18} title="main.py"
import uvicorn
from fastapi import FastAPI
from pydantic import AnyHttpUrl, BaseSettings, Field
from pydantic import AnyHttpUrl, Field
from pydantic_settings import BaseSettings


class Settings(BaseSettings):
BACKEND_CORS_ORIGINS: list[Union[str, AnyHttpUrl]] = ['http://localhost:8000']
BACKEND_CORS_ORIGINS: list[str | AnyHttpUrl] = ['http://localhost:8000']
OPENAPI_CLIENT_ID: str = Field(default='', env='OPENAPI_CLIENT_ID')
APP_CLIENT_ID: str = Field(default='', env='APP_CLIENT_ID')
TENANT_ID: str = Field(default='', env='TENANT_ID')
Expand All @@ -85,17 +84,16 @@ if __name__ == '__main__':

Now, let's configure our `CORS`. Without `CORS` your OpenAPI docs won't work as expected:

```python {5,25-32} title="main.py"
from typing import Union

```python {3,23-30} title="main.py"
import uvicorn
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from pydantic import AnyHttpUrl, BaseSettings, Field
from pydantic import AnyHttpUrl, Field
from pydantic_settings import BaseSettings


class Settings(BaseSettings):
BACKEND_CORS_ORIGINS: list[Union[str, AnyHttpUrl]] = ['http://localhost:8000']
BACKEND_CORS_ORIGINS: list[str | AnyHttpUrl] = ['http://localhost:8000']
OPENAPI_CLIENT_ID: str = Field(default='', env='OPENAPI_CLIENT_ID')
APP_CLIENT_ID: str = Field(default='', env='APP_CLIENT_ID')
TENANT_ID: str = Field(default='', env='TENANT_ID')
Expand All @@ -118,7 +116,6 @@ if settings.BACKEND_CORS_ORIGINS:
allow_headers=['*'],
)


@app.get("/")
async def root():
return {"message": "Hello World"}
Expand All @@ -131,17 +128,16 @@ if __name__ == '__main__':
## Configure OpenAPI Documentation
In order for our OpenAPI documentation to work, we have to configure a few settings directly in the `FastAPI` application.

```python {23-29} title="main.py"
from typing import Union

```python {21-27} title="main.py"
import uvicorn
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from pydantic import AnyHttpUrl, BaseSettings, Field
from pydantic import AnyHttpUrl, Field
from pydantic_settings import BaseSettings


class Settings(BaseSettings):
BACKEND_CORS_ORIGINS: list[Union[str, AnyHttpUrl]] = ['http://localhost:8000']
BACKEND_CORS_ORIGINS: list[str | AnyHttpUrl] = ['http://localhost:8000']
OPENAPI_CLIENT_ID: str = Field(default='', env='OPENAPI_CLIENT_ID')
APP_CLIENT_ID: str = Field(default='', env='APP_CLIENT_ID')
TENANT_ID: str = Field(default='', env='TENANT_ID')
Expand Down Expand Up @@ -170,7 +166,6 @@ if settings.BACKEND_CORS_ORIGINS:
allow_headers=['*'],
)


@app.get("/")
async def root():
return {"message": "Hello World"}
Expand All @@ -193,19 +188,17 @@ Now, the fun part begins! 🚀
Import the `SingleTenantAzureAuthorizationCodeBearer` from `fastapi_azure_auth` and configure it:


```python {7,42-48} title="main.py"
from typing import Union

```python {4,40-46} title="main.py"
import uvicorn
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from pydantic import AnyHttpUrl, BaseSettings, Field
from fastapi_azure_auth import SingleTenantAzureAuthorizationCodeBearer

from pydantic import AnyHttpUrl, Field
from pydantic_settings import BaseSettings


class Settings(BaseSettings):
BACKEND_CORS_ORIGINS: list[Union[str, AnyHttpUrl]] = ['http://localhost:8000']
BACKEND_CORS_ORIGINS: list[str | AnyHttpUrl] = ['http://localhost:8000']
OPENAPI_CLIENT_ID: str = Field(default='', env='OPENAPI_CLIENT_ID')
APP_CLIENT_ID: str = Field(default='', env='APP_CLIENT_ID')
TENANT_ID: str = Field(default='', env='TENANT_ID')
Expand Down Expand Up @@ -234,6 +227,7 @@ if settings.BACKEND_CORS_ORIGINS:
allow_headers=['*'],
)


azure_scheme = SingleTenantAzureAuthorizationCodeBearer(
app_client_id=settings.APP_CLIENT_ID,
tenant_id=settings.TENANT_ID,
Expand Down Expand Up @@ -262,19 +256,17 @@ the first user authenticates. This isn't required, but makes things a bit quicke
configuration will be considered out of date, and update when a user does a request. You can use
[background tasks](https://fastapi.tiangolo.com/tutorial/background-tasks/) to refresh it before that happens if you'd like.

```python {51-56} title="main.py"
from typing import Union

```python {48-53} title="main.py"
import uvicorn
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from pydantic import AnyHttpUrl, BaseSettings, Field
from fastapi_azure_auth import SingleTenantAzureAuthorizationCodeBearer

from pydantic import AnyHttpUrl, Field
from pydantic_settings import BaseSettings


class Settings(BaseSettings):
BACKEND_CORS_ORIGINS: list[Union[str, AnyHttpUrl]] = ['http://localhost:8000']
BACKEND_CORS_ORIGINS: list[str | AnyHttpUrl] = ['http://localhost:8000']
OPENAPI_CLIENT_ID: str = Field(default='', env='OPENAPI_CLIENT_ID')
APP_CLIENT_ID: str = Field(default='', env='APP_CLIENT_ID')
TENANT_ID: str = Field(default='', env='TENANT_ID')
Expand Down Expand Up @@ -303,6 +295,7 @@ if settings.BACKEND_CORS_ORIGINS:
allow_headers=['*'],
)


azure_scheme = SingleTenantAzureAuthorizationCodeBearer(
app_client_id=settings.APP_CLIENT_ID,
tenant_id=settings.TENANT_ID,
Expand All @@ -311,15 +304,13 @@ azure_scheme = SingleTenantAzureAuthorizationCodeBearer(
}
)


@app.on_event('startup')
async def load_config() -> None:
"""
Load OpenID config on startup.
"""
await azure_scheme.openid_config.load_config()


@app.get("/")
async def root():
return {"message": "Hello World"}
Expand All @@ -336,19 +327,17 @@ views based on the scope.

Let's do that:

```python {4,59} title="main.py"
from typing import Union

```python {2,55} title="main.py"
import uvicorn
from fastapi import FastAPI, Security
from fastapi.middleware.cors import CORSMiddleware
from pydantic import AnyHttpUrl, BaseSettings, Field
from fastapi_azure_auth import SingleTenantAzureAuthorizationCodeBearer

from pydantic import AnyHttpUrl, Field
from pydantic_settings import BaseSettings


class Settings(BaseSettings):
BACKEND_CORS_ORIGINS: list[Union[str, AnyHttpUrl]] = ['http://localhost:8000']
BACKEND_CORS_ORIGINS: list[str | AnyHttpUrl] = ['http://localhost:8000']
OPENAPI_CLIENT_ID: str = Field(default='', env='OPENAPI_CLIENT_ID')
APP_CLIENT_ID: str = Field(default='', env='APP_CLIENT_ID')
TENANT_ID: str = Field(default='', env='TENANT_ID')
Expand Down Expand Up @@ -377,6 +366,7 @@ if settings.BACKEND_CORS_ORIGINS:
allow_headers=['*'],
)


azure_scheme = SingleTenantAzureAuthorizationCodeBearer(
app_client_id=settings.APP_CLIENT_ID,
tenant_id=settings.TENANT_ID,
Expand All @@ -385,15 +375,13 @@ azure_scheme = SingleTenantAzureAuthorizationCodeBearer(
}
)


@app.on_event('startup')
async def load_config() -> None:
"""
Load OpenID config on startup.
"""
await azure_scheme.openid_config.load_config()


@app.get("/", dependencies=[Security(azure_scheme)])
async def root():
return {"message": "Hello World"}
Expand Down
Loading