6

I'm using a pydantic model to represent a request body in fastapi.

from pydantic import BaseModel, Schema

class Files(BaseModel):
    '''Class for file URLs'''
    urls: Set[str] = Schema(..., title='Urls to files')

This will restrict the request body to set of urls defined as str.

I was wondering if there's a way to further limit the "types" of urls sent in the body, by using e.g. regular expressions. I know Schema has a regex flags, but I think that will only work with a single input (or at least it didn't work with my lists).

Val
  • 6,585
  • 5
  • 22
  • 52

1 Answers1

10

You can use the ConstrainedStr type like this:

import pydantic
from typing import Set
MyUrlsType =pydantic.constr(regex="^[a-z]$")
class MyForm(pydantic.BaseModel):
    urls : Set[MyUrlsType]

It only works at the creation of the object:

MyForm(urls={"a", "B"})
Traceback (most recent call last):
  File "<pyshell#7>", line 1, in <module>
    MyForm(urls={"a", "B"})
  File "C:\Users\XXXX\AppData\Local\Programs\Python\Python37-32\lib\site-packages\pydantic\main.py", line 275, in __init__
    values, fields_set, _ = validate_model(__pydantic_self__, data)
  File "C:\Users\XXXX\AppData\Local\Programs\Python\Python37-32\lib\site-packages\pydantic\main.py", line 785, in validate_model
    raise err
pydantic.error_wrappers.ValidationError: 1 validation error for MyForm
urls -> 1
  string does not match regex "^[a-z]$" (type=value_error.str.regex; pattern=^[a-z]$)

The ConstrainedStr Type is not enforced on Set add method:

f = MyForm(urls={"a", "b"})
>>> <MyForm urls={'b', 'a'}>
f.urls.add("c")
f.urls.add("yolo")
f.urls
>>> {'b', 'a', 'yolo', 'c'}
Krilivye
  • 547
  • 4
  • 8