Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
def test_invalid_dict():
with pytest.raises(AssertionError):
app = FastAPI()
class Item(BaseModel):
title: str
@app.get("/items/")
def read_items(q: Dict[str, Item] = Query(None)):
pass # pragma: no cover
from typing import Optional
from fastapi import FastAPI
from pydantic import BaseModel
from starlette.testclient import TestClient
app = FastAPI()
class SubModel(BaseModel):
a: Optional[str] = "foo"
class Model(BaseModel):
x: Optional[int]
sub: SubModel
class ModelSubclass(Model):
y: int
@app.get("/", response_model=Model, response_model_exclude_unset=True)
from typing import Optional
from fastapi import FastAPI, Security
from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer
from starlette.testclient import TestClient
app = FastAPI()
security = HTTPBearer(auto_error=False)
@app.get("/users/me")
def read_current_user(
credentials: Optional[HTTPAuthorizationCredentials] = Security(security),
):
if credentials is None:
return {"msg": "Create an account first"}
return {"scheme": credentials.scheme, "credentials": credentials.credentials}
client = TestClient(app)
openapi_schema = {
import datetime
import faiss
from fastapi import FastAPI, Query
from utils import load_yaml_config
config = load_yaml_config("./config.yml")
faiss_model_path = config["model"]["faiss_model_path"]
index = faiss.read_index(faiss_model_path)
model_update_time = None
app = FastAPI()
@app.get("/faiss/similar_items/")
async def get_single_item_similar(
spu_id: int = Query(
...,
title="spu_id",
description="item spu id",
gt=0),
n_items: int = Query(
9,
titel="n_items",
description="topN of similar items",
ge=1)
):
tim_str = datetime.datetime.now().strftime("%Y%m%d")
from typing import Optional
from pydantic import BaseModel
from fastapi import Depends, FastAPI, Security
from fastapi.security import OAuth2PasswordBearer
app = FastAPI()
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="/token")
class User(BaseModel):
username: str
email: Optional[str] = None
full_name: Optional[str] = None
disabled: Optional[bool] = None
def fake_decode_token(token):
return User(
username=token + "fakedecoded", email="john@example.com", full_name="John Doe"
)
from fastapi import FastAPI
app = FastAPI()
@app.get("/items/")
async def read_items(q: str = None):
results = {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]}
if q:
results.update({"q": q})
return results
def server(model):
app = FastAPI()
input_features = {
f['name'] for f in model.model_definition['input_features']
}
@app.get('/')
def check_health():
return JSONResponse({"message": "Ludwig server is up"})
@app.post('/predict')
async def predict(request: Request):
form = await request.form()
files, entry = convert_input(form)
try:
if (entry.keys() & input_features) != input_features:
server_timing.append(f"{name}={(stats.pop().ttot * 1000):.3f}")
if server_timing:
response.headers["Server-Timing"] = ','.join(server_timing)
#yappi.clear_stats()
return response
# ######################
# ##### Usage test #####
# ######################
import asyncio
from httpx import AsyncClient
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
async def context_id_endpoint() -> Tuple[int, float]:
start = time.time()
await asyncio.sleep(1)
end = time.time()
return get_context_id(), end - start
track: Dict[str, str] = {
"endpoint": context_id_endpoint.__qualname__,
"pydantic": fastapi.routing.serialize_response.__qualname__,
"render": Response.render.__qualname__,
"dispatch": BenchMiddleware.dispatch.__qualname__
}
from fastapi import FastAPI, Query
app = FastAPI()
@app.get("/items/")
async def read_items(q: str = Query(None, title="Query string", min_length=3)):
results = {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]}
if q:
results.update({"q": q})
return results
from typing import Set
from fastapi import FastAPI
from pydantic import BaseModel
from pydantic.types import UrlStr
app = FastAPI()
class Image(BaseModel):
url: UrlStr
name: str
class Item(BaseModel):
name: str
description: str = None
price: float
tax: float = None
tags: Set[str] = []
image: Image = None