forked from retoor/devplacepy
Compare commits
1
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
6392e84917 |
File diff suppressed because one or more lines are too long
+11
-3
@@ -15,19 +15,27 @@ def avatar_seed(user) -> str:
|
||||
return user.get("avatar_seed") or user.get("username") or ""
|
||||
|
||||
|
||||
def generate_avatar_svg(seed: str) -> str:
|
||||
def _svg_with_size(svg: str, size: int) -> str:
|
||||
size_attr = f' width="{size}" height="{size}"'
|
||||
if svg.startswith("<svg"):
|
||||
tag_end = svg.index(">")
|
||||
return svg[:tag_end] + size_attr + svg[tag_end:]
|
||||
return svg
|
||||
|
||||
|
||||
def generate_avatar_svg(seed: str, size: int = 128) -> str:
|
||||
try:
|
||||
from multiavatar.multiavatar import multiavatar
|
||||
|
||||
svg = multiavatar(seed, None, None)
|
||||
if svg and svg.strip().startswith("<svg"):
|
||||
return svg
|
||||
return _svg_with_size(svg, size)
|
||||
except Exception as e:
|
||||
logger.exception(e)
|
||||
logger.warning(f"Avatar generation failed for {seed}: {e}")
|
||||
initial = seed[:1].upper() if seed else "?"
|
||||
return (
|
||||
'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100">'
|
||||
f'<svg xmlns="http://www.w3.org/2000/svg" width="{size}" height="{size}" viewBox="0 0 100 100">'
|
||||
f'<rect width="100" height="100" rx="50" fill="#ff6b35"/>'
|
||||
f'<text x="50" y="65" text-anchor="middle" fill="white" font-size="40" font-weight="700" font-family="sans-serif">{initial}</text></svg>'
|
||||
)
|
||||
|
||||
@@ -38,7 +38,6 @@ def field(
|
||||
example="",
|
||||
description="",
|
||||
options=None,
|
||||
nullable=False,
|
||||
):
|
||||
spec = {
|
||||
"name": name,
|
||||
@@ -47,7 +46,6 @@ def field(
|
||||
"required": required,
|
||||
"example": example,
|
||||
"description": description,
|
||||
"nullable": nullable,
|
||||
}
|
||||
if options:
|
||||
spec["options"] = list(options)
|
||||
|
||||
@@ -39,15 +39,7 @@ def _unwrap_optional(annotation):
|
||||
return annotation
|
||||
|
||||
|
||||
def _is_optional(annotation):
|
||||
if get_origin(annotation) is Union:
|
||||
return type(None) in get_args(annotation)
|
||||
return False
|
||||
|
||||
|
||||
def _value(name, annotation, stack, is_nullable=False):
|
||||
if is_nullable:
|
||||
return None
|
||||
def _value(name, annotation, stack):
|
||||
annotation = _unwrap_optional(annotation)
|
||||
origin = get_origin(annotation)
|
||||
if origin in (list, set, tuple):
|
||||
@@ -79,8 +71,7 @@ def _from_model(model, stack):
|
||||
stack = stack | {model}
|
||||
example = {}
|
||||
for name, info in model.model_fields.items():
|
||||
is_nullable = _is_optional(info.annotation)
|
||||
example[name] = _value(name, info.annotation, stack, is_nullable)
|
||||
example[name] = _value(name, info.annotation, stack)
|
||||
return example
|
||||
|
||||
|
||||
|
||||
@@ -17,14 +17,16 @@ _CACHE_CONTROL = f"public, max-age={SECONDS_PER_DAY}, immutable"
|
||||
|
||||
@router.get("/{style}/{seed}")
|
||||
async def avatar_proxy(request: Request, style: str, seed: str, size: int = 128):
|
||||
etag = '"' + hashlib.md5(f"{seed}:{size}".encode("utf-8")).hexdigest() + '"'
|
||||
size = max(16, min(512, size))
|
||||
cache_key = f"{seed}:{size}"
|
||||
etag = '"' + hashlib.md5(cache_key.encode("utf-8")).hexdigest() + '"'
|
||||
headers = {"ETag": etag, "Cache-Control": _CACHE_CONTROL}
|
||||
|
||||
if request.headers.get("if-none-match") == etag:
|
||||
return Response(status_code=304, headers=headers)
|
||||
|
||||
svg = _cache.get(seed)
|
||||
svg = _cache.get(cache_key)
|
||||
if svg is None:
|
||||
svg = generate_avatar_svg(seed)
|
||||
_cache.set(seed, svg)
|
||||
svg = generate_avatar_svg(seed, size)
|
||||
_cache.set(cache_key, svg)
|
||||
return Response(content=svg, media_type="image/svg+xml", headers=headers)
|
||||
|
||||
@@ -218,16 +218,6 @@
|
||||
font-weight: 700;
|
||||
}
|
||||
|
||||
.param-nullable {
|
||||
font-size: 0.625rem;
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 0.05em;
|
||||
color: var(--text-muted);
|
||||
border: 1px dashed var(--border);
|
||||
border-radius: 999px;
|
||||
padding: 0.05rem 0.4rem;
|
||||
}
|
||||
|
||||
.param-loc {
|
||||
font-size: 0.625rem;
|
||||
text-transform: uppercase;
|
||||
|
||||
@@ -139,7 +139,6 @@ export class ApiTester {
|
||||
const label = this.el("div", { class: "param-label" }, [
|
||||
this.el("span", { class: "param-name", text: param.name }),
|
||||
param.required ? this.el("span", { class: "param-required", text: "*" }) : null,
|
||||
param.nullable ? this.el("span", { class: "param-nullable", text: "nullable" }) : null,
|
||||
this.el("span", { class: "param-loc param-loc-" + param.location, text: param.location }),
|
||||
]);
|
||||
const allowed = param.type === "enum" && param.options && param.options.length
|
||||
|
||||
+29
-1
@@ -1,7 +1,6 @@
|
||||
# retoor <retoor@molodetz.nl>
|
||||
|
||||
import requests
|
||||
from devplacepy.avatar import avatar_url, generate_avatar_svg
|
||||
from tests.conftest import BASE_URL
|
||||
|
||||
|
||||
@@ -10,3 +9,32 @@ def test_avatar_endpoint_serves_svg(app_server):
|
||||
assert r.status_code == 200
|
||||
assert "svg" in r.headers.get("content-type", "").lower()
|
||||
assert "<svg" in r.text
|
||||
|
||||
|
||||
def test_avatar_respects_size(app_server):
|
||||
r = requests.get(f"{BASE_URL}/avatar/multiavatar/alice_test?size=32")
|
||||
assert r.status_code == 200
|
||||
assert 'width="32"' in r.text
|
||||
assert 'height="32"' in r.text
|
||||
|
||||
|
||||
def test_avatar_different_sizes_different_response(app_server):
|
||||
r32 = requests.get(f"{BASE_URL}/avatar/multiavatar/bob_test?size=32")
|
||||
r128 = requests.get(f"{BASE_URL}/avatar/multiavatar/bob_test?size=128")
|
||||
assert r32.status_code == 200
|
||||
assert r128.status_code == 200
|
||||
etag32 = r32.headers.get("etag", "")
|
||||
etag128 = r128.headers.get("etag", "")
|
||||
assert etag32 != etag128, "same seed with different sizes must produce different ETags"
|
||||
|
||||
|
||||
def test_avatar_size_clamped_low(app_server):
|
||||
r = requests.get(f"{BASE_URL}/avatar/multiavatar/clamp_low?size=1")
|
||||
assert r.status_code == 200
|
||||
assert 'width="16"' in r.text
|
||||
|
||||
|
||||
def test_avatar_size_clamped_high(app_server):
|
||||
r = requests.get(f"{BASE_URL}/avatar/multiavatar/clamp_high?size=9999")
|
||||
assert r.status_code == 200
|
||||
assert 'width="512"' in r.text
|
||||
|
||||
@@ -1,59 +0,0 @@
|
||||
# retoor <retoor@molodetz.nl>
|
||||
|
||||
from typing import Optional
|
||||
|
||||
from pydantic import BaseModel
|
||||
|
||||
from devplacepy.docs_api._shared import field
|
||||
from devplacepy.docs_examples import _is_optional, schema_example
|
||||
|
||||
|
||||
def test_field_nullable_parameter():
|
||||
f = field("bio", "query", "string", False, "", "User biography", nullable=True)
|
||||
assert f["nullable"] is True
|
||||
|
||||
f2 = field("username", "path", "string", True, "alice", "Target username")
|
||||
assert f2["nullable"] is False
|
||||
|
||||
|
||||
def test_is_optional_optional_type():
|
||||
assert _is_optional(Optional[str]) is True
|
||||
assert _is_optional(Optional[int]) is True
|
||||
assert _is_optional(Optional[list[str]]) is True
|
||||
|
||||
|
||||
def test_is_optional_non_optional():
|
||||
assert _is_optional(str) is False
|
||||
assert _is_optional(int) is False
|
||||
assert _is_optional(list[str]) is False
|
||||
assert _is_optional(dict) is False
|
||||
|
||||
|
||||
def test_schema_example_nullable_fields():
|
||||
class NullableModel(BaseModel):
|
||||
name: str
|
||||
bio: Optional[str] = None
|
||||
age: int
|
||||
score: Optional[int] = None
|
||||
tags: Optional[list[str]] = None
|
||||
|
||||
result = schema_example(NullableModel)
|
||||
|
||||
assert result["name"] == "string"
|
||||
assert result["age"] == 0
|
||||
assert result["bio"] is None
|
||||
assert result["score"] is None
|
||||
assert result["tags"] is None
|
||||
|
||||
|
||||
def test_schema_example_non_nullable_fields_unaffected():
|
||||
class StrictModel(BaseModel):
|
||||
x: str
|
||||
y: int
|
||||
z: bool
|
||||
|
||||
result = schema_example(StrictModel)
|
||||
|
||||
assert result["x"] == "string"
|
||||
assert result["y"] == 0
|
||||
assert result["z"] is False
|
||||
Reference in New Issue
Block a user