0

I'm currently super stumped. I have a large flask application that I recently deployed to my production ec2 server that's not functioning properly. It works fine in dev/test. It looks like, maybe, apache is hanging. When I first deployed it, it worked a few times. Then, after that I started getting 500 server errors. When I restart apache, it works fine again for a session but the 500 server errors come back. Each time, on a different page of the application. This is reoccurring. How would I go about fixing this? Here's my routes/app.py:

from flask import Flask, render_template,redirect,request,url_for, flash, session
from Index_generator import index_generator
from Yelp_api import request_yelp
from plaid import auth
from search_results import search,search1
from Options import return_data
from datetime import timedelta
import os
import urllib2
import time
from path import path_data
#from writer import create_config_file
import logging
from logging_path import log_dir



logger = logging.getLogger("Routing")
logger.setLevel(logging.INFO)
foodie_log = log_dir()
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %  (message)s')
foodie_log.setFormatter(formatter)
logger.addHandler(foodie_log)

app = Flask(__name__)

app.secret_key = os.urandom(24)
go = path_data()


@app.before_request
def make_session_permanent():
    session.permanent = False
    app.permanent_session_lifetime = timedelta(seconds=300)
#@app.route('/setup',methods=['GET','POST']) 
#def setup():
#   if request.method == 'POST':
#        Username=request.form['username']
#        Password=request.form['password']
#        Port=request.form['port']
#        Host=request.form['host']
#        C_Key=request.form['CONSUMER_KEY']
#        C_Sec=request.form['CONSUMER_SECRET']
#        Tok=request.form['TOKEN']
#        Tok_Sec=request.form['TOKEN_SECRET']
#        clientid=request.form['client_id']
#        Sec=request.form['secret']
#        create_config_file(Username,Password,Port,Host,C_Key,C_Sec,Tok,Tok_Sec,clientid,Sec)
#        return 'complete'
#    elif request.method == 'GET':
#
#        return render_template('setup.html')

@app.route('/')
def home():
    store = index_generator()
    session['store'] = store
    return render_template('home.html')

@app.route('/about')
def about():
  return render_template('about.html')

@app.route('/home_city',methods = ['POST'])
def home_city():
    try:
        CITY=request.form['city']
        store = session.get('store')
        request_yelp(DEFAULT_LOCATION=CITY,data_store=store)
        return render_template('bank.html')
    except Exception as e:
        logger.error(e)
        error = 'Sorry, no results. Is' + ' ' +CITY + ' '+ 'your hometown? If not, try again and if so, we have been made aware of the issue and is working to resolve it'
        return render_template('home.html',error=error)
@app.route('/traveling',methods = ['POST'])
def travel():
    store = session.get('store')
    answer=request.form['Travel']
    if answer == 'yes':
        #time.sleep(2)
        return render_template('destination.html')
    else:
        results_home = search(index=store)
        time.sleep(2)
        return return_data(results_home)


@app.route('/dest_city',methods = ['POST'])
def dest_city():
    store = session.get('store')
    try:
        DESTINATION=request.form['dest_city']
        request_yelp(DEFAULT_LOCATION=DESTINATION,  data_store=store,sourcetype='dest_city')
        results_dest = search1(index=store)
        time.sleep(2)
        return return_data(results_dest)
     except urllib2.HTTPError:
        error = 'Sorry, no results. Is your destination city? If not, try again and if so, we have been made aware of the issue and is working to resolve it'
       return render_template('destination.html',error=error)


@app.route('/bank',methods = ['POST'])
def bank():
   try:
        store = session.get('store')
        print store
        Bank=request.form['Fin_Bank']
        Username=request.form['username']
        Password=request.form['password']
        Test =  auth(account=Bank,username=Username,password=Password,data_store=store)
        if Test == 402 or Test ==401:
            error = 'Invalid credentials'
            return render_template('bank.html',error=error)
        else :
            return render_template('travel.html')

    except:
        logger.error(e)
if __name__ == '__main__':
  app.run(debug=True)
  app.secret_key=os.urandom(24)
Mitch
  • 177
  • 1
  • 6

1 Answers1

2

Not completely sure if this causes your errors but you should definitely change this:

You have to set app.secret_key to a static value rather than os.urandom(24), e.g.:

app.secret_key = "/\xfa-\x84\xfeW\xc3\xda\x11%/\x0c\xa0\xbaY\xa3\x89\x93$\xf5\x92\x9eW}"

With your current code, each worker thread of your application will have a different secret key, which can result in errors or session inconsistency depending on how you use the session object in your application.

redevined
  • 772
  • 2
  • 6
  • 23
  • Thanks Cipher I'll try it. I'm using the session to grab the data store that was created upon page entry for that user so that data generated from other processes in the app can use that same data store for that user. – Mitch Jul 24 '15 at 12:50
  • Don't know about the original poster but I had a similar problem and this was the solution. As always, it makes total sense in retrospect but it was completely baffling when the application threw an error on every third reload. – tomca32 Mar 02 '16 at 14:52