laitimes

FastAPI开源框架开发实践:默认参数(default parameters)

author:Architecture Notes

Sometimes, we need to specify default values for query and path parameters for certain API services to avoid validation error messages such as field required and value_error.missing. Setting a default value for a parameter will allow the API method to be executed with or without a parameter value.

Depending on the requirements, the default value for the assignment is usually 0 for the number type, False for the Boolean type, an empty string for the string type, an empty list [] for the list type, and an empty dictionary {} for the dictionary type.

This article describes examples of default parameter development, including delete_pending_users() and change_password() services.

FastAPI开源框架开发实践:默认参数(default parameters)

1. delete_pending_users Services

The following delete_pending_users() service shows how to apply default values to query and path parameters:

@app.delete("/ch01/login/remove/all")
def delete_users(usernames: List[str]):
 for user in usernames:
 del valid_users[user]
 return {"message": "用户已删除"}           

This code defines a FastAPI route handler that deletes multiple users.

List[str] is a type annotation that indicates that usernames should be a list of strings. This is a type hint provided by the Pydantic library that FastAPI relies on to automatically handle validation of the requested data.

delete_pending_users() can even be executed without passing any accounts arguments, since accounts are always an empty List by default.

FastAPI开源框架开发实践:默认参数(default parameters)

If the user name exists in the valid_users dictionary, the corresponding user will be deleted. If you try to delete a key that doesn't exist, Python will throw a KeyError. If you want to avoid this exception, you need to check if the key exists before attempting to delete it.

FastAPI开源框架开发实践:默认参数(default parameters)

2. change_password services

Here's an example of the change_password() service, where the old_pwd and new_pwd default parameter values are empty strings.

@app.get("/ch01/login/password/change")
def change_password(username: str, old_pwd: str = '', new_pwd: str = ''):
    pwd_len = 8
    if valid_users.get(username) is None:
        return {"message": "用户不存在"}
    elif old_pwd == '' or new_pwd == '':
        characters = ascii_lowercase
        temp_pwd = ''.join(random.choice(characters) for i in range(pwd_len))
        user = valid_users.get(username)
        user.password = temp_pwd
        user.passphrase = hashpw(temp_pwd.encode(), gensalt())
        return user
    else:
        user = valid_users.get(username)
        if user.password == old_pwd:
            user.password = new_pwd
            user.passphrase = hashpw(new_pwd.encode(), gensalt())
            return user
        else:
            return {"message": "无效用户"}           

When accessing the API service, no parameter values are passed to old_pwd and new_pwd, as they are all empty str by default. hashpw() is a bcrypt utility that generates hashed passwords from an auto-generated salt.

FastAPI开源框架开发实践:默认参数(default parameters)

In the figure above, since both the old_pwd and new_pwd are empty strings, a random password is generated according to the code logic.

In the following figure, the old_pwd and new_pwd parameter values are passed in at the same time, and the password is updated to the new_pwd parameter value.

FastAPI开源框架开发实践:默认参数(default parameters)

#WinterLifeCheck-in Season##记录我的2024#

Read on