[Python] What is the best way to sanitize data in the backend with Flask to prevent XSS...

Discussão em 'Python' iniciado por Stack, Abril 7, 2025.

  1. Stack

    Stack Membro Participativo

    I am developing a RESTful API with Flask and need to sanitize the data received from users (both JSON and form data) to prevent XSS attacks. Currently, I’m using a before_request function to sanitize the data before it reaches the endpoints.Here is my code:

    def before_request() -> None:
    if request.method in ["POST", "PUT"]:
    if request.is_json:
    request_data = request.get_json()
    if request_data is not None:
    g.data = sanitize_data(request_data)
    else:
    request_data = request.form.to_dict()
    if request_data is not None:
    g.data = sanitize_data(request_data)

    def sanitize_data(data):
    if isinstance(data, dict):
    return {key: sanitize_data(value) for key, value in data.items()}
    elif isinstance(data, list):
    return [sanitize_data(item) for item in data]
    elif isinstance(data, str):
    try:
    json.loads(data) # Avoid escaping JSON strings
    return data
    except json.JSONDecodeError:
    return escape(data) # Sanitize non-JSON strings
    else:
    return data

    def get_request_data():
    if request.is_json:
    return getattr(g, "data", request.get_json())
    else:
    return getattr(g, "data", request.form.to_dict())

    @BP.route("/user/edit-name", methods=["POST"])
    @flask_login.login_required
    def edit_user_name():
    data = get_request_data()
    response = utils.put_resource(
    "projects",
    resource_id=data["uuid"],
    query_params={"action": "Users.EditName"},
    data=data,
    )
    ...code...


    My questions:

    1. Is this an efficient and secure way to sanitize data in Flask? Are there better alternatives?
    2. What are the best practices for sanitizing user input in a Flask backend to prevent XSS attacks?

    Continue reading...

Compartilhe esta Página