Home > Mobile >  Flask POST Request Response With Processed Request [duplicate]
Flask POST Request Response With Processed Request [duplicate]

Time:10-06

I am trying to send a webhook with a json to my flask app- it then takes the key values and inputs it to my search engine and should reply back with the results and 200 (code that it was successful) my code looks like this:

from flask import Flask, request, abort
from Webhooks.TGSearchEngine import TGSearch

app = Flask(__name__)

@app.route('/', methods=['POST'])
def webhook():
    sys.stdout.flush()
    if request.method == 'POST':
        reply = request.json['reply']
        query = request.json['query']
        channel = request.json['channel']
        messageid = request.json['id']
        return TGSearch.main(reply, query, channel, messageid), 200
    else:
        abort(400)

But I get TypeError( TypeError: The view function did not return a valid response. The function either returned None or ended without a return statement.

My TGSearch.main() module takes the vars and returns a dictionary with the results. I don't understand why it would throw this error. Any ideas?

CodePudding user response:

If you are sure that TGSearch.main(reply, query, channel, messageid), 200 doesn't return None value, you had to convert the result of the response to a valid response object.

You can pass the result in a variable to a template rendering:

response = TGSearch.main(reply, query, channel, messageid), 200
return render_template("example.html", response)

You can convert the response into a JSON:

from flask.json import jsonify
result = TGSearch.main(reply, query, channel, messageid), 200
response = jsonify(result)

Or in the case you are getting a tuple, you can access separate values and make them a string.

result = TGSearch.main(reply, query, channel, messageid), 200 // "Message", 200
return str(result[0])   str(result[1])

CodePudding user response:

Flask must always return something. In your else statement you should add a return.

Note: you specified methods=['POST'] in your route, so the only method allowed will be POST, I don't think it's necessary to check if request.method == 'POST'

  • Related