<ruby id="bdb3f"></ruby>

    <p id="bdb3f"><cite id="bdb3f"></cite></p>

      <p id="bdb3f"><cite id="bdb3f"><th id="bdb3f"></th></cite></p><p id="bdb3f"></p>
        <p id="bdb3f"><cite id="bdb3f"></cite></p>

          <pre id="bdb3f"></pre>
          <pre id="bdb3f"><del id="bdb3f"><thead id="bdb3f"></thead></del></pre>

          <ruby id="bdb3f"><mark id="bdb3f"></mark></ruby><ruby id="bdb3f"></ruby>
          <pre id="bdb3f"><pre id="bdb3f"><mark id="bdb3f"></mark></pre></pre><output id="bdb3f"></output><p id="bdb3f"></p><p id="bdb3f"></p>

          <pre id="bdb3f"><del id="bdb3f"><progress id="bdb3f"></progress></del></pre>

                <ruby id="bdb3f"></ruby>

                ThinkChat2.0新版上線,更智能更精彩,支持會話、畫圖、視頻、閱讀、搜索等,送10W Token,即刻開啟你的AI之旅 廣告
                # Python Cerberus 教程 > 原文: [http://zetcode.com/python/cerberus/](http://zetcode.com/python/cerberus/) Python Cerberus 教程展示了如何在 Python 中使用 Cerberus 驗證數據。 ## Cerberus Cerberus 是一個 Python 驗證庫,它提供了功能強大而又簡單輕巧的數據驗證功能。 它被設計為易于擴展,允許自定義驗證。 Cerberus 通過定義數據驗證模式來工作。 該模式將傳遞到`Validator`并使用`validate()`進行驗證。 它具有適用于數據的一組規則,例如`required`,`min`或`max`。 可以將多個規則應用于數據字段。 如果驗證失敗,我們可以獲得帶有`errors`屬性的錯誤消息。 ## Cerberus 類型 以下是 Cerberus 的簡單演示。 使用`type`規則,我們可以設置字段的預期數據類型。 `simple.py` ```py #!/usr/bin/env python3 from cerberus import Validator schema = {'name': {'type': 'string'}} v = Validator(schema) document = {'name': 'john doe'} if v.validate(document): print('data is valid') else: print('invalid data') ``` 在示例中,我們驗證`name`字段; 我們希望它是一個字符串值。 ```py from cerberus import Validator ``` 我們導入`Validator`類。 ```py schema = {'name': {'type': 'string'}} ``` 我們定義模式。 這是 Python 字典。 我們指定名稱字段必須為字符串。 ```py document = {'name': 'john doe'} ``` 這是我們的數據。 ```py if v.validate(document): print('data is valid') else: print('invalid data') ``` 我們使用`validate()`驗證數據。 ```py $ ./simple.py data is valid ``` 這是輸出。 在第二個示例中,我們檢查字符串和列表類型。 `types.py` ```py #!/usr/bin/env python3 from cerberus import Validator v = Validator() v.schema = {'words': {'type': ['string', 'list']}} if v.validate({'words': 'falcon'}): print('valid data') else: print('invalid data') if v.validate({'words': ['falcon', 'sky', 'cloud']}): print('valid data') else: print('invalid data') ``` 該示例驗證`words`字段是字符串還是列表。 ## Cerberus 法則 `required`規則使該字段為必填字段。 `required.py` ```py #!/usr/bin/env python3 from cerberus import Validator v = Validator() v.schema = {'name': {'required': True, 'type': 'string'}, 'age': {'type': 'integer'}} if v.validate({'age': 34}): print('valid data') else: print('invalid data') print(v.errors) ``` 該示例有兩個數據字段:`name`和`age`。 `name`是必填字段。 ```py $ ./required.py invalid data {'name': ['required field']} ``` 我們省略了`name`字段; 因此,驗證失敗。 ## Cerberus 最小和最大規則 `min`和`max`規則設置整數,浮點數和數字類型所允許的最小值和最大值。 對于字符串類型,我們可以使用`minlength`和`maxlength`。 `min_max.py` ```py #!/usr/bin/env python3 from cerberus import Validator v = Validator() v.schema = {'name': { 'type': 'string', 'minlength': 2}, 'age': {'type': 'integer', 'min': 18, 'max': 65}} if v.validate({'name': 'J', 'age': 4}): print('valid data') else: print('invalid data') print(v.errors) ``` 在示例中,我們為字符串設置了最小長度,為整數設置了最小和最大大小。 ```py $ ./min_max.py invalid data {'age': ['min value is 18'], 'name': ['min length is 2']} ``` 我們有兩個驗證錯誤。 ## Cerberus 正則表達式規則 我們可以使用正則表達式定義更復雜的規則。 `regex.py` ```py #!/usr/bin/env python3 from cerberus import Validator v = Validator() v.schema = {"contact_details": { "type": "dict", "schema": { "phone": { "type": "string", "minlength": 10, "maxlength": 10, "regex": "^0[0-9]{9}$" }, "email": { "type": "string", "minlength": 8, "maxlength": 255, "required": True, "regex": "^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\\.[a-zA-Z0-9-.]+$" } } }} if v.validate({'contact_details': {'phone': '0901123123', 'email': 'john.doe@example.com'}}): print('valid data') else: print('invalid data') print(v.errors) ``` 在示例中,我們使用正則表達式為`phone`和`email`字段定義驗證規則。 ## Cerberus 值強制轉換 值強制使我們可以在數據驗證之前將可調用對象應用于值。 可調用對象的返回值替換文檔中的新值。 在驗證之前,可以使用強制轉換數據或清除數據。 `coercing.py` ```py #!/usr/bin/env python3 from cerberus import Validator from datetime import datetime def to_date(s): return datetime.strptime(s, '%Y-%m-%d') v = Validator() v.schema = {'start_date': {'type': 'datetime', 'coerce': to_date}} if v.validate({'start_date': '2019-12-11'}): print('valid data') else: print('invalid data') print(v.errors) if v.validate({'start_date': '2019/12/11'}): print('valid data') else: print('invalid data') print(v.errors) ``` 在示例中,我們使用自定義`to_date()`函數將數據時間值轉換為選定的格式。 ```py $ ./coercing.py valid data invalid data {'start_date': ["field 'start_date' cannot be coerced: time data '2019/12/11' does not match format '%Y-%m-%d'", 'must be of datetime type']} ``` 這是輸出。 ## 使用 YAML 文件 在下一個示例中,我們將數據存儲在 YAML 文件中。 `cities.yaml` ```py cities: - Bratislava - Kosice - Trnava - Moldava - Trencin ``` 該文件包含城市列表。 `from_yaml.py` ```py #!/usr/bin/env python3 from cerberus import Validator import yaml v = Validator() v.schema = {'cities': {'type': 'list', 'schema': {'type': 'string'}}} with open('cities.yaml') as f: data = yaml.load(f, Loader=yaml.FullLoader) print(data) if v.validate({'cities': data['cities']}): print('valid data') else: print('invalid data') print(v.errors) ``` 我們從 YAML 文件中讀取數據并進行驗證。 `schema`規則設置針對列表的所有元素驗證定義的規則。 ```py v = Validator() v.schema = {'cities': {'type': 'list', 'schema': {'type': 'string'}}} ``` `cities`字段必須是一個列表,并且其所有元素都必須是字符串。 ## Cerberus 定制驗證器 我們可以通過從`Validator`類擴展來創建自定義驗證器。 `custom_validator.py` ```py #!/usr/bin/env python3 from cerberus import Validator from dataclasses import dataclass @dataclass class Person: name: str age: int class PersonValidator(Validator): def validate_person(self, obj): return self.validate(obj.__dict__) schema = {'name': { 'type': 'string', 'minlength': 2}, 'age': {'type': 'integer', 'min': 18, 'max': 65}} v = PersonValidator(schema) p = Person('John Doe', 2) if v.validate_person(p): print('valid data') else: print('invalid data') print(v.errors) ``` 在示例中,我們為`Person`對象定義了一個自定義驗證器。 在本教程中,我們展示了如何使用 Cerberus 在 Python 中驗證數據。 您可能也對以下相關教程感興趣: [Python 字符串](/lang/python/strings/), [Python Jinja 教程](/python/jinja/)和 [Python 教程](/lang/python/),或列出[所有 Python 教程](/all/#python) 。
                  <ruby id="bdb3f"></ruby>

                  <p id="bdb3f"><cite id="bdb3f"></cite></p>

                    <p id="bdb3f"><cite id="bdb3f"><th id="bdb3f"></th></cite></p><p id="bdb3f"></p>
                      <p id="bdb3f"><cite id="bdb3f"></cite></p>

                        <pre id="bdb3f"></pre>
                        <pre id="bdb3f"><del id="bdb3f"><thead id="bdb3f"></thead></del></pre>

                        <ruby id="bdb3f"><mark id="bdb3f"></mark></ruby><ruby id="bdb3f"></ruby>
                        <pre id="bdb3f"><pre id="bdb3f"><mark id="bdb3f"></mark></pre></pre><output id="bdb3f"></output><p id="bdb3f"></p><p id="bdb3f"></p>

                        <pre id="bdb3f"><del id="bdb3f"><progress id="bdb3f"></progress></del></pre>

                              <ruby id="bdb3f"></ruby>

                              哎呀哎呀视频在线观看