Skip to content

Instantly share code, notes, and snippets.

View dmontagu's full-sized avatar

David Montague dmontagu

  • Pydantic
  • Bozeman, MT
View GitHub Profile
from pydantic_core import from_json

partial_json_data = '["aa", "bb", "c'  # (1)!

try:
    result = from_json(partial_json_data, allow_partial=False)
except ValueError as e:
    print(e)  # (2)!
 #> EOF while parsing a string at line 1 column 15
from fastapi import APIRouter
router = APIRouter()
# Change
@router.get(...)
# to
@router.api_route(methods=['GET', 'OPTIONS'], ...)
@dmontagu
dmontagu / day18.py
Last active December 18, 2020 05:55
import re
from pathlib import Path
from typing import Any, Dict, Type
class Part1Number(int):
def __add__(self, other: "Part1Number") -> "Part1Number":
return Part1Number(super().__add__(other))
def __sub__(self, other: "Part1Number") -> "Part1Number":
@dmontagu
dmontagu / bootstrap-new-mac.sh
Created August 10, 2020 08:23
Bootstrap a new mac
#!/usr/bin/env bash
# This bootstraps installing ssh-keys to github
# set colors
if tput setaf 1 &> /dev/null; then
tput sgr0
if [[ $(tput colors) -ge 256 ]] 2>/dev/null; then
ORANGE="$(tput setaf 172)"
else
@dmontagu
dmontagu / app.py
Created February 18, 2020 00:28
FastAPI + dash
# Based on the example from https://www.activestate.com/blog/dash-vs-bokeh/
import dash
import dash_core_components as dcc
import dash_html_components as html
import pandas as pd
import plotly.graph_objs as obj
import uvicorn as uvicorn
from dash.dependencies import Input, Output
from fastapi import FastAPI
from starlette.middleware.wsgi import WSGIMiddleware
@dmontagu
dmontagu / secure_openapi.py
Last active August 16, 2024 07:44
Secure OpenAPI (filter based on available scopes)
from typing import Any, Callable, Dict, List, Sequence, Set
from pydantic.schema import get_model_name_map
from starlette.requests import Request
from starlette.routing import BaseRoute, Route
from fastapi import Depends, FastAPI, routing
from fastapi.encoders import jsonable_encoder
from fastapi.openapi.models import OpenAPI
from fastapi.openapi.utils import get_openapi_path
@dmontagu
dmontagu / __init__.pyi
Created January 27, 2020 22:09
pybind11-wrapped CGAL
from typing import Any, List, Tuple
import numpy as np
ArrayNx2F64 = Any # Actually, should be np.ndarray but mypy doesn't like it
ArrayNx3F64 = Any
ArrayNx3I32 = Any
ArrayNx2I32 = Any
ArrayNI32 = Any
@dmontagu
dmontagu / repeat_every.py
Created December 17, 2019 10:00
Task repeating
import asyncio
import logging
from asyncio import ensure_future
from functools import wraps
from traceback import format_exception
from typing import Any, Callable, Coroutine, Optional, Union
from starlette.concurrency import run_in_threadpool
NoArgsNoReturnFuncT = Callable[[], None]
@dmontagu
dmontagu / mypy.ini
Created November 7, 2019 00:32
Pydantic 0.32.2 mypy plugin
[mypy]
plugins = path/to/pydanticmypy.py:strict
follow_imports = silent
strict_optional = True
warn_redundant_casts = True
warn_unused_ignores = True
disallow_any_generics = True
check_untyped_defs = True
ignore_missing_imports = True
from typing import TYPE_CHECKING, Any, Callable, get_type_hints
from fastapi import APIRouter
class InferringRouter(APIRouter):
if not TYPE_CHECKING:
def add_api_route(self, path: str, endpoint: Callable[..., Any], **kwargs: Any) -> None:
if kwargs.get("response_model") is None: