lundi 27 avril 2015

Flask routes returning 500 errors

So I'm attempting to deploy my python flask app to a ubuntu AWS EC2 instance. I've setup mod_wsgi, configured the virtual host setup a virtualenv and created alias to server my static files. For some reason I can't get my custom url for my api routes to return the correct information. I've tried everything I've searched everywhere this is my last option.

#!/usr/bin/env python
import threading
import subprocess
import uuid
import json
from celery import Celery
from celery.task import Task
from celery.decorators import task
from celery.result import AsyncResult
from scripts.runTable import runTable
from scripts.getCities import getCities
from scripts.pullScript import createOperation
from flask import Flask, render_template, make_response, url_for, abort, jsonify, request, send_from_directory, Response
app = Flask(__name__)
app.config['CELERY_BROKER_URL'] = 'amqp://guest:guest@localhost:5672//'
app.config['CELERY_RESULT_BACKEND'] = 'amqp'
app.config['CELERY_TASK_RESULT_EXPIRES'] = 18000
app.config['CELERY_ACCEPT_CONTENT'] = ['json']
app.config['CELERY_TASK_SERIALIZER'] ='json'
app.config['CELERY_RESULT_SERIALIZER'] = 'json'

operation = createOperation()
cities = getCities()
table = runTable()
value = ''
state = ''

celery = Celery(app.name, backend=app.config['CELERY_RESULT_BACKEND'], broker=app.config['CELERY_BROKER_URL'])
celery.conf.update(app.config)

@task(bind=True)
def pull_async_data(self, data):
    global state
    state = pull_async_data.request.id
    operation.runSequence(data)


@app.route('/api/v1/getMapInfo', methods=['GET'])
def map():
    mp = operation.getMapData()
    resp = Response(mp, status=200, mimetype="application/json")
    return resp


@app.route('/api/v1/getTable', methods=['GET'])
def tables():
    tb = table.getTableInfo()
    resp = Response(tb, status=200, mimetype="application/json")
    return resp


##Get states from the DB
@app.route('/api/v1/getStates', methods=['GET'])
def states():
    st = cities.getStatesFromDB()
    resp = Response(st, status=200, mimetype="application/json")
    return resp


@app.route('/api/v1/getCities', methods=['POST'])
def city():
    data = request.get_json()
    # print data
    ct = cities.getCitiesFromDB(data)
    resp = Response(ct, status=200, mimetype="application/json")
    return resp


@app.route('/api/v1/getQueue', methods=['GET'])
def queue():
    queue = operation.getCurrentQueue()
    resp = Response(queue, status=200, mimetype="application/json")
    return resp



##Checking the status of api progress
@app.route('/api/v1/checkStatus', methods=['GET'])
def status():
    res = pull_async_data.AsyncResult(state).state
    js = json.dumps({'State': res})
    resp = Response(js, status=200, mimetype="application/json")
    return resp


##Perform the pull and start the script
@app.route('/api/v1/pull', methods=['POST'])
def generate():
    global value
    value = json.dumps(request.get_json())
    count = operation.getCurrentQueue(value)
    pull_async_data.apply_async(args=(value, ))
    js = json.dumps({"Operation": "Started", "totalQueue": count})
    resp = Response(js, status=200, mimetype="application/json")
    return resp


##Check main app
if __name__ == "__main__":
    app.run(debug=True)

Here is the WSGI file oakapp.wsgi

#!/usr/bin/python
import sys

activate_this = '/var/www/oakapp/venv/bin/activate_this.py'
execfile(activate_this, dict(__file__=activate_this))

sys.path.append('/var/www/oakapp')

print sys.path.insert(0, '/var/www/oakapp/scripts')

from app import app as application

Here is the virtualhost environment

    <VirtualHost *:80>
            ServerName oakapp.com

            DocumentRoot /var/www/oakapp

            Alias /js /var/www/oakapp/js
            Alias /css /var/www/oakapp/css

            WSGIDaemonProcess oakapp user=apps group=ubuntu threads=5
            WSGIScriptAlias / /var/www/oakapp/oakapp.wsgi


            <Directory /var/www/oakapp/>
                    WSGIProcessGroup oakapp
                    WSGIApplicationGroup %{GLOBAL}
                    WSGIScriptReloading On
                    Order allow,deny
                    Allow from all
            </Directory>

            ErrorLog /var/www/oakapp/logs/oakapp_error.log
            LogLevel info
            CustomLog /var/www/oakapp/logs/oakapp_access.log combined
    </VirtualHost>

Here is my access log, it's creating the wsgi instance, so I have to be doing something right.

[Tue Apr 28 04:30:03.705360 2015] [:info] [pid 2611:tid 140512828155776] mod_wsgi (pid=2611): Attach interpreter ''.
[Tue Apr 28 04:30:11.704865 2015] [:info] [pid 2611:tid 140512695293696] [remote 72.219.180.235:10929] mod_wsgi (pid=2611, process='oakapp', application=''): Loading WSGI script '/var/www/oakapp/oakapp.wsgi'.
[Tue Apr 28 04:30:11.705804 2015] [:error] [pid 2611:tid 140512695293696] None

Here is a netstate -plunt output

    Active Internet connections (only servers)
    Proto Recv-Q Send-Q Local Address           Foreign Address         State       PID/Program name
    tcp        0      0 0.0.0.0:22              0.0.0.0:*               LISTEN      1062/sshd       
    tcp        0      0 127.0.0.1:3031          0.0.0.0:*               LISTEN      29277/uwsgi     
    tcp        0      0 0.0.0.0:46035           0.0.0.0:*               LISTEN      24222/beam      
    tcp6       0      0 :::22                   :::*                    LISTEN      1062/sshd       
    tcp6       0      0 :::5672                 :::*                    LISTEN      24222/beam      
    tcp6       0      0 :::80                   :::*                    LISTEN      2608/apache2    
    tcp6       0      0 :::4369                 :::*                    LISTEN      24197/epmd      
    udp        0      0 0.0.0.0:17372           0.0.0.0:*                           568/dhclient    
    udp        0      0 0.0.0.0:68              0.0.0.0:*                           568/dhclient    
    udp6       0      0 :::28264                :::*                                568/dhclient 

Here is the directory structure

    ├── app.py
    ├── app.pyc
    ├── css
    │   ├── fonts
    │   │   ├── untitled-font-1.eot
    │   │   ├── untitled-font-1.svg
    │   │   ├── untitled-font-1.ttf
    │   │   └── untitled-font-1.woff
    │   ├── leaflet.css
    │   └── master.css
    ├── js
    │   ├── images
    │   │   ├── layers-2x.png
    │   │   ├── layers.png
    │   │   ├── marker-icon-2x.png
    │   │   ├── marker-icon.png
    │   │   └── marker-shadow.png
    │   ├── leaflet.js
    │   └── main.js
    ├── json
    │   └── states.json
    ├── logs
    │   ├── oakapp_access.log
    │   └── oakapp_error.log
    ├── oakapp.wsgi
    ├── sass
    │   └── master.scss
    ├── scripts
    │   ├── database
    │   │   ├── cities_extended.sql
    │   │   ├── oak.db
    │   │   └── states.sql
    │   ├── getCities.py
    │   ├── getCities.pyc
    │   ├── __init__.py
    │   ├── __init__.pyc
    │   ├── pullScript.py
    │   ├── pullScript.pyc
    │   ├── runTable.py
    │   └── runTable.pyc
    ├── templates
        └── index.html

Any help is appreciated.

Here is a curl request ran from my personal machine to the host machine

    djove:.ssh djowinz$ curl http://ift.tt/1A92wUr
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
    <title>500 Internal Server Error</title>
    <h1>Internal Server Error</h1>
    <p>The server encountered an internal error and was unable to complete your request.  Either the server is overloaded or there is an error in the application.</p>

Here is the curl request ran from the host machine to the host machine using localhost as requested.

    root@ip-172-31-24-66:/var/www/oakapp# curl http://localhost/api/v1/getTable
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
    <title>500 Internal Server Error</title>
    <h1>Internal Server Error</h1>
    <p>The server encountered an internal error and was unable to complete your request.  Either the server is overloaded or there is an error in the application.</p>




Aucun commentaire:

Enregistrer un commentaire