nmh
nmh

Reputation: 501

Printing except messages in flask templates via jinja2

I've create a function to connect to a db that prints a 'failure to connect to db' message if no connection is made:

  def connectToDB():
        connectionString = 'dbname=reportingdb1 user=red_gui password=RadnfgoInd host=10.100.51.42'
  try:
     return psycopg2.connect(connectionString)
  except:
     print ("Failure to connect to db")

In my views.py files in the index section, this function is called straight away and in my testing environment prints the except failure statement into my terminal when I deliberately use the wrong credentials for the db (for testing purposes).

 ####Index Page
@app.route('/', methods=['GET', 'POST'])
@app.route('/index', methods=['GET', 'POST'])
def index():
          connectToDB()
          form = StaffNames()
          if form.validate_on_submit():
                  return redirect('/results')
          return render_template('index.html',title='Search Page',form=form)

My problem is, I want this message to print out on the web page. I've tried using return instead of print and that hasn't worked. I've also tried attempting to store the except message in a variable, then in my templates/index.html file, call it through jinja2 curly brackets.For examples I tried: in views.py

except:
     noconnect = "Failure to connect to db"

then in my index.html:

{{ noconnect }}

But this too hasn't worked. What would be the best practice to do this? Thanks

Upvotes: 0

Views: 1091

Answers (2)

Dušan Maďar
Dušan Maďar

Reputation: 9909

Simplify connectToDB so it only connects to the DB and nothing else.

def connectToDB():
    connectionString = 'dbname=reportingdb1 user=red_gui password=RadnfgoInd host=10.100.51.42'
    psycopg2.connect(connectionString)

Handle any potential exception in the view (but be aware that catching all exceptions is not a good practice).

 ####Index Page
@app.route('/', methods=['GET', 'POST'])
@app.route('/index', methods=['GET', 'POST'])
def index():
    exception = None
    try:
        connectToDB()
    except:
        exception = 'Failure to connect to db'

    form = StaffNames()
    if not exception:
        if form.validate_on_submit():
            return redirect('/results')

    return render_template('index.html',title='Search Page', form=form, exception=exception)

Place {{ exception }} somewhere in your index.html

Upvotes: 1

nicorellius
nicorellius

Reputation: 4053

Web frameworks generally require objects to be passed via context to the views and templates. You have to pass in the objects in the render_template:

. . .

error = connectToDB()

return render_template('index.html', title='Search Page',
                       form=form, error=error)

Then in your template, use: {{ error }}

Another way to do this that is more Django-like is to create a dictionary for your data:

error = 'error message'
test = 'test'

. . .

data = {
    'error': error,
    'test': test
}

Then return your render_template like so:

return render_template('index.html', title='Search Page',
                       form=form, **data)

The double stars make it so you can still do this: {{ error }}. Otherwise, you will have to do this: {{ data.error }}

Upvotes: 0

Related Questions