1

Trying to setup a basic flask (Python) app in PyCharm

Below is the basic 'Hello world' app modified with some Python I already know. I changed the return 'Hello world!' to return contacts to try and print out my dictionaries onto the blank page, but I'm getting a 500 server error.

What is my basic mistake?

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

Error

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

Looks like error happened in app.py line 203

try:
    request_started.send(self)
    rv = self.preprocess_request()
    if rv is None:
        rv = self.dispatch_request()
except Exception as e:
Leon Gaban
  • 36,509
  • 115
  • 332
  • 529

2 Answers2

2

You are returning a dictionary; Flask requires you to return a string, a response object or a valid WSGI application. See the response rules.

You could either return a string version of the dictionary, hand the dictionary to a template, or return a JSON response. You didn't state what you expected to be returned, however.

If you just want to see your contacts 'on a blank page', convert the dictionary to a string:

return str(contacts)
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
2

You must return something Flask recognizes as a response from a view. This includes render_template, jsonify, or a custom Response object. In your case it looks like you want to return a JSON object, so use jsonify.

davidism
  • 121,510
  • 29
  • 395
  • 339