0
votes

I'm using pythonanywhere to receive texts via Twilio, and everytime I send a text back (POST request) I'm getting a 502 Bad Gateway Error. See below for my code.

import requests
import time
import json
from datetime import datetime
from datetime import datetime
import pytz
from pytz import timezone
from twilio.rest import Client
from twilio.http.http_client import TwilioHttpClient
import os
from flask import Flask, request
from twilio import twiml


app = Flask(__name__)


proxy_client = TwilioHttpClient(proxy={'http': os.environ['http_proxy'], 'https': os.environ['https_proxy']})
client = Client(account_sid, auth_token,http_client=proxy_client)

@app.route('/sms', methods=['POST'])
def sms():
    print('test')
    number = request.form['From']
    message_body = request.form['Body']
    resp = twiml.Response()
    resp.message("hi")
    return str(resp)

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

And this is the error I'm gettingenter image description here

1
There are a number of things that can cause 502s. There is a help page in the PythonAnywhere help pages that covers how to start diagnosing the problem.Glenn

1 Answers

0
votes

The problem is likely that you are asking Flask to retrieve content from the body as multipart/form-data that may not exist.

Try changing request.form['From'] to request.form.get('From') which will not raise a KeyError if the key is missing.

Another option is to wrap your function (temporarily) into a try/except block and print out the traceback so you can at least find out what is happening on the server from stdout and debug the issue that way.