Flask 路由返回 500 错误

Flask routes returning 500 errors

所以我正在尝试将我的 python flask 应用程序部署到 ubuntu AWS EC2 实例。我已经设置 mod_wsgi,配置了虚拟主机设置 virtualenv 并创建了别名来为我的静态文件提供服务。出于某种原因,我无法为我的 api 路由获取我的自定义 url 到 return 的正确信息。我已经尝试了所有搜索过的方法,这是我最后的选择。

#!/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)

这是WSGI文件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

这里是虚拟主机环境

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

这是我的访问日志,它正在创建 wsgi 实例,所以我必须做正确的事情。

[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

这是一个 netstate -plunt 输出

    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 

这是目录结构

    ├── 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

感谢任何帮助。

这是一个从我的个人机器到主机

的curl请求运行
    djove:.ssh djowinz$ curl http://**.*.**.139/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>

这里是 curl 请求 运行 从宿主机到宿主机使用 localhost 的请求。

    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>

事实证明这是我如何实例化 uwsgi 的问题。我从头开始删除了所有内容,并使用 uwsgi 完成了烧瓶安装说明,并且能够使所有内容正常工作。