How to track anonymous users using Flask

My application has a shopping cart in which anonymous users can fill their cart with products. User login is only required before payment. How can this be implemented?

The main problem is that the flask should track the user (even anonymous) and their orders. My current approach is to use the AnonymousUserMixin object, which is assigned to current_user . It is assumed that current_user will not change throughout the session. However, I noticed that a new AnonymousUserMixin object is assigned to current_user , for example, each time the browser page is refreshed. Please note that this does not happen if the user is authenticated.

Any suggestions on how to get around this?

+5
source share
2 answers

There is no need for a custom AnonymousUserMixin , you can store shopping cart data in a session:

  • an anonymous user adds something to the basket → updates his session with the basket data.
  • user wants to check → redirect him to the login page
  • the registered user returns to the exit → retrieves the data of his basket from the session and does everything that you would do if he had been registered all the time
+8
source

You can use the AnonymousUserMixin subclass if you want, but you need to add some logic to it so that you can associate each anonymous user with a basket stored in your database.

This is what you can do:

  • When a new user connects to your application, you assign a randomly generated unique identifier. You can record this random identifier in a user session (if you want the cart to be deleted when you close the browser window) or in a long-lived cookie (if you want the cart to be remembered even after closing the browser). You can use Flask-Login to control the session / cookie in fact, you do not need to consider unknown users as anonymous, once you assign them an identifier, you can treat them as registered users.

  • How do you know if an anonymous user is known or new? When the user connects, you check if the session or cookie exists and look for the identifier there. If the identifier is found, you can find the cart for the user. If you use a subclass of AnonymousUserMixin , you can add id as a member variable so that you can do current_user.id even for anonymous users. You can use this logic in the Flask-Login user loader callback.

  • When a user is ready to pay, you convert an anonymous user into a registered user, keeping the identifier.

  • If you have a cron job that regularly clears old / abandoned anonymous carts from the database, you may find that the old anonymous user connects and provides an identifier for a user who does not have a recycle bin in the database (because the cart is deprecated and deleted). You can handle this by creating a new cart for the same identifier, and you can even notify the user that the contents of the cart have expired.

Hope this helps!

+1
source

All Articles