3

I have a Django application to log the character sequences from an autocomplete interface. Each time a call is made to the server, the parameters are added to a list and when the user submits the query, the list is written to a file.

Since I am not sure how to preserve the list between subsequent calls, I relied on a global variable say query_logger. Now I can preserve the list in the following way:

def log_query(query, completions, submitted=False):
    global query_logger
    if query_logger is None:
        query_logger = list()

    query_logger.append(query, completions, submitted)

    if submitted: 
        query_logger = None

While this hack works for a single client sending requests I don't think this is a stable solution when requests come from multiple clients. My question is two-fold:

  1. What is the order of execution of requests: Do they follow first come first serve (especially if the requests are asynchronous)?
  2. What is a better approach for doing this?
1
  • 2
    It also will not work if you are deploying with a multi process web server. Commented Jun 12, 2018 at 5:50

3 Answers 3

2

You must not use global variables for this.

The proper answer is to use the session - that is exactly what it is for.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks. That's what I was thinking. Still, had to confirm there are no alternatives.
1
  1. If your django server is single-threaded, then yes, it will respond to requests as it receives them. If you're using wsgi or another proxy, that becomes more complicated. Regardless, I think you'll want to use a db to store the information.

  2. I encountered a similar problem and ended up using sqlite to store the data temporarily, because that's super simple and easy to manage. You'll want to use IP addresses or create a unique ID passed as a url parameter in order to identify clients on subsequent requests.

I also scheduled a daily task (using cron on ubuntu) that goes through and removes any incomplete requests that haven't been completed (excluding those started in the last hour).

1 Comment

Thanks! I think I will go with session as @daniel roseman suggested.
-1

Simplest (bad) solution would be to have a global variable. Which means you need some in memory location or a db to store this info

2 Comments

My solution above uses global variables. DB is a possible way to go!
Move the initial assignment outside the scope of the function and test please. Also you might be able to use request.session

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.