I am playing with Flask to understand it better. I have a simple app that queries a large database and returns a random element. The following code is not working but I know exactly where it fails. It fails when I can random.randint() to get a random element in the list. There is however no error shown in my logs, what is the root cause of this? It works if I use a hardcoded value instead of a random int. I use curl to test it. I snipped the database code as it seems to be correct.
from flask import Flask, render_template, request
app = Flask(__name__)
# <snipped>: Do some sql queries and populate a list called P_LIST
r = random.randint(0, len(P_LIST)) # This line silently fails.
r_e = P_LIST[r] # Never seems to get here
print "get_random_element", r_e # Never prints this line!!
@app.route('/element', methods=['POST', 'GET'])
if request.method == 'GET':
p = request.args.get('q', '')
print "Request:", p
if p == 'random' or p == '':
p = get_random_element()
print "Random element:", p
print "Else:", p
return render_template('random.html', element=p)
if __name__ == '__main__':
It is something I don't understand but here is what is happening. I need to import random inside the random() function. Otherwise the global "import random" statement does not seem to be sufficient. Not sure why. So adding one import line inside random() made it work. If anybody can explain this I would be grateful.
EDIT: Now I understand what is going on. The function name random() was causing some sort of conflict. If I change it to rand() everything works fine now with just one global import.
You have redefined
random by defining a function named
@app.route('/element', methods=['POST', 'GET']) def random(): ...
This shadows the imported module, causing the problem that you see. When you
import random again in
get_random_element() your code can access the module
random instead of the local function
Fix this by renaming the function, perhaps call it
element() since that is the route name.