Archive

Problem
MongoDB generates 96 bit hash values that are used as primary keys. In a project of mine I also needed randomly generated primary keys so I decided to go the MongoDB way. So the question is: how to generate 96 bit hash values with Python?

Update (20130813)
I found a related work called SimpleFlake. SimpleFlake generates 64 bit IDs, where the ID is prefixed with a millisecond timestamp and the remaining bits are completely random. It has the advantage that IDs show the chronological order of ID creation.

Here I present a basic socket client server example. It can be used as a starting point for a more serious project.

Problem
You want to have a server that is listening on a port. The server can receive data and these pieces of data must be processed one after the other. That is, the server must manage a queue and the received data are put in this queue. The elements in the queue must be processed one by one.

We also need a client whose job is to send data to the server.

(1) Common config part

# config.py
PORT=3030

The port number won’t be repeated in the server and in the client. Instead, it is read from a config file.

We create a thread that is running in the background and manages the queue. In a loop it checks if there is an element in the queue. If yes, then it takes out the first element and processes it.

In the main function we start listening on a given port. Incoming data are passed to the thread, where the thread puts it in the queue.

You can stop the server with CTRL+C. The cleanup method stops the thread nicely: it changes a variable to False, thus the thread quits from its infinite loop. Notice the parameters of q.get: we block for 1 second only. This way we have a chance to stop the thread even if the queue is empty. With t.join() we wait until it completely stops.