Global variable in Python server

Viewed 5702

Background: I am a complete beginner when it comes to servers, but I know my way around programming in Python.

I am trying to setup a simple server using the basic Python 2.7 modules (SimpleHTTPServer, CGIHTTPServer, etc). This server needs to load a global, read-only variable with several GB of data from a file when it starts; then, when each user accesses the page, the server uses the big data to generate some output which is then given to the user.

For the sake of example, let's suppose I have a 4 GB file names.txt which contains all possible proper nouns of English:

Jack
John
Allison
Richard
...

Let's suppose that my goal is to read the whole list of names into memory, and then choose 1 name at random from this big list of proper nouns. I am currently able to use Python's native CGIHTTPServer module to accomplish this. To start, I just run the CGIHTTPServer module directly, by executing from a terminal:

python -m CGIHTTPServer

Then, someone accesses www.example-server.net:8000/foo.py and they are given one of these names at random. I have the following code in foo.py:

#!/usr/bin/env python

import random

name_list = list()
FILE = open('names.txt','r')
for line in FILE:
    name = line[:-1]
    name_list.append(name)

FILE.close()
name_to_return = random.choice(name_list)

print "Content-type: text/html"
print
print "<title>Here is your name</title>"
print "<p>" + name_to_return + "</p>"

This does what I want; however, it is extremely inefficient, because every access forces the server to re-read a 4 GB file.

How can I make this into an efficient process, where the variable name_list is created as global immediately when the server starts, and each access only reads from that variable?

4 Answers
Related