Flask无法在WSGI mod上导入Python文件

时间:2013-12-11 12:03:22

标签: python flask wsgi

我正在使用Flask构建移动应用程序。在为大型应用程序设置Flask结构之前,它工作正常。像这样http://flask.pocoo.org/docs/patterns/packages/

当我有一个python文件时,WSGI工作得很好。但是,导入python文件后,WSGI无法正常工作。

这是目录结构。

/home
  /bridge
    index.py
    apis.wsgi
    /apis
      __init__.py
      settings.py

Index.py

from apis import app
app.run(host='0.0.0.0',debug=True)

apis.wsgi

import sys
sys.path.insert(0,'/home/bridge/apis')
from apis import app as application

初始化的.py

from flask import Flask
app = Flask(__name__)

import apis.settings

settings.py

from flask import Flask
import os
import sys
from flask import render_template, request, jsonify, redirect, url_for, send_file, Response, make_response

@app.route('/apis/settings/aboutus')
def aboutus():
    return render_template('settings/aboutus.html')

运行后运行 #python index.py Domain.com/apis/settings/aboutus正常运行。

但是,如果我打开WSGI,则无法加载页面并显示此错误。

Internal Server Error

当然,我检查了错误日志。

[error] [client 14.63.12.134] mod_wsgi (pid=2138): Exception occurred processing WSGI script '/home/bridge/index.wsgi'.
[error] [client 14.63.12.134] Traceback (most recent call last):
[error] [client 14.63.12.134]   File "/home/bridge/index.wsgi", line 3, in <module>
[error] [client 14.63.12.134]     from index import app as application
[error] [client 14.63.12.134]   File "/home/bridge/index.py", line 2, in <module>
[error] [client 14.63.12.134]     app.run(host='0.0.0.0',debug=True)
[error] [client 14.63.12.134]   File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 772, in run
[error] [client 14.63.12.134]     run_simple(host, port, self, **options)
[error] [client 14.63.12.134]   File "/usr/local/lib/python2.7/dist-packages/werkzeug/serving.py", line 706, in run_simple
[error] [client 14.63.12.134]     test_socket.bind((hostname, port))
[error] [client 14.63.12.134]   File "/usr/lib/python2.7/socket.py", line 224, in meth
[error] [client 14.63.12.134]     return getattr(self._sock,name)(*args)
[error] [client 14.63.12.134] error: [Errno 98] Address already in use

我收到了这些错误。

你能看出问题是什么吗?谢谢。

2 个答案:

答案 0 :(得分:4)

index.py更正为:

from apis import app

if __name__ == "__main__":
    app.run(host='0.0.0.0',debug=True)

因为wsgi服务器会调用您的app,所以您不需要再次调用app.run,否则会引发“已在使用的地址”错误。所以我们使用if __name__ == "__main__":来包装app.run(...)flask docs也指出了这个伎俩。

答案 1 :(得分:0)

我只是解决了这个问题。

index.py

中的

from apis import app
#app.run(host='0.0.0.0',debug=True)

我删除了运行命令,但它确实有效。当WSGI mod尝试运行它时,app.run命令已经运行。