查询数据库发送短信

时间:2015-08-10 19:24:46

标签: flask twilio flask-sqlalchemy

我正在尝试使用Flask,Twilio和SqlAlchemy构建一个简单的SMS应用程序。当有人发送我的Twilio号码时,它会填充数据库,但我无法查询Postgres数据库以填充“到”字段。这是代码。非常感谢任何帮助。

from flask import Flask, render_template, request
from flask.ext.sqlalchemy import SQLAlchemy
import twilio.twiml
from twilio.rest import TwilioRestClient
from sqlalchemy.sql import select

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql://localhost/twilio_sms'
db = SQLAlchemy(app)
account_sid = ""
auth_token = ""

# Database model
class User(db.Model):
    __tablename__ = "users"
    id = db.Column(db.Integer, primary_key=True)
    phone = db.Column(db.String(120), unique=True)

    def __init__(self, phone):
        self.phone = phone

# The script that processes the incoming phone numbers
@app.route("/", methods=['GET', 'POST'])
def sms():
    phone = None
    if request.method == 'POST':
        phone = request.values.get('From')
        if not db.session.query(User).filter(User.phone == phone).count():
            reg = User(phone)
            db.session.add(reg)
            db.session.commit()
            resp = twilio.twiml.Response()
            with resp.message("Let's dance the night away!") as m:
                m.media("http://i.giphy.com/2lxG3ySjtbpBe.gif")
            return str(resp)

# Renders the form for message submission
@app.route("/form")
def form():
    return render_template('send.html')

这是我遇到麻烦的部分。

# The script that publishes the message
@app.route("/send", methods=['GET', 'POST'])
def send():
    phone = None
    client = TwilioRestClient(account_sid, auth_token)
    for users in db.session.query(User).filter(User.phone == phone):
        print users #Inserted to text whether the query returned any value
        #message = client.messages.create(to="users", from_="+twilio_number", body=request.form['Message'])
        #return render_template('success.html')

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

2 个答案:

答案 0 :(得分:1)

我终于想通了......我必须使用query将数字转换为列表,然后将其作为字符串传递。

@app.route("/send", methods=['GET', 'POST'])
def send():
    users = User.query.order_by(User.phone)
    client = TwilioRestClient(account_sid, auth_token)
    for user in users:
        message = client.messages.create(to=str(user), from_="+12125550433", body=request.form['Message'])
    return render_template('success.html')

答案 1 :(得分:0)

send()函数中,您正在分配phone = None,然后根据该功能过滤数据库查询。

我相信您希望在请求中抓取sms()中的上述数字。