Python for Finance: Analyze Big Financial Data

(Elle) #1

session[‘logged_in’] = True


directly log in new user


flash(‘You were sucessfully registered.’)
app.config.update(dict(USERNAME=request.form[‘username’]))
return redirect(url_for(‘show_entries’))
return render_template(‘register.html’, error=error)


@app.route(‘/login’, methods=[‘GET’, ‘POST’])
def login():
”’ Logs in a user. ”’
error = None
if request.method == ‘POST’:
db = get_db()
try:
query = ‘select id from users where name = ? and password = ?’
id = db.execute(query, (request.form[‘username’],
request.form[‘password’])).fetchone()[ 0 ]


fails if record with provided username and password


is not found


session[‘logged_in’] = True
flash(‘You are now logged in.’)
app.config.update(dict(USERNAME=request.form[‘username’]))
return redirect(url_for(‘show_entries’))
except:
error = ‘User not found or wrong password.’
return render_template(‘login.html’, error=error)


@app.route(‘/add’, methods=[‘POST’])
def add_entry():
”’ Adds entry to the TC database. ”’
if not session.get(‘logged_in’):
abort( 401 )
db = get_db()
now = dt.datetime.now()
db.execute(‘insert into comments (comment, user, time) values (?, ?, ?)’,
[request.form[‘text’], app.config[‘USERNAME’], str(now)[:- 7 ]])
db.commit()
flash(‘Your comment was successfully added.’)
return redirect(url_for(‘show_entries’))


@app.route(‘/logout’)
def logout():
”’ Logs out the current user. ”’
session.pop(‘logged_in’, None)
flash(‘You were logged out’)
return redirect(url_for(‘show_entries’))


main routine


if name == ‘main’:
init_db() # comment out if data in current


TC database is to be kept


app.run()


SECURITY

Although the example in this section illustrates the basic design of a web application in Python with Flask, it

barely addresses security issues, which are of paramount importance when it comes to web applications.

However, Flask and other web frameworks provide complete tool sets to tackle typical security issues (e.g.,

encryption) with due diligence.

Templating


Basically, templating with Flask (Jinja2) works similarly to simple string replacements


in Python: you have a basic string indicating where to replace what and some data to be


inserted into the string object. Consider the following examples:


In  [ 77 ]: ‘%d,    %d, %d’ %   ( 1 ,    2 ,     3 )
Out[77]: ‘1, 2, 3’
In [ 78 ]: ‘{}, {}, {}’.format( 1 , 2 , 3 )
Free download pdf