简体   繁体   中英

Flask SMS with twilio error

from flask import *
from twilio import twiml
from twilio.rest import TwilioRestClient

from flask import render_template
import os

#Pull in configuration from system environment variables
TWILIO_ACCOUNT_SID = os.environ.get('Axxxxxx')
TWILIO_AUTH_TOKEN = os.environ.get('Sxxxxxxxxx')
TWILIO_NUMBER = os.environ.get('xxxxxxx')

# create an authenticated client that can make requests to Twilio for your
# account.

#client = TwilioRestClient(account='Axxxxx', token'sxxxxxxxx')

#create a flask web app
app = Flask(__name__)

client = TwilioRestClient(account='Axxxxx', token='Sxxxxx')

@app.route('/')
def homepage():
    return render_template('index.html')

#Handling a post request to send text messages.

@app.route('/message', methods=['POST', 'GET'])
def message():
     # Send a text message to the number provided
    if request.method == 'POST':

        message = client.sms.messages.create(to=request.form['Phone_number'],
                                         from_=TWILIO_NUMBER,
                                         body=request.form['body'])

    return render_template('message.html')


if __name__ == '__main__':
    # Note that in production, you would want to disable debugging
    app.run(debug=True)

I am using flask. When i input the number and the text message it gives me this error

Method Not Allowed
The method is not allowed for the requested URL.

You're posting to the wrong endpoint. Your form should look like this:

<!DOCTYPE html>
<html lang="en">
    <head>
        <title>Send an SMS</title>
    </head>
    <body>
        <form action="/message" method="POST">
            Cell phone number: <input name="phone_number" type="text" />
            Text in here: <input name="body" type="text" />
            <button type="submit">Send Text</button>
        </form>
        </script>
    </body>
</html>

(Above, action was changed from / to /message .)


Note: if this is a template run through flask.render_template , you should change

<form action="/message" method="POST">

to

<form action="{{ url_for('message') }}" method="POST">

This is a more sustainable way to use urls in flask, and it will reduce your overhead if you ever need to change the value.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM