Internal Server Error when deploying simple Flask app onto GCloud

Question:

When I run this app locally, it works fine. In the cloud, I get the error below. I think it’s my yaml file. As a side note, if there is anything in the logs I should not be sharing, I’d appreciate knowing. Thank you!

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.

My main.py file:

from flask import Flask
import requests

app = Flask(__name__)

@app.route("/")
def data():
    response = requests.request("GET", "https://jsonplaceholder.typicode.com/posts")
    data = response.json()
    return(data)

returned_data = data()

#for i, item in enumerate(returned_data):

#    userID = item.get("userID", None)
#    id = item.get("id", None)
#    title = item.get("id", None)

#    print(userID,id,title)
    
if __name__ == "__main__":
    app.run(host='127.0.0.1', port=8080, debug=True)

My app.yaml file:

runtime: python39
entrypoint: gunicorn -b :$PORT -w 2 main:app

My app.yaml file:

runtime: python39
entrypoint: gunicorn -b :$PORT -w 2 main:app

and my requirements.txt

requests
Flask==2.1.0
gunicorn

Here are the logs:

{
insertId: "63604ebd000c8d09af3f2e13"
labels: {
clone_id: "00c61b114F0e8fb053d8ebee071db45f9aa9ec947906c0029f3b30b22f414ae90868c30c989456619d667de0e08ca37e2598be2ed37ad5d3b"
}
logName: "projects/XXXX/logs/%2Fvar%2Flog%2Fgoogle_init.log"
receiveTimestamp: "2022-10-31T22:39:58.016186551Z"
resource: {
labels: {
module_id: "default"
project_id: "XXXX"
version_id: "20221031t161907"
zone: "us6"
}
type: "gae_app"
}
textPayload: "[start] 2022/10/31 22:39:57.821966 Start program failed: termination triggered by nginx exit"
timestamp: "2022-10-31T22:39:57.822537Z"
}

Asked By: Clay Campbell

||

Answers:

Your code is producing a list and trying to return a list as you’re doing in flask will lead to the error –

TypeError: The view function did not return a valid response. The return type must be a string, dict, tuple, Response instance, or WSGI callable, but it was a list.

To fix the error, modify your code to use jsonify

from flask import Flask, jsonify
import requests

app = Flask(__name__)

@app.route("/")
def data():
    response = requests.request("GET", "https://jsonplaceholder.typicode.com/posts")
    data = response.json()
    # return(data)
    return jsonify(data) # New; jsonify the list before it's returned

#returned_data = data() This line also causes an error

Answered By: NoCommandLine
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.