[英]How do you validate application logic using Pyramid's Colander?
到目前為止,我正在使用漏勺驗證aiohttp應用程序中的數據。
我面臨的問題是我不知道如何進行“深度”驗證。
給定以下架構:
import colander
class User(colander.MappingSchema):
username = colander.SchemaNode(colander.String())
password = colander.SchemaNode(colander.String())
confirmation = colander.SchemaNode(colander.String())
我都確認輸入數據結構具有所有必填字段(為清楚起見,約束最小),但我還需要檢查以下內容:
username
尚未被其他用戶使用 password
和confirmation
相同 因此,在我的控制器中,代碼類似於以下偽代碼:
def create_user(request):
user = await request.json()
schema = User()
# do schema validation
try:
user = schema.deserialize(user)
except colander.Invalid, exc:
response = dict(
status='error',
errors=errors.asdict()
)
return json_response(response)
else:
# check password and confirmation are the same
if user['password'] != user['confirmation']:
response = dict(
status='error'
errors=dict(confirmation="doesn't match password")
)
return json_response(response)
# check the user is not already used by another user
# we want usernames to be unique
if user_exists(user['user']):
response = dict(
status='error',
errors=dict(username='Choose another username')
)
return json_response(response)
return json_response(dict(status='ok'))
基本上有兩種驗證方式。 在單個濾鍋模式中是否可以同時具有兩種邏輯? 這是一個好模式嗎?
顯然,這是個問題,但恕我直言,最好將數據驗證與應用程序邏輯分開。
您還會遇到一些問題,試圖確認用戶名是唯一的:
async
方法時會遇到問題。 create_user
可能無法創建具有相同用戶名的兩個用戶。 檢查密碼是否匹配是另一回事,它不需要有關世界其他地方的任何知識,並且應該與漏勺無關緊要。 我不是漏勺專家,但是看起來您可以使用延遲驗證器來檢查兩個密碼是否匹配。
有關代碼的其他一些注意事項:
create_user
應該是一個async
方法 user_exists
應該也是異步的 on conflict
使用postgres的on conflict
或等效問題來捕獲重復的用戶,而不是先檢查它們是否存在
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.