app.run的Python烧瓶错误

时间:2016-12-30 14:11:27

标签: python flask pythonanywhere

我是Python Flask的新手。 如果没有app.run(),我的Flask_app.py能够运行,但是当我把它放入时显示错误。我目前在pythonanywhere.com上运行

from flask import Flask,jsonify,abort,make_response
import MySQLdb
import MySQLdb.cursors

app = Flask(__name__)
db = MySQLdb.connect(host='venus.mysql.pythonanywhere-services.com',user='venus',passwd='pw',db='venuspp$default',cursorclass=MySQLdb.cursors.DictCursor)

@app.route('/')
def hello_world():
    return 'Hello from bybye!'

@app.route('/KL', methods=['GET'])
def KL():
    curs = db.cursor()
    try:
        curs.execute("SELECT * FROM KL")
        a = curs.fetchall()
    except Exception:
        return 'Error: unable to fetch items'
    #return "hihi"
    return jsonify({'venus': a})

if __name__ == '__main__':
    app.run()

错误如下:

* Running on http://127.0.0.1:5000/
Traceback (most recent call last):
  File "/home/vinus/mysite/flask_app.py", line 49, in <module>
    app.run()
  File "/usr/local/lib/python3.4/dist-packages/flask/app.py", line 772, in run
    run_simple(host, port, self, **options)
  File "/usr/local/lib/python3.4/dist-packages/werkzeug/serving.py", line 710, in run_simple
    inner()
  File "/usr/local/lib/python3.4/dist-packages/werkzeug/serving.py", line 692, in inner
    passthrough_errors, ssl_context).serve_forever()
  File "/usr/local/lib/python3.4/dist-packages/werkzeug/serving.py", line 486, in make_server
    passthrough_errors, ssl_context)
  File "/usr/local/lib/python3.4/dist-packages/werkzeug/serving.py", line 410, in __init__
    HTTPServer.__init__(self, (host, int(port)), handler)
  File "/usr/lib/python3.4/socketserver.py", line 430, in __init__
    self.server_bind()
  File "/usr/lib/python3.4/http/server.py", line 133, in server_bind
    socketserver.TCPServer.server_bind(self)
  File "/usr/lib/python3.4/socketserver.py", line 444, in server_bind
    self.socket.bind(self.server_address)
OSError: [Errno 98] Address already in use
  1. 如果没有app.run(),我的脚本是否正确且健壮?我会每天更新我的数据库。我不希望它破裂。
  2. 我该怎么做才能纠正错误?

2 个答案:

答案 0 :(得分:3)

Pythonanywhere通过wsgi配置运行flask app,因此它会为你运行,如果你检查/var/www/username_pythonanywhere_com_wsgi.py,你会看到如下所示:

import sys

# add your project directory to the sys.path
project_home = u'/home/username/project_name'
if project_home not in sys.path:
    sys.path = [project_home] + sys.path

# import flask app but need to call it "application" for WSGI to work
from yourappmodule import app as application
#app.py
from flask import Flask

app = Flask(__name__)

@app.route('/')
def hello_world():
    return 'Hello!'

因此,如果没有app.run()

,您的应用程序将完美运行

答案 1 :(得分:0)

我建议检查: How to Run a Flask Application

,如果案例坚持不遵循“烧瓶运行”路径,请检查: debug Flask server inside Jupyter Notebook

(此材料已经在Stack Overflow上了,只需将链接放在此处以帮助谁在寻找答案)。