Python for Finance: Analyze Big Financial Data

(Elle) #1

register:


@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)

Once users have registered or logged in again, they should be able to add comments in the


chat room. The function add_entry stores the comment text, the username of the user who


commented, and the exact time (to the second) of the posting. The function also checks


whether the user is logged in or not:


@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’))

Finally, to end the session, the user must log out. This is what the function logout


supports:


@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’))

If we want to run the Python script as a standalone application we should add the


following lines, which make sure that a server is fired up and that the application is


served:


#   main    routine
if __name__ == ‘__main__’:
init_db() # comment out if data in current
# TC database is to be kept
app.run()

Putting all these pieces together, we end up with the Python script shown as Example 14-


2.


Example 14-2. Python script embodying the core of the Tradechat application


Tradechat



A simple example for a web-based chat room


based on Flask and SQLite3.


Free download pdf