[Python] Redis Python - how to delete all keys according to a specific pattern In python,...

Discussão em 'Python' iniciado por Stack, Julho 15, 2025.

  1. Stack

    Stack Membro Participativo

    I'm writing a django management command to handle some of our redis caching. Basically, I need to choose all keys, that confirm to a certain pattern (for example: "prefix:*") and delete them.

    I know I can use the cli to do that:

    redis-cli KEYS "prefix:*" | xargs redis-cli DEL


    But I need to do this from within the app. So I need to use the python binding (I'm using py-redis). I have tried feeding a list into delete, but it fails:

    from common.redis_client import get_redis_client
    cache = get_redis_client()
    x = cache.keys('prefix:*')

    x == ['prefix:key1','prefix:key2'] # True


    # And now

    cache.delete(x)


    # returns 0 . nothing is deleted

    I know I can iterate over x:

    for key in x:
    cache.delete(key)


    But that would be losing redis awesome speed and misusing its capabilities. Is there a pythonic solution with py-redis, without iteration and/or the cli?

    Thanks!

    Continue reading...

Compartilhe esta Página