UnicodeDecodeError issue

Steven D'Aprano steve+comp.lang.python at pearwood.info
Sat Aug 31 11:44:34 EDT 2013


On Sat, 31 Aug 2013 15:58:11 +0300, Ferrous Cranus wrote:

Failure is here, line 135:

>> cur.execute('''INSERT INTO files (url, host, city, lastvisit) VALUES
>> (%s, %s, %s, %s)''', (filename, host, city, lastvisit) ),

[...]
> But how is this possible since:
> 
> 
> host = socket.gethostbyaddr( os.environ['REMOTE_ADDR'] ) or
> socket.gethostbyaddr( os.environ['HTTP_CF_CONNECTING_IP'] ) or
> os.environ['REMOTE_ADDR']

What's the line number of that line of code? My guess is that it is AFTER 
line 135, which is where the error occurs. Or possibly it is inside a 
function that hasn't been called. Here is the same failure:

print(host)
host = "this is too late"


Here is the same failure again:

if 0:
    host = "this never gets called"
print(host)


Here is the same failure again:

data = []
for x in data:
    host = "This never happens"
print(host)


And again, a trickier one this time:

host = "something"
del host  # and now it is gone
print(host)


And again:

def func():
    global host
    print(host)
func()
host = "Too late, the error has already occurred"


One last one:

def set_host():
    host = "This is a local variable"
set_host()
print(host)


Study all these examples. Now read your own code. host has not been 
defined at the time the cur.execute line is reached. You have to work out 
which of my examples best matches your code.


> it must have a value by defaulting to something.

No, there is no default value for variables. How long have you been 
programming in Python? Six months? A year?


> The cur.execute fails because it make use of 'host' which is undefined.

Correct.


> 		# Try to insert the file into the database cur.execute
('''INSERT INTO
> 		files (url, host, city, lastvisit) VALUES
> (%s, %s, %s, %s)''', (filename, host, city, lastvisit) )
> 
> 
> And the question remain as to why 'host' is undefined.

Because you haven't defined it BEFORE you try to use it. There is no 
point defining it AFTER you use it, the error has already occurred.

You have to make the coffee before you drink it:

# This fails too
drink(coffee)
coffee = make_coffee()


# This doesn't help at all
drink(coffee)
coffee = make_coffee() or prepare_coffee()


# This is also useless
drink(coffee)
coffee = make_coffee() or prepare_coffee() or "coffee"


# But this works
coffee = make_coffee()
drink(coffee)



-- 
Steven



More information about the Python-list mailing list