问题描述:

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

import sqlite3

import random

app = Flask(__name__)

def show_home_page():

return render_template("home.html")

def get_random_element():

# <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!!

return r_e

@app.route('/')

def server():

return show_home_page()

@app.route('/element', methods=['POST', 'GET'])

def random():

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

else:

print "Else:", p

return render_template('random.html', element=p)

return show_home_page()

if __name__ == '__main__':

app.run()

网友答案:

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 random().

@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 random().

Fix this by renaming the function, perhaps call it element() since that is the route name.

相关阅读:
Top