我是Azure功能的新手,正在寻找一种方法来验证POST请求接收到的请求数据。
是否可以使用pydantic库来执行这些验证,如果不能,输入验证的最佳方式是什么。
使用python类型注释的数据验证和设置管理。
pydantic 在运行时强制执行类型提示,并在数据无效时提供用户友好的错误。
您可以使用pydantic库对主体进行任何验证,如:
from pydantic import ValidationError
try:
User(signup_ts='broken', friends=[1, 2, 'not number'])
except ValidationError as e:
print(e.json())
我有一个azure函数代码,它接受POST请求并触发函数。此示例代码处理基本联系信息表单的提交
import logging
import azure.functions as func
from urllib.parse import parse_qs
def main(req: func.HttpRequest) -> func.HttpResponse:
# This function will parse the response of a form submitted using the POST method
# The request body is a Bytes object
# You must first decode the Bytes object to a string
# Then you can parse the string using urllib parse_qs
logging.info("Python HTTP trigger function processed a request.")
req_body_bytes = req.get_body()
logging.info(f"Request Bytes: {req_body_bytes}")
req_body = req_body_bytes.decode("utf-8")
logging.info(f"Request: {req_body}")
first_name = parse_qs(req_body)["first_name"][0]
last_name = parse_qs(req_body)["last_name"][0]
email = parse_qs(req_body)["email"][0]
cell_phone = parse_qs(req_body)["cell_phone"][0]
return func.HttpResponse(
f"You submitted this information: {first_name} {last_name} {email}
{cell_phone}",
status_code=200,
)
查看以下Python POST请求的GitHub示例:https://github.com/yokawasa/azure-functions-python-samples/tree/master/v2functions/http-trigger-onnx-model