簡體   English   中英

如何使用Pyramid的漏勺驗證應用程序邏輯?

[英]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尚未被其他用戶使用
  • passwordconfirmation相同

因此,在我的控制器中,代碼類似於以下偽代碼:

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'))

基本上有兩種驗證方式。 在單個濾鍋模式中是否可以同時具有兩種邏輯? 這是一個好模式嗎?

顯然,這是個問題,但恕我直言,最好將數據驗證與應用程序邏輯分開。

您還會遇到一些問題,試圖確認用戶名是唯一的:

  1. Colander需要了解您的應用程序,例如。 獲得對數據庫連接的訪問​​權限,以檢查數據庫中該用戶名不存在。
  2. 沒有為異步編程設置Colander(AFAIK),因此在處理檢查用戶是否存在的async方法時會遇到問題。
  3. 您確實希望用戶創建為ACID,所以同時調用具有相同用戶名的create_user可能無法創建具有相同用戶名的兩個用戶。

檢查密碼是否匹配是另一回事,它不需要有關世界其他地方的任何知識,並且應該與漏勺無關緊要。 我不是漏勺專家,但是看起來您可以使用延遲驗證器來檢查兩個密碼是否匹配。

有關代碼的其他一些注意事項:

  1. create_user應該是一個async方法
  2. 我對您的數據庫一無所知,但要從異步編程中獲得任何好處, user_exists應該也是異步的
  3. 用戶存在檢查應包含在ACID用戶創建中。 例如。 您應該on conflict使用postgres的on conflict或等效問題來捕獲重復的用戶,而不是先檢查它們是否存在
  4. 為了保持適當的狀態並簡化測試,您的視圖應針對錯誤返回正確的http響應代碼(當前,所有狀態都返回200)。 您應將201用於創建,將400用於無效日期,將409或用戶名沖突。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM