Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass parameters between flask @app.route('/page')

I am trying to pass the value i get from Random() to Help() but it returns as AttributeError: 'NoneType' object has no attribute 'app'.

from flask import Flask, request, render_template
from random import randint

@app.route('/help')
def Help(Random):
   PassingRandom = Random

   return render_template("help.html", PassingRandom=PassingRandom)

def Random():
   Value = randint(0,100)
   return Value

MyValue = Random()

if __name__ == "__main__":
   Help(MyValue)
   app.run(debug=True)

Is their a way within flask to pass in the parameter without returning the error, preferably without using globals.

like image 939
JayE Avatar asked Oct 22 '17 15:10

JayE


2 Answers

You can either allow the user to pass the value to the function via the URL, or you can call Random inside Help:

@app.route('/help/<random>')
def Help(random):
    return render_template("help.html", PassingRandom=random)

Or, by calling the function Random in Help:

@app.route('/help')
def Help():
   PassingRandom = Random()
   return render_template("help.html", PassingRandom=PassingRandom)
like image 109
Ajax1234 Avatar answered Sep 27 '22 22:09

Ajax1234


Whoa... I'd strongly advise on going through a few tutorials on Flask- But just to give a quick explanation.

First off, you never declared your app.

Secondly, you're not supposed to (generally) call your @app.route function directly. The general idea is that you reach the function through going through a url (in your case /help).

If you want the same random value throughout your whole app, then yes, a global variable is the answer. If you want it to change every time you access /help, just call random from there.

By the way, just a bit of PEP8 to brighten the day- function/variable names should be lowercase, and don't use names that are the same as module names (e.g. Random)

like image 42
maor10 Avatar answered Sep 27 '22 23:09

maor10