So today I came up with a need to use the built-in csv module INSIDE the web2py DAL Field's compute callback. Code snippet of my db.py looks like this.
import csv
def zipcode2city(zipcode):
print "Debug: you will see this line on console"
content = csv.DictReader(open("zipcode.csv"))
print "Debug: you will NOT see this line on console"
# find the zipcode in content and return its city
return "Tucson" # for example
db.define_table("my_table",
Field("zipcode", "string"),
Field("city", "string", compute=lambda r: zipcode2city(r["zipcode"]),
)
However, during my test using the built-in admin interface, the above code snippet NEVER update the city. So I put some print lines to debug. It turns out I saw the 1st print output but not the 2nd, yet WITHOUT any error or exception in between. Really nasty.
Eventually I spot the culprit. It is because the scaffold appadmin.py contains a function named exactly "csv"! So when that zipcode2city() runs, "csv" is that function, not the module. I would hereby suggest to change that function in appadmin to another name such as "csv_export" (and also change its views, of course).
I did not further trace down to see why web2py does not generate an explicit error ticket during the compute callback. Is this by design? For what reason?