I have a commenting system where people can type in a comment and optionally their name and email if they like.
In production, where things are real, the IP address that can be collected are all interestingly different. But when testing this manually on my laptop, since the server is running http://localhost:8000
, the request.META.get('REMOTE_ADDR')
always becomes 127.0.0.1
. Boring! So I fake it. Like this:
import random
from ipaddress import IPv4Address
def _random_ip_address(seed):
random.seed(seed)
return str(IPv4Address(random.getrandbits(32)))
...
# Here's the code deep inside the POST handler just before storing
# the form submission the database.
if settings.DEBUG and metadata.get("REMOTE_ADDR") == "127.0.0.1":
# Make up a random one!
metadata["REMOTE_ADDR"] = _random_ip_address(
str(form.cleaned_data["name"]) + str(form.cleaned_data["email"])
)
It's pretty rough but it works and makes me happy.
Comments