【问题标题】:basic flask program returning 500 server error [duplicate]基本烧瓶程序返回500服务器错误[重复]
【发布时间】:2014-01-15 11:21:52
【问题描述】:

尝试在 PyCharm 中设置一个基本的烧瓶 (Python) 应用

下面是使用我已经知道的一些 Python 修改的基本“Hello world”应用程序。 我将返回 'Hello world!' 更改为 return contacts 以尝试将我的字典打印到空白页上,但出现 500 服务器错误。

我的基本错误是什么?

from flask import Flask

app = Flask(__name__)


@app.route('/')
def hello_world():

    contacts = dict()
    johnSmith = dict()
    jasonBourne = dict()
    lisbethSalander = dict()

    johnSmith['label'] = 'John Smith'
    johnSmith['phone'] = '(222) 333-4444'
    johnSmith['email'] = 'john@johnsmith.net'

    jasonBourne['label'] = 'Jason Bourne'
    jasonBourne['phone'] = '(333) 444-5555'
    jasonBourne['email'] = 'jason@cia.gov'

    lisbethSalander['label'] = 'Lisbeth Salander'
    lisbethSalander['phone'] = '(444) 555-6666'
    lisbethSalander['email'] = 'lsalander@gmail.com'

    contacts['1'] = johnSmith
    contacts['2'] = jasonBourne
    contacts['3'] = susanBoom

    print contacts
    return contacts
    # return 'Hello world!'

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

错误

Internal Server Error
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

app.py 第 203 行似乎发生了错误

try:
    request_started.send(self)
    rv = self.preprocess_request()
    if rv is None:
        rv = self.dispatch_request()
except Exception as e:

【问题讨论】:

    标签: python flask return


    【解决方案1】:

    您必须返回 Flask 识别为视图响应的内容。这包括render_templatejsonify 或自定义Response 对象。在您的情况下,您似乎想要返回一个 JSON 对象,因此请使用 jsonify

    【讨论】:

      【解决方案2】:

      您正在返回字典; Flask 要求您返回一个字符串、一个响应对象或一个有效的 WSGI 应用程序。请参阅response rules

      您可以返回字典的字符串版本,将字典交给模板,或者返回 JSON 响应。但是,您没有说明希望返回什么。

      如果您只想“在空白页上”查看您的联系人,请将字典转换为字符串:

      return str(contacts)
      

      【讨论】:

        猜你喜欢
        • 2015-10-15
        • 2015-12-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-08-06
        • 2021-01-21
        • 2015-03-27
        • 1970-01-01
        相关资源
        最近更新 更多