Coder Social home page Coder Social logo

yoyowallet / django-idempotency-key Goto Github PK

View Code? Open in Web Editor NEW
45.0 45.0 7.0 364 KB

Allows view/viewset functions to use idempotency keys and automatically return the same data if called multiple times.

License: MIT License

Makefile 1.14% Python 98.86%

django-idempotency-key's People

Contributors

delboyjay avatar dependabot[bot] avatar jianyuan avatar stuart-bradley avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

django-idempotency-key's Issues

Redis module is required by default

Problem:
Even though I'm using "idempotency_key.locks.ThreadLock", I need to import Redis in order for Django to run.

Solution:
Add a conditional check to see if the user is using "idempotency_key.locks.MultiProcessRedisLock". If they are, then we import Redis.
Implementation can be seen at pull request #13 .

[Question] when you say return the same data, you mean for GET requests only right?

If the request has previously succeeded then the original data will be returned and

you mentioned

If the request has previously succeeded then the original data will be returned and
nothing new is created.

This applies only to GET requests using the same idempotency key in the header yes?

If it's POST, and the same idempotency key is used, we get a 409 conflict yes? we won't actually get back the same data would we?

MultiProcessRedisLock locks on lock name not on encoded key

Issue : The Redis lock is applied to a key labelled "LOCK_NAME" which remains consistent across all requests. This ensures that only one request can be processed at any given time. To improve this approach, it might be more appropriate to first append an encoded key to the label before applying the lock.

https://github.com/yoyowallet/django-idempotency-key/blob/master/idempotency_key/locks/redis.py#L20

Solution: I reckon we can add encoded key following way. I can create PR if you are happy with below solution.


class CustomExemptIdempotencyKeyMiddleware(ExemptIdempotencyKeyMiddleware):
    def __init__(self, get_response):
        super().__init__(get_response)
        self.storage_lock_class = utils.get_lock_class()

    def reload_storage_lock(self, encoded_key):
        self.storage_lock = self.storage_lock_class(encoded_key)

    def release_lock(self):
        self.storage_lock.release()

    def acquire_lock(self):
        return self.storage_lock.acquire()

    def generate_response(self, request, encoded_key, lock=None):
        # The default storage lock is established with a common lock prefix shared among all locks.
        # To generate a lock with an encoded key, simply reload the storage lock.
        self.reload_storage_lock(encoded_key)

        if lock is None:
            lock = utils.get_lock_enable()

        if not lock:
            return self.perform_generate_response(request, encoded_key)

        # If there was a timeout for a lock on the storage object then return a
        # HTTP_423_LOCKED
        if not self.acquire_lock():
            return resource_locked(request, None)
        try:
            return self.perform_generate_response(request, encoded_key)
        finally:
            self.release_lock()
class CustomMultiProcessRedisLock(IdempotencyKeyLock):
    """
    Should be used if a lock is required across processes. Note that this class uses
    Redis in order to perform the lock.
    """

    def __init__(self, idempotency_key=None):
        location = utils.get_lock_location()
        if location is None or location == "":
            raise ValueError("Redis server location must be set in the settings file.")

        self.redis_obj = Redis.from_url(location)

        lock_name = (
            f"{utils.get_lock_name()}-{idempotency_key}"
            if idempotency_key
            else utils.get_lock_name()
        )
        self.storage_lock = self.redis_obj.lock(
            name=lock_name,
            # Time before lock is forcefully released.
            timeout=utils.get_lock_time_to_live(),
            blocking_timeout=utils.get_lock_timeout(),
        )

    def acquire(self, *args, **kwargs) -> bool:
        return self.storage_lock.acquire(blocking=False)

    def release(self):
        # Just incase if Middleware releases without acquiring. Less likely. Ignoring it instead of popping up an error.
        with suppress(Exception):
            self.storage_lock.release()

Django 3 support

Can someone explain the issues with Django 3? Perhaps I can come up with a PR.

idempotency_key_manual is returning 409 conflict, not the response stored in the cache

Hi,

I have tried to use "idempotency_key.middleware.IdempotencyKeyMiddleware" in settings.py, and @idempotency_key_manual as a decorator on the view function. While the responses are getting written to the cache correctly, usage of idempotency_key_manual is only returning a 409 conflict if a duplicate request is served. Im expecting it to return the response object stored in the database for that key.

I have noticed, it is because the idempotency_key_manual = false even though the decorator is specified.
And hence this code below gets executed
if not request.idempotency_key_manual and key_exists:
# Get the required return status code from settings
status_code = utils.get_conflict_code()

Also im using 2 other decorators
@swagger_auto_schema and @transaction.atomic
along with @idempotency_key_manual. Could that be a problem that they dont work well together?

Decorator and class based views

Hello, does this package supports class based views? I've tried to use it along with ExemptIdempotencyKeyMiddleware but the idempotency_key decorator doesn't work, it allows creating multiple instances, I added a custom middleware to inspect the request and the header with the key exists, could anyone provide an example about how should it be used with drf?

class DebugMiddleware:
    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):
        if request.method == 'POST':
            print('Headers', request.headers)
            print('META', request.META)
            idempotency_key = request.META.get("HTTP_IDEMPOTENCY_KEY")
            print(f'idempotency_key: {idempotency_key}')
        response = self.get_response(request)
        return response
class OrdersCreateViews(CreateAPIView):
    """
    View to create new Orders.
    """
    serializer_class = OrderSerializer
    authentication_classes = (TokenAuthentication,)

    @idempotency_key
    def create(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        self.perform_create(serializer)
        headers = self.get_success_headers(serializer.data)
        return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.