Question: Python code: # all the imports import os import sqlite3 from flask import Flask, request, session, g, redirect, url_for, abort, render_template, flash app =

Python code:

# all the imports

import os

import sqlite3

from flask import Flask, request, session, g, redirect, url_for, abort, \

render_template, flash

app = Flask(__name__) # create the application instance :)

app.config.from_object(__name__) # load config from this file , flaskr.py

# Load default config and override config from an environment variable

app.config.update(dict(

DATABASE=os.path.join(app.root_path, 'flaskr.db'),

SECRET_KEY='development key',

USERNAME='admin',

PASSWORD='default'

))

app.config.from_envvar('FLASKR_SETTINGS', silent=True)

def connect_db():

"""Connects to the specific database."""

rv = sqlite3.connect(app.config['DATABASE'])

rv.row_factory = sqlite3.Row

return rv

def get_db():

"""Opens a new database connection if there is none yet for the

current application context.

"""

if not hasattr(g, 'sqlite_db'):

g.sqlite_db = connect_db()

return g.sqlite_db

@app.teardown_appcontext

def close_db(error):

"""Closes the database again at the end of the request."""

if hasattr(g, 'sqlite_db'):

g.sqlite_db.close()

def init_db():

db = get_db()

with app.open_resource('schema.sql', mode='r') as f:

db.cursor().executescript(f.read())

db.commit()

@app.cli.command('initdb')

def initdb_command():

"""Initializes the database."""

init_db()

print('Initialized the database.')

@app.route('/')

def show_entries():

db = get_db()

cur = db.execute('select title, text from entries order by id desc')

entries = cur.fetchall()

return render_template('show_entries.html', entries=entries)

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

def topical():

db = get_db()

entries=[]

if request.method == 'POST':

session.whattopic = request.form['topic']

if not session.whattopic :

flash("No topic provided")

else:

cur = db.execute('select title, text from entries where title=?',

[session.whattopic])

entries = cur.fetchall();

return render_template('show_topic.html', whatshow=entries)

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

def add_entry():

if not session.get('logged_in'):

abort(401)

db = get_db()

db.execute('insert into entries (title, text) values (?, ?)',

[request.form['title'], request.form['text']])

db.commit()

flash('New entry was successfully posted')

return redirect(url_for('show_entries'))

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

def login():

error = None

if request.method == 'POST':

if request.form['username'] != app.config['USERNAME']:

error = 'Invalid username'

elif request.form['password'] != app.config['PASSWORD']:

error = 'Invalid password'

else:

session['logged_in'] = True

flash('You were logged in')

return redirect(url_for('show_entries'))

return render_template('login.html', error=error)

@app.route('/logout')

def logout():

session.pop('logged_in', None)

flash('You were logged out')

return redirect(url_for('show_entries')

layout.html:

Flaskr

{% if not session.logged_in %} log in {% else %} log out {% endif %}

{% for message in get_flashed_messages() %}

{{ message }}

{% endfor %} {% block body %}{% endblock %}

login.html

{% extends "layout.html" %} {% block body %}

Login

{% if error %}

Error: {{ error }}{% endif %}

Username:

Password:

{% endblock %}

show_entries.html:

{% extends "layout.html" %} {% block body %} {% if session.logged_in %}

Title:

Text:

{% endif %}

{% for entry in entries %}

{{ entry.title }}

{{ entry.text|safe }} {% else %}

Unbelievable. No entries here so far {% endfor %}

{% endblock %}

show_topic.html:

{% extends "layout.html" %} {% block body %}

Topic to retreive:

{% for entry in entries %}

{{ entry.title }}

{{ entry.text|safe }} {% else %}

Unbelievable. Nothing on that topic so far {% endfor %}

{% endblock %}

A) Consider the jinja coded expression that actually produces html for the flashed message "No topic provided." On what line of the file does this code appear?

B) According to the python code, one of the tag element attribute values is incorrect in the show_topic template. (You have to figure out which tag and attribute). What is the correct attribute value according to the python code?

C) Several flask module names are available globally to the templates. (These are actually proxies, but they act like globals, so we'll call them global for convenience) Other than session object, what is the other global that is used in the show_topic template?

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!