├── MANIFEST.in ├── docs ├── requirements.txt ├── _static │ └── telephone.png ├── index.rst ├── Makefile ├── make.bat └── conf.py ├── setup.cfg ├── .travis.yml ├── README.md ├── .gitignore ├── LICENSE ├── setup.py ├── test_flask_twilio.py ├── example.py └── flask_twilio.py /MANIFEST.in: -------------------------------------------------------------------------------- 1 | include test_flask_twilio.py 2 | -------------------------------------------------------------------------------- /docs/requirements.txt: -------------------------------------------------------------------------------- 1 | flask-sphinx-themes 2 | sphinx 3 | -------------------------------------------------------------------------------- /docs/_static/telephone.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/lpsinger/flask-twilio/HEAD/docs/_static/telephone.png -------------------------------------------------------------------------------- /setup.cfg: -------------------------------------------------------------------------------- 1 | [aliases] 2 | test = pytest 3 | 4 | [bdist_wheel] 5 | universal=1 6 | 7 | [coverage:run] 8 | source = flask_twilio 9 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | sudo: false 2 | language: python 3 | python: 4 | - "2.7" 5 | - "3.4" 6 | - "3.5" 7 | - "3.6" 8 | script: python setup.py test 9 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # flask-twilio 2 | Make Twilio voice/SMS calls with Flask 3 | 4 | [![Build Status](https://travis-ci.org/lpsinger/flask-twilio.svg?branch=master)](https://travis-ci.org/lpsinger/flask-twilio) 5 | [![Doc Status](https://readthedocs.org/projects/flask-twilio/badge/?version=latest)](http://flask-twilio.readthedocs.io/en/latest/) 6 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | 5 | # C extensions 6 | *.so 7 | 8 | # Distribution / packaging 9 | .Python 10 | env/ 11 | build/ 12 | develop-eggs/ 13 | dist/ 14 | downloads/ 15 | eggs/ 16 | .eggs/ 17 | lib/ 18 | lib64/ 19 | parts/ 20 | sdist/ 21 | var/ 22 | *.egg-info/ 23 | .installed.cfg 24 | *.egg 25 | .pytest_cache 26 | 27 | # PyInstaller 28 | # Usually these files are written by a python script from a template 29 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 30 | *.manifest 31 | *.spec 32 | 33 | # Installer logs 34 | pip-log.txt 35 | pip-delete-this-directory.txt 36 | 37 | # Unit test / coverage reports 38 | htmlcov/ 39 | .tox/ 40 | .coverage 41 | .coverage.* 42 | .cache 43 | nosetests.xml 44 | coverage.xml 45 | *,cover 46 | 47 | # Translations 48 | *.mo 49 | *.pot 50 | 51 | # Django stuff: 52 | *.log 53 | 54 | # Sphinx documentation 55 | docs/_build/ 56 | 57 | # PyBuilder 58 | target/ 59 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Copyright (c) 2015 by Leo Singer. 2 | 3 | Some rights reserved. 4 | 5 | Redistribution and use in source and binary forms, with or without 6 | modification, are permitted provided that the following conditions are 7 | met: 8 | 9 | * Redistributions of source code must retain the above copyright 10 | notice, this list of conditions and the following disclaimer. 11 | 12 | * Redistributions in binary form must reproduce the above 13 | copyright notice, this list of conditions and the following 14 | disclaimer in the documentation and/or other materials provided 15 | with the distribution. 16 | 17 | * The names of the contributors may not be used to endorse or 18 | promote products derived from this software without specific 19 | prior written permission. 20 | 21 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 22 | "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 23 | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 24 | A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 25 | OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 26 | SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 27 | LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 28 | DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 29 | THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 30 | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 31 | OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 32 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | """ 2 | Flask-Twilio 3 | ------------- 4 | 5 | Make Twilio voice/SMS calls with Flask 6 | """ 7 | import sys 8 | 9 | from setuptools import setup 10 | exec(open('flask_twilio.py').readline()) 11 | 12 | setup_requires = [] 13 | if {'pytest', 'test', 'ptr'}.intersection(sys.argv): 14 | setup_requires.append('pytest-runner') 15 | if {'build_sphinx'}.intersection(sys.argv): 16 | setup_requires.extend(['sphinx', 'flask-sphinx-themes']) 17 | 18 | setup( 19 | name='Flask-Twilio', 20 | version=__version__, 21 | url='https://github.com/lpsinger/flask-twilio', 22 | license='BSD', 23 | author='Leo Singer', 24 | author_email='leo.singer@ligo.org', 25 | description='Make Twilio voice/SMS calls with Flask', 26 | long_description=__doc__, 27 | py_modules=['flask_twilio'], 28 | zip_safe=False, 29 | include_package_data=True, 30 | platforms='any', 31 | install_requires=[ 32 | 'itsdangerous', 33 | 'flask>=0.9', 34 | 'six', 35 | 'twilio>=6.0.0' 36 | ], 37 | setup_requires=setup_requires, 38 | tests_require=[ 39 | 'pytest', 40 | ], 41 | classifiers=[ 42 | 'Environment :: Web Environment', 43 | 'Intended Audience :: Developers', 44 | 'License :: OSI Approved :: BSD License', 45 | 'Operating System :: OS Independent', 46 | 'Development Status :: 2 - Pre-Alpha', 47 | 'Programming Language :: Python', 48 | 'Programming Language :: Python :: 2.7', 49 | 'Programming Language :: Python :: 3.4', 50 | 'Programming Language :: Python :: 3.5', 51 | 'Programming Language :: Python :: 3.6', 52 | 'Topic :: Internet :: WWW/HTTP :: Dynamic Content', 53 | 'Topic :: Software Development :: Libraries :: Python Modules', 54 | 'Topic :: Communications :: Telephony' 55 | ] 56 | ) 57 | -------------------------------------------------------------------------------- /docs/index.rst: -------------------------------------------------------------------------------- 1 | Flask-Twilio Documentation 2 | ========================== 3 | 4 | Flask-Twilio Installation 5 | ------------------------- 6 | 7 | Install the extension by running pip:: 8 | 9 | $ pip install Flask-Twilio 10 | 11 | 12 | Set Up 13 | ------ 14 | 15 | Flask-Twilio can be initialized by first creating the application and then 16 | creating the :py:class:`flask_twilio.Twilio` instance:: 17 | 18 | from flask import Flask 19 | from flask_twilio import Twilio 20 | 21 | app = Flask(__name__) 22 | twilio = Twilio(app) 23 | 24 | or using the factory method approach, creating the application first, then the 25 | :py:class:`flask_twilio.Twilio` instance, and finally calling 26 | :py:meth:`flask_twilio.Twilio.init_app`:: 27 | 28 | twilio = Twilio() 29 | app = Flask(__name__) 30 | twilio.init_app(app) 31 | 32 | 33 | Making a Call 34 | ------------- 35 | 36 | Making a call involves two steps: first, creating a call view, and second, 37 | placing a call. The view produces an XML file that serves as a script for 38 | Twilio to follow. Here is an example call view:: 39 | 40 | from flask_twilio import Response 41 | from twilio.twiml.messaging_response import Message 42 | from twilio.twiml.voice_response import Say 43 | 44 | @app.route('/call.xml') 45 | @twilio.twiml 46 | def call(): 47 | resp = Response() 48 | resp.append(Say('This is a voice call from Twilio!', voice='female')) 49 | resp.append(Message('This is an SMS message from Twilio!')) 50 | return resp 51 | 52 | The :py:attr:`flask_twilio.Twilio.twiml` decorator adds some validation and must come 53 | `after` the ``app.route`` decorator. 54 | 55 | To place a call using this view, we use the 56 | :py:meth:`flask_twilio.Twilio.call_for` method, which is based on 57 | :py:func:`flask.url_for`:: 58 | 59 | twilio.call_for('call', to='+15005550006') 60 | 61 | 62 | Sending a Text Message 63 | ---------------------- 64 | 65 | The above example simultaneously places a voice call and sends a text message. 66 | If you only want to send a text message, there is a shortcut:: 67 | 68 | twilio.message('This is an SMS message from Twilio!', to='+15005550006') 69 | 70 | 71 | Full Example Flask Application 72 | ------------------------------ 73 | 74 | See `example.py on GitHub`_ for a full example Flask application. 75 | 76 | .. _example.py on GitHub: https://github.com/lpsinger/flask-twilio/blob/master/example.py 77 | 78 | 79 | Configuration Variables 80 | ----------------------- 81 | 82 | Flask-Twilio understands the following configuration values: 83 | 84 | =========================== ==================================================== 85 | ``TWILIO_ACCOUNT_SID`` Your Twilio account SID. 86 | ``TWILIO_AUTH_SID`` The SID that you use to authenticate with Twilio, 87 | if different from your account SID (for example, if 88 | you are using an `API key`_). 89 | ``TWILIO_AUTH_TOKEN`` Your Twilio authentication token. 90 | ``TWILIO_FROM`` Your default 'from' phone number (optional). 91 | Note that there are some useful 92 | `dummy numbers for testing`_. 93 | ``SECRET_KEY`` Same as the standard Flask coniguration value. 94 | If provided, then Flask-Twilio will perform some 95 | sanity checking to ensure that requests from Twilio 96 | result from calls placed by this application. 97 | =========================== ==================================================== 98 | 99 | .. _dummy numbers for testing: https://www.twilio.com/docs/api/rest/test-credentials#test-sms-messages-parameters-From 100 | .. _api key: https://www.twilio.com/docs/api/rest/keys 101 | 102 | 103 | API 104 | --- 105 | 106 | .. automodule:: flask_twilio 107 | -------------------------------------------------------------------------------- /test_flask_twilio.py: -------------------------------------------------------------------------------- 1 | from six.moves.urllib.parse import urlsplit 2 | from base64 import b64encode 3 | import pytest 4 | from flask import Flask 5 | from twilio.request_validator import RequestValidator 6 | from twilio.rest.api.v2010.account.call import CallList 7 | from flask_twilio import Twilio, Response 8 | from twilio.twiml.voice_response import Say 9 | 10 | 11 | def basic_auth(username, password): 12 | auth = 'Basic ' + b64encode((username + ':' + password).encode()).decode() 13 | return {'Authorization': auth} 14 | 15 | 16 | @pytest.fixture 17 | def twilio(): 18 | app = Flask(__name__) 19 | app.config['TWILIO_ACCOUNT_SID'] = 'sid' 20 | app.config['TWILIO_AUTH_TOKEN'] = 'token' 21 | app.config['TWILIO_FROM'] = '+15005550006' 22 | twilio = Twilio(app) 23 | 24 | @app.route('/call') 25 | @twilio.twiml 26 | def call(): 27 | resp = Response() 28 | resp.append(Say('Testing, 1, 2, 3.')) 29 | return resp 30 | 31 | return twilio 32 | 33 | 34 | @pytest.fixture 35 | def always_valid(monkeypatch): 36 | monkeypatch.setattr( 37 | RequestValidator, 'validate', lambda *args, **kargs: True) 38 | 39 | 40 | @pytest.fixture 41 | def always_invalid(monkeypatch): 42 | monkeypatch.setattr( 43 | RequestValidator, 'validate', lambda *args, **kargs: False) 44 | 45 | 46 | @pytest.fixture 47 | def mock_create_call(monkeypatch): 48 | ret = dict() 49 | 50 | def store(self, to, from_, url): 51 | ret['to'] = to 52 | ret['from_'] = from_ 53 | ret['url'] = url 54 | 55 | monkeypatch.setattr(CallList, 'create', store) 56 | return ret 57 | 58 | 59 | def test_get_denied(twilio): 60 | """Check that GET requests are denied.""" 61 | app = twilio.app 62 | test_client = app.test_client() 63 | resp = test_client.get('/call') 64 | assert resp.status_code == 405 65 | 66 | 67 | def test_post_denied(twilio): 68 | """Check that POST requests are denied if they do not carry a valid Twilio 69 | signature.""" 70 | app = twilio.app 71 | test_client = app.test_client() 72 | resp = test_client.post('/call') 73 | assert resp.status_code == 403 74 | 75 | 76 | def test_testing_allowed(twilio): 77 | """Check that POST requests are allowed in testing mode.""" 78 | app = twilio.app 79 | test_client = app.test_client() 80 | app.config['TESTING'] = True 81 | resp = test_client.post('/call') 82 | assert resp.status_code == 200 83 | 84 | 85 | def test_valid_allowed(twilio, always_valid): 86 | """Check that POST requests are allowed if Twilio validates them.""" 87 | app = twilio.app 88 | test_client = app.test_client() 89 | resp = test_client.post('/call') 90 | assert resp.status_code == 200 91 | 92 | 93 | def test_invalid_allowed(twilio, always_invalid): 94 | """Check that invalid POST requests are denied if Twilio does not validate 95 | them.""" 96 | app = twilio.app 97 | test_client = app.test_client() 98 | resp = test_client.post('/call') 99 | assert resp.status_code == 403 100 | 101 | 102 | def test_no_auth(twilio): 103 | """Test that server sends auth challenge if secret key is set""" 104 | app = twilio.app 105 | test_client = app.test_client() 106 | app.config['SECRET_KEY'] = 'secret' 107 | resp = test_client.post('/call') 108 | assert resp.status_code == 401 109 | 110 | 111 | def test_wrong_username(twilio): 112 | """Test that server declines if username is wrong""" 113 | app = twilio.app 114 | test_client = app.test_client() 115 | app.config['SECRET_KEY'] = 'secret' 116 | resp = test_client.post('/call', headers=basic_auth('bob', 'password')) 117 | assert resp.status_code == 401 118 | 119 | 120 | def test_wrong_password(twilio): 121 | """Test that server declines if username is wrong""" 122 | app = twilio.app 123 | test_client = app.test_client() 124 | app.config['SECRET_KEY'] = 'secret' 125 | resp = test_client.post('/call', headers=basic_auth('twilio', 'password')) 126 | assert resp.status_code == 401 127 | 128 | 129 | def test_auth_correct(twilio, always_valid, mock_create_call): 130 | """Test that server permits a request that is not spoofed""" 131 | app = twilio.app 132 | test_client = app.test_client() 133 | app.config['SECRET_KEY'] = 'secret' 134 | with app.test_request_context(): 135 | twilio.call_for('call', to='+15005550006') 136 | urlparts = urlsplit(mock_create_call['url']) 137 | username, password = urlparts.netloc.split('@')[0].split(':') 138 | resp = test_client.post( 139 | urlparts.path, headers=basic_auth(username, password)) 140 | assert resp.status_code == 200 141 | -------------------------------------------------------------------------------- /example.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | """ 3 | Demo Flask-Twilio application 4 | """ 5 | 6 | import os 7 | import socket 8 | 9 | from flask import flash, Flask, render_template, request 10 | from flask_twilio import Twilio, Response 11 | from twilio.base.exceptions import TwilioRestException 12 | from twilio.twiml.messaging_response import Message 13 | from twilio.twiml.voice_response import Say 14 | from jinja2 import DictLoader 15 | 16 | # A standard test number. 17 | # See https://www.twilio.com/docs/api/rest/test-credentials. 18 | DEFAULT_NUMBER = '+15005550006' 19 | 20 | # Application configuration. 21 | app = Flask(__name__) 22 | app.config['SECRET_KEY'] = os.urandom(24) 23 | app.config['SERVER_NAME'] = socket.getfqdn() + ':5000' 24 | app.config['TWILIO_ACCOUNT_SID'] = os.environ.get('TWILIO_ACCOUNT_SID') 25 | app.config['TWILIO_AUTH_SID'] = os.environ.get('TWILIO_AUTH_SID') 26 | app.config['TWILIO_AUTH_TOKEN'] = os.environ.get('TWILIO_AUTH_TOKEN') 27 | app.config['TWILIO_FROM'] = os.environ.get('TWILIO_FROM', DEFAULT_NUMBER) 28 | twilio = Twilio(app) 29 | 30 | # Main form template. 31 | app.jinja_loader = DictLoader({'example.html': '''\ 32 | 33 | Flask-Twilio Test 34 | 35 | 36 | 37 | 45 |
46 |
47 |
48 |

Flask-Twilio Test

49 |
50 | {% with messages = get_flashed_messages(with_categories=true) %} 51 | {% for category, message in messages %} 52 |
{{ message }}
53 | {% endfor %} 54 | {% endwith %} 55 |
56 | 57 | 58 |
59 | 60 |
61 | 64 | 66 | 71 |
72 |
73 |
74 |
75 |
76 | 77 | 78 | 79 | '''}) 80 | 81 | 82 | @app.route('/twiml') 83 | @twilio.twiml 84 | def test_call(): 85 | """View for producing the TwiML document.""" 86 | say = int(request.values.get('say', 1)) 87 | sms = int(request.values.get('sms', 1)) 88 | resp = Response() 89 | if say: 90 | resp.append(Say('This is a voice call from Twilio!', voice='female')) 91 | if sms: 92 | resp.append(Message('This is an SMS message from Twilio!')) 93 | return resp 94 | 95 | 96 | @app.route('/', methods=['GET']) 97 | def index_get(): 98 | """Main form view.""" 99 | return render_template( 100 | 'example.html', 101 | to=request.values.get('to', DEFAULT_NUMBER)) 102 | 103 | 104 | @app.route('/', methods=['POST']) 105 | def index_post(): 106 | """Main form action.""" 107 | try: 108 | say = int(request.values.get('say', 1)) 109 | sms = int(request.values.get('sms', 1)) 110 | to = request.values.get('to', None) 111 | if say: 112 | twilio.call_for('test_call', to, say=say, sms=sms) 113 | else: 114 | twilio.message('This is an SMS message from Twilio!', to) 115 | flash('Request was successfully sent to Twilio.', 'success') 116 | except TwilioRestException as e: 117 | flash('Failed to make call: ' + e.msg, 'danger') 118 | app.logger.exception('Failed to make call') 119 | return index_get() 120 | 121 | 122 | # Start application. 123 | app.run('0.0.0.0') 124 | -------------------------------------------------------------------------------- /docs/Makefile: -------------------------------------------------------------------------------- 1 | # Makefile for Sphinx documentation 2 | # 3 | 4 | # You can set these variables from the command line. 5 | SPHINXOPTS = 6 | SPHINXBUILD = sphinx-build 7 | PAPER = 8 | BUILDDIR = _build 9 | 10 | # User-friendly check for sphinx-build 11 | ifeq ($(shell which $(SPHINXBUILD) >/dev/null 2>&1; echo $$?), 1) 12 | $(error The '$(SPHINXBUILD)' command was not found. Make sure you have Sphinx installed, then set the SPHINXBUILD environment variable to point to the full path of the '$(SPHINXBUILD)' executable. Alternatively you can add the directory with the executable to your PATH. If you don't have Sphinx installed, grab it from http://sphinx-doc.org/) 13 | endif 14 | 15 | # Internal variables. 16 | PAPEROPT_a4 = -D latex_paper_size=a4 17 | PAPEROPT_letter = -D latex_paper_size=letter 18 | ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . 19 | # the i18n builder cannot share the environment and doctrees with the others 20 | I18NSPHINXOPTS = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . 21 | 22 | .PHONY: help clean html dirhtml singlehtml pickle json htmlhelp qthelp devhelp epub latex latexpdf text man changes linkcheck doctest coverage gettext 23 | 24 | help: 25 | @echo "Please use \`make ' where is one of" 26 | @echo " html to make standalone HTML files" 27 | @echo " dirhtml to make HTML files named index.html in directories" 28 | @echo " singlehtml to make a single large HTML file" 29 | @echo " pickle to make pickle files" 30 | @echo " json to make JSON files" 31 | @echo " htmlhelp to make HTML files and a HTML help project" 32 | @echo " qthelp to make HTML files and a qthelp project" 33 | @echo " applehelp to make an Apple Help Book" 34 | @echo " devhelp to make HTML files and a Devhelp project" 35 | @echo " epub to make an epub" 36 | @echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter" 37 | @echo " latexpdf to make LaTeX files and run them through pdflatex" 38 | @echo " latexpdfja to make LaTeX files and run them through platex/dvipdfmx" 39 | @echo " text to make text files" 40 | @echo " man to make manual pages" 41 | @echo " texinfo to make Texinfo files" 42 | @echo " info to make Texinfo files and run them through makeinfo" 43 | @echo " gettext to make PO message catalogs" 44 | @echo " changes to make an overview of all changed/added/deprecated items" 45 | @echo " xml to make Docutils-native XML files" 46 | @echo " pseudoxml to make pseudoxml-XML files for display purposes" 47 | @echo " linkcheck to check all external links for integrity" 48 | @echo " doctest to run all doctests embedded in the documentation (if enabled)" 49 | @echo " coverage to run coverage check of the documentation (if enabled)" 50 | 51 | clean: 52 | rm -rf $(BUILDDIR)/* 53 | 54 | html: 55 | $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html 56 | @echo 57 | @echo "Build finished. The HTML pages are in $(BUILDDIR)/html." 58 | 59 | dirhtml: 60 | $(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml 61 | @echo 62 | @echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml." 63 | 64 | singlehtml: 65 | $(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml 66 | @echo 67 | @echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml." 68 | 69 | pickle: 70 | $(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle 71 | @echo 72 | @echo "Build finished; now you can process the pickle files." 73 | 74 | json: 75 | $(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json 76 | @echo 77 | @echo "Build finished; now you can process the JSON files." 78 | 79 | htmlhelp: 80 | $(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp 81 | @echo 82 | @echo "Build finished; now you can run HTML Help Workshop with the" \ 83 | ".hhp project file in $(BUILDDIR)/htmlhelp." 84 | 85 | qthelp: 86 | $(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp 87 | @echo 88 | @echo "Build finished; now you can run "qcollectiongenerator" with the" \ 89 | ".qhcp project file in $(BUILDDIR)/qthelp, like this:" 90 | @echo "# qcollectiongenerator $(BUILDDIR)/qthelp/Flask-Twilio.qhcp" 91 | @echo "To view the help file:" 92 | @echo "# assistant -collectionFile $(BUILDDIR)/qthelp/Flask-Twilio.qhc" 93 | 94 | applehelp: 95 | $(SPHINXBUILD) -b applehelp $(ALLSPHINXOPTS) $(BUILDDIR)/applehelp 96 | @echo 97 | @echo "Build finished. The help book is in $(BUILDDIR)/applehelp." 98 | @echo "N.B. You won't be able to view it unless you put it in" \ 99 | "~/Library/Documentation/Help or install it in your application" \ 100 | "bundle." 101 | 102 | devhelp: 103 | $(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp 104 | @echo 105 | @echo "Build finished." 106 | @echo "To view the help file:" 107 | @echo "# mkdir -p $$HOME/.local/share/devhelp/Flask-Twilio" 108 | @echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/Flask-Twilio" 109 | @echo "# devhelp" 110 | 111 | epub: 112 | $(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub 113 | @echo 114 | @echo "Build finished. The epub file is in $(BUILDDIR)/epub." 115 | 116 | latex: 117 | $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex 118 | @echo 119 | @echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex." 120 | @echo "Run \`make' in that directory to run these through (pdf)latex" \ 121 | "(use \`make latexpdf' here to do that automatically)." 122 | 123 | latexpdf: 124 | $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex 125 | @echo "Running LaTeX files through pdflatex..." 126 | $(MAKE) -C $(BUILDDIR)/latex all-pdf 127 | @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." 128 | 129 | latexpdfja: 130 | $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex 131 | @echo "Running LaTeX files through platex and dvipdfmx..." 132 | $(MAKE) -C $(BUILDDIR)/latex all-pdf-ja 133 | @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." 134 | 135 | text: 136 | $(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text 137 | @echo 138 | @echo "Build finished. The text files are in $(BUILDDIR)/text." 139 | 140 | man: 141 | $(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man 142 | @echo 143 | @echo "Build finished. The manual pages are in $(BUILDDIR)/man." 144 | 145 | texinfo: 146 | $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo 147 | @echo 148 | @echo "Build finished. The Texinfo files are in $(BUILDDIR)/texinfo." 149 | @echo "Run \`make' in that directory to run these through makeinfo" \ 150 | "(use \`make info' here to do that automatically)." 151 | 152 | info: 153 | $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo 154 | @echo "Running Texinfo files through makeinfo..." 155 | make -C $(BUILDDIR)/texinfo info 156 | @echo "makeinfo finished; the Info files are in $(BUILDDIR)/texinfo." 157 | 158 | gettext: 159 | $(SPHINXBUILD) -b gettext $(I18NSPHINXOPTS) $(BUILDDIR)/locale 160 | @echo 161 | @echo "Build finished. The message catalogs are in $(BUILDDIR)/locale." 162 | 163 | changes: 164 | $(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes 165 | @echo 166 | @echo "The overview file is in $(BUILDDIR)/changes." 167 | 168 | linkcheck: 169 | $(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck 170 | @echo 171 | @echo "Link check complete; look for any errors in the above output " \ 172 | "or in $(BUILDDIR)/linkcheck/output.txt." 173 | 174 | doctest: 175 | $(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest 176 | @echo "Testing of doctests in the sources finished, look at the " \ 177 | "results in $(BUILDDIR)/doctest/output.txt." 178 | 179 | coverage: 180 | $(SPHINXBUILD) -b coverage $(ALLSPHINXOPTS) $(BUILDDIR)/coverage 181 | @echo "Testing of coverage in the sources finished, look at the " \ 182 | "results in $(BUILDDIR)/coverage/python.txt." 183 | 184 | xml: 185 | $(SPHINXBUILD) -b xml $(ALLSPHINXOPTS) $(BUILDDIR)/xml 186 | @echo 187 | @echo "Build finished. The XML files are in $(BUILDDIR)/xml." 188 | 189 | pseudoxml: 190 | $(SPHINXBUILD) -b pseudoxml $(ALLSPHINXOPTS) $(BUILDDIR)/pseudoxml 191 | @echo 192 | @echo "Build finished. The pseudo-XML files are in $(BUILDDIR)/pseudoxml." 193 | -------------------------------------------------------------------------------- /docs/make.bat: -------------------------------------------------------------------------------- 1 | @ECHO OFF 2 | 3 | REM Command file for Sphinx documentation 4 | 5 | if "%SPHINXBUILD%" == "" ( 6 | set SPHINXBUILD=sphinx-build 7 | ) 8 | set BUILDDIR=_build 9 | set ALLSPHINXOPTS=-d %BUILDDIR%/doctrees %SPHINXOPTS% . 10 | set I18NSPHINXOPTS=%SPHINXOPTS% . 11 | if NOT "%PAPER%" == "" ( 12 | set ALLSPHINXOPTS=-D latex_paper_size=%PAPER% %ALLSPHINXOPTS% 13 | set I18NSPHINXOPTS=-D latex_paper_size=%PAPER% %I18NSPHINXOPTS% 14 | ) 15 | 16 | if "%1" == "" goto help 17 | 18 | if "%1" == "help" ( 19 | :help 20 | echo.Please use `make ^` where ^ is one of 21 | echo. html to make standalone HTML files 22 | echo. dirhtml to make HTML files named index.html in directories 23 | echo. singlehtml to make a single large HTML file 24 | echo. pickle to make pickle files 25 | echo. json to make JSON files 26 | echo. htmlhelp to make HTML files and a HTML help project 27 | echo. qthelp to make HTML files and a qthelp project 28 | echo. devhelp to make HTML files and a Devhelp project 29 | echo. epub to make an epub 30 | echo. latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter 31 | echo. text to make text files 32 | echo. man to make manual pages 33 | echo. texinfo to make Texinfo files 34 | echo. gettext to make PO message catalogs 35 | echo. changes to make an overview over all changed/added/deprecated items 36 | echo. xml to make Docutils-native XML files 37 | echo. pseudoxml to make pseudoxml-XML files for display purposes 38 | echo. linkcheck to check all external links for integrity 39 | echo. doctest to run all doctests embedded in the documentation if enabled 40 | echo. coverage to run coverage check of the documentation if enabled 41 | goto end 42 | ) 43 | 44 | if "%1" == "clean" ( 45 | for /d %%i in (%BUILDDIR%\*) do rmdir /q /s %%i 46 | del /q /s %BUILDDIR%\* 47 | goto end 48 | ) 49 | 50 | 51 | REM Check if sphinx-build is available and fallback to Python version if any 52 | %SPHINXBUILD% 2> nul 53 | if errorlevel 9009 goto sphinx_python 54 | goto sphinx_ok 55 | 56 | :sphinx_python 57 | 58 | set SPHINXBUILD=python -m sphinx.__init__ 59 | %SPHINXBUILD% 2> nul 60 | if errorlevel 9009 ( 61 | echo. 62 | echo.The 'sphinx-build' command was not found. Make sure you have Sphinx 63 | echo.installed, then set the SPHINXBUILD environment variable to point 64 | echo.to the full path of the 'sphinx-build' executable. Alternatively you 65 | echo.may add the Sphinx directory to PATH. 66 | echo. 67 | echo.If you don't have Sphinx installed, grab it from 68 | echo.http://sphinx-doc.org/ 69 | exit /b 1 70 | ) 71 | 72 | :sphinx_ok 73 | 74 | 75 | if "%1" == "html" ( 76 | %SPHINXBUILD% -b html %ALLSPHINXOPTS% %BUILDDIR%/html 77 | if errorlevel 1 exit /b 1 78 | echo. 79 | echo.Build finished. The HTML pages are in %BUILDDIR%/html. 80 | goto end 81 | ) 82 | 83 | if "%1" == "dirhtml" ( 84 | %SPHINXBUILD% -b dirhtml %ALLSPHINXOPTS% %BUILDDIR%/dirhtml 85 | if errorlevel 1 exit /b 1 86 | echo. 87 | echo.Build finished. The HTML pages are in %BUILDDIR%/dirhtml. 88 | goto end 89 | ) 90 | 91 | if "%1" == "singlehtml" ( 92 | %SPHINXBUILD% -b singlehtml %ALLSPHINXOPTS% %BUILDDIR%/singlehtml 93 | if errorlevel 1 exit /b 1 94 | echo. 95 | echo.Build finished. The HTML pages are in %BUILDDIR%/singlehtml. 96 | goto end 97 | ) 98 | 99 | if "%1" == "pickle" ( 100 | %SPHINXBUILD% -b pickle %ALLSPHINXOPTS% %BUILDDIR%/pickle 101 | if errorlevel 1 exit /b 1 102 | echo. 103 | echo.Build finished; now you can process the pickle files. 104 | goto end 105 | ) 106 | 107 | if "%1" == "json" ( 108 | %SPHINXBUILD% -b json %ALLSPHINXOPTS% %BUILDDIR%/json 109 | if errorlevel 1 exit /b 1 110 | echo. 111 | echo.Build finished; now you can process the JSON files. 112 | goto end 113 | ) 114 | 115 | if "%1" == "htmlhelp" ( 116 | %SPHINXBUILD% -b htmlhelp %ALLSPHINXOPTS% %BUILDDIR%/htmlhelp 117 | if errorlevel 1 exit /b 1 118 | echo. 119 | echo.Build finished; now you can run HTML Help Workshop with the ^ 120 | .hhp project file in %BUILDDIR%/htmlhelp. 121 | goto end 122 | ) 123 | 124 | if "%1" == "qthelp" ( 125 | %SPHINXBUILD% -b qthelp %ALLSPHINXOPTS% %BUILDDIR%/qthelp 126 | if errorlevel 1 exit /b 1 127 | echo. 128 | echo.Build finished; now you can run "qcollectiongenerator" with the ^ 129 | .qhcp project file in %BUILDDIR%/qthelp, like this: 130 | echo.^> qcollectiongenerator %BUILDDIR%\qthelp\Flask-Twilio.qhcp 131 | echo.To view the help file: 132 | echo.^> assistant -collectionFile %BUILDDIR%\qthelp\Flask-Twilio.ghc 133 | goto end 134 | ) 135 | 136 | if "%1" == "devhelp" ( 137 | %SPHINXBUILD% -b devhelp %ALLSPHINXOPTS% %BUILDDIR%/devhelp 138 | if errorlevel 1 exit /b 1 139 | echo. 140 | echo.Build finished. 141 | goto end 142 | ) 143 | 144 | if "%1" == "epub" ( 145 | %SPHINXBUILD% -b epub %ALLSPHINXOPTS% %BUILDDIR%/epub 146 | if errorlevel 1 exit /b 1 147 | echo. 148 | echo.Build finished. The epub file is in %BUILDDIR%/epub. 149 | goto end 150 | ) 151 | 152 | if "%1" == "latex" ( 153 | %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex 154 | if errorlevel 1 exit /b 1 155 | echo. 156 | echo.Build finished; the LaTeX files are in %BUILDDIR%/latex. 157 | goto end 158 | ) 159 | 160 | if "%1" == "latexpdf" ( 161 | %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex 162 | cd %BUILDDIR%/latex 163 | make all-pdf 164 | cd %~dp0 165 | echo. 166 | echo.Build finished; the PDF files are in %BUILDDIR%/latex. 167 | goto end 168 | ) 169 | 170 | if "%1" == "latexpdfja" ( 171 | %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex 172 | cd %BUILDDIR%/latex 173 | make all-pdf-ja 174 | cd %~dp0 175 | echo. 176 | echo.Build finished; the PDF files are in %BUILDDIR%/latex. 177 | goto end 178 | ) 179 | 180 | if "%1" == "text" ( 181 | %SPHINXBUILD% -b text %ALLSPHINXOPTS% %BUILDDIR%/text 182 | if errorlevel 1 exit /b 1 183 | echo. 184 | echo.Build finished. The text files are in %BUILDDIR%/text. 185 | goto end 186 | ) 187 | 188 | if "%1" == "man" ( 189 | %SPHINXBUILD% -b man %ALLSPHINXOPTS% %BUILDDIR%/man 190 | if errorlevel 1 exit /b 1 191 | echo. 192 | echo.Build finished. The manual pages are in %BUILDDIR%/man. 193 | goto end 194 | ) 195 | 196 | if "%1" == "texinfo" ( 197 | %SPHINXBUILD% -b texinfo %ALLSPHINXOPTS% %BUILDDIR%/texinfo 198 | if errorlevel 1 exit /b 1 199 | echo. 200 | echo.Build finished. The Texinfo files are in %BUILDDIR%/texinfo. 201 | goto end 202 | ) 203 | 204 | if "%1" == "gettext" ( 205 | %SPHINXBUILD% -b gettext %I18NSPHINXOPTS% %BUILDDIR%/locale 206 | if errorlevel 1 exit /b 1 207 | echo. 208 | echo.Build finished. The message catalogs are in %BUILDDIR%/locale. 209 | goto end 210 | ) 211 | 212 | if "%1" == "changes" ( 213 | %SPHINXBUILD% -b changes %ALLSPHINXOPTS% %BUILDDIR%/changes 214 | if errorlevel 1 exit /b 1 215 | echo. 216 | echo.The overview file is in %BUILDDIR%/changes. 217 | goto end 218 | ) 219 | 220 | if "%1" == "linkcheck" ( 221 | %SPHINXBUILD% -b linkcheck %ALLSPHINXOPTS% %BUILDDIR%/linkcheck 222 | if errorlevel 1 exit /b 1 223 | echo. 224 | echo.Link check complete; look for any errors in the above output ^ 225 | or in %BUILDDIR%/linkcheck/output.txt. 226 | goto end 227 | ) 228 | 229 | if "%1" == "doctest" ( 230 | %SPHINXBUILD% -b doctest %ALLSPHINXOPTS% %BUILDDIR%/doctest 231 | if errorlevel 1 exit /b 1 232 | echo. 233 | echo.Testing of doctests in the sources finished, look at the ^ 234 | results in %BUILDDIR%/doctest/output.txt. 235 | goto end 236 | ) 237 | 238 | if "%1" == "coverage" ( 239 | %SPHINXBUILD% -b coverage %ALLSPHINXOPTS% %BUILDDIR%/coverage 240 | if errorlevel 1 exit /b 1 241 | echo. 242 | echo.Testing of coverage in the sources finished, look at the ^ 243 | results in %BUILDDIR%/coverage/python.txt. 244 | goto end 245 | ) 246 | 247 | if "%1" == "xml" ( 248 | %SPHINXBUILD% -b xml %ALLSPHINXOPTS% %BUILDDIR%/xml 249 | if errorlevel 1 exit /b 1 250 | echo. 251 | echo.Build finished. The XML files are in %BUILDDIR%/xml. 252 | goto end 253 | ) 254 | 255 | if "%1" == "pseudoxml" ( 256 | %SPHINXBUILD% -b pseudoxml %ALLSPHINXOPTS% %BUILDDIR%/pseudoxml 257 | if errorlevel 1 exit /b 1 258 | echo. 259 | echo.Build finished. The pseudo-XML files are in %BUILDDIR%/pseudoxml. 260 | goto end 261 | ) 262 | 263 | :end 264 | -------------------------------------------------------------------------------- /flask_twilio.py: -------------------------------------------------------------------------------- 1 | __version__ = '0.0.6' 2 | __all__ = ('Response', 'Twilio') 3 | 4 | from string import ascii_letters, digits 5 | from random import SystemRandom 6 | from functools import wraps 7 | from six.moves.urllib.parse import urlsplit, urlunsplit 8 | from twilio.rest import Client 9 | from twilio.request_validator import RequestValidator 10 | from twilio.twiml import TwiML 11 | from flask import Response as FlaskResponse 12 | from flask import abort, current_app, make_response, request, url_for 13 | from flask import _app_ctx_stack as stack 14 | from itsdangerous import TimestampSigner 15 | 16 | 17 | rand = SystemRandom() 18 | letters_and_digits = ascii_letters + digits 19 | 20 | 21 | class Response(FlaskResponse, TwiML): 22 | """ 23 | A response class for constructing TwiML documents, providing all of 24 | the verbs that are available through :py:class:`twilio.twiml.Response`. 25 | See also https://www.twilio.com/docs/api/twiml. 26 | """ 27 | 28 | def __init__(self, *args, **kwargs): 29 | TwiML.__init__(self) 30 | FlaskResponse.__init__(self, *args, **kwargs) 31 | 32 | @property 33 | def response(self): 34 | return [self.to_xml()] 35 | 36 | @response.setter 37 | def response(self, value): 38 | pass 39 | 40 | 41 | class Twilio(object): 42 | """This class is used to control Twilio calls.""" 43 | 44 | def __init__(self, app=None): 45 | self.app = app 46 | if app is not None: 47 | self.init_app(app) 48 | 49 | def init_app(self, app): 50 | """Factory method.""" 51 | app.teardown_appcontext(self.teardown) 52 | 53 | def teardown(self, exception): 54 | ctx = stack.top 55 | if hasattr(ctx, 'twilio_client'): 56 | del ctx.twilio_client 57 | if hasattr(ctx, 'twilio_validator'): 58 | del ctx.twilio_validator 59 | if hasattr(ctx, 'twilio_signer'): 60 | del ctx.twilio_signer 61 | 62 | @property 63 | def client(self): 64 | """ 65 | An application-specific intance of 66 | :py:class:`twilio.rest.Client`. Primarily for internal use. 67 | """ 68 | ctx = stack.top 69 | if ctx is not None: 70 | if not hasattr(ctx, 'twilio_client'): 71 | username = current_app.config.get('TWILIO_AUTH_SID') 72 | account_sid = current_app.config.get('TWILIO_ACCOUNT_SID') 73 | if username is None: 74 | username = account_sid 75 | elif account_sid is None: 76 | account_sid = username 77 | password = current_app.config['TWILIO_AUTH_TOKEN'] 78 | ctx.twilio_client = Client( 79 | username=username, password=password, 80 | account_sid=account_sid) 81 | return ctx.twilio_client 82 | 83 | @property 84 | def validator(self): 85 | """ 86 | An application-specific instance of 87 | :py:class:`twilio.request_validator.RequestValidator`. 88 | Primarily for internal use. 89 | """ 90 | ctx = stack.top 91 | if ctx is not None: 92 | if not hasattr(ctx, 'twilio_validator'): 93 | ctx.twilio_validator = RequestValidator( 94 | current_app.config['TWILIO_AUTH_TOKEN']) 95 | return ctx.twilio_validator 96 | 97 | @property 98 | def signer(self): 99 | """ 100 | An application-specific instance of 101 | :py:class:`itsdangerous.TimestampSigner`, or ``None`` if no secret key 102 | is set. Primarily for internal use. 103 | """ 104 | ctx = stack.top 105 | if ctx is not None: 106 | if not hasattr(ctx, 'twilio_signer'): 107 | if current_app.secret_key is not None: 108 | ctx.twilio_signer = TimestampSigner( 109 | current_app.secret_key, 'twilio') 110 | else: 111 | ctx.twilio_signer = None 112 | return ctx.twilio_signer 113 | 114 | def twiml(self, view_func): 115 | """Decorator for marking view that will create TwiML documents.""" 116 | @wraps(view_func) 117 | def wrapper(*args, **kwargs): 118 | if not(current_app.debug or current_app.testing): 119 | if request.method != 'POST': 120 | abort(405) 121 | 122 | # Perform HTTP Basic authentication if a secret key is set. 123 | # 124 | # The username must be `twilio`, and the password must be a 125 | # validly signed string that was generated less than 10 minutes 126 | # ago. This guarantees that the Twilio call was initiated by 127 | # this application, rather than a malicious agent. 128 | # 129 | # Note that if we are using HTTP, then a malicious agent can 130 | # still snoop on the data that we are sending to and from 131 | # Twilio, and can also spoof our reply to Twilio. Both issues 132 | # would be addressed by using HTTPS. 133 | if self.signer is not None: 134 | auth = request.authorization 135 | authorized = ( 136 | auth and 137 | auth.username == 'twilio' and 138 | self.signer.validate(auth.password, max_age=600)) 139 | if not authorized: 140 | # If authorization failed, then issue a challenge. 141 | return 'Unauthorized', 401, { 142 | 'WWW-Authenticate': 'Basic realm="Login Required"'} 143 | # Validate the Twilio request. This guarantees that the request 144 | # came from Twilio, rather than some other malicious agent. 145 | valid = self.validator.validate( 146 | request.url, 147 | request.form, 148 | request.headers.get('X-Twilio-Signature', '')) 149 | if not valid: 150 | # If the request was spoofed, then send '403 Forbidden'. 151 | abort(403) 152 | # Call the view itself. 153 | rv = view_func(*args, **kwargs) 154 | # Adjust MIME type and return. 155 | resp = make_response(rv) 156 | resp.mimetype = 'text/xml' 157 | return resp 158 | wrapper.methods = ('GET', 'POST') 159 | # Done! 160 | return wrapper 161 | 162 | def call_for(self, endpoint, to, **values): 163 | """ 164 | Initiate a Twilio call. 165 | 166 | Parameters 167 | ---------- 168 | endpoint : `str` 169 | The view endpoint, as would be passed to :py:func:`flask.url_for`. 170 | to : `str` 171 | The destination phone number. 172 | values : `dict` 173 | Additional keyword arguments to pass to :py:func:`flask.url_for`. 174 | 175 | Returns 176 | ------- 177 | call : `twilio.rest.resources.Call` 178 | An object representing the call in progress. 179 | """ 180 | # Extract keyword arguments that are intended for `calls.create` 181 | # instead of `url_for`. 182 | values = dict(values, _external=True) 183 | from_ = values.pop('from_', None) or current_app.config['TWILIO_FROM'] 184 | 185 | # Construct URL for endpoint. 186 | url = url_for(endpoint, **values) 187 | 188 | # If we are not in debug or testing mode and a secret key is set, then 189 | # add HTTP basic auth information to the URL. The username is `twilio`. 190 | # The password is a random string that has been signed with 191 | # `itsdangerous`. 192 | if not(current_app.debug or current_app.testing or self.signer is None): 193 | urlparts = list(urlsplit(url)) 194 | token = ''.join(rand.choice(letters_and_digits) for i in range(32)) 195 | password = self.signer.sign(token).decode() 196 | urlparts[1] = 'twilio:' + password + '@' + urlparts[1] 197 | url = urlunsplit(urlparts) 198 | 199 | # Issue phone call. 200 | return self.client.calls.create(to=to, from_=from_, url=url) 201 | 202 | def message(self, body, to, **values): 203 | """ 204 | Send an SMS message with Twilio. 205 | 206 | Parameters 207 | ---------- 208 | body : `str` 209 | The body of the text message. 210 | to : `str` 211 | The destination phone number. 212 | values : `dict` 213 | Additional keyword arguments to pass to 214 | :py:meth:`twilio.rest.resources.SmsMessages.create`. 215 | 216 | Returns 217 | ------- 218 | message : :py:class:`twilio.rest.resources.SmsMessage` 219 | An object representing the message that was sent. 220 | """ 221 | values = dict(values) 222 | from_ = values.pop('from_', None) or current_app.config['TWILIO_FROM'] 223 | return self.client.messages.create( 224 | body=body, to=to, from_=from_, **values) 225 | -------------------------------------------------------------------------------- /docs/conf.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # 3 | # Flask-Twilio documentation build configuration file, created by 4 | # sphinx-quickstart on Wed Oct 7 02:40:35 2015. 5 | # 6 | # This file is execfile()d with the current directory set to its 7 | # containing dir. 8 | # 9 | # Note that not all possible configuration values are present in this 10 | # autogenerated file. 11 | # 12 | # All configuration values have a default; values that are commented out 13 | # serve to show the default. 14 | 15 | import sys 16 | import os 17 | import shlex 18 | 19 | # If extensions (or modules to document with autodoc) are in another directory, 20 | # add these directories to sys.path here. If the directory is relative to the 21 | # documentation root, use os.path.abspath to make it absolute, like shown here. 22 | sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))) 23 | sys.path.append(os.path.abspath('_themes')) 24 | 25 | from flask_twilio import __version__ 26 | 27 | # -- General configuration ------------------------------------------------ 28 | 29 | # If your documentation needs a minimal Sphinx version, state it here. 30 | #needs_sphinx = '1.0' 31 | 32 | # Add any Sphinx extension module names here, as strings. They can be 33 | # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom 34 | # ones. 35 | extensions = [ 36 | 'sphinx.ext.autodoc', 37 | 'sphinx.ext.intersphinx', 38 | 'sphinx.ext.napoleon' 39 | ] 40 | 41 | # Add any paths that contain templates here, relative to this directory. 42 | templates_path = ['_templates'] 43 | 44 | # The suffix(es) of source filenames. 45 | # You can specify multiple suffix as a list of string: 46 | # source_suffix = ['.rst', '.md'] 47 | source_suffix = '.rst' 48 | 49 | # The encoding of source files. 50 | #source_encoding = 'utf-8-sig' 51 | 52 | # The master toctree document. 53 | master_doc = 'index' 54 | 55 | # General information about the project. 56 | project = u'Flask-Twilio' 57 | copyright = u'2015, Leo Singer' 58 | author = u'Leo Singer' 59 | 60 | # The version info for the project you're documenting, acts as replacement for 61 | # |version| and |release|, also used in various other places throughout the 62 | # built documents. 63 | # 64 | # The short X.Y version. 65 | version = __version__ 66 | # The full version, including alpha/beta/rc tags. 67 | release = __version__ 68 | 69 | # The language for content autogenerated by Sphinx. Refer to documentation 70 | # for a list of supported languages. 71 | # 72 | # This is also used if you do content translation via gettext catalogs. 73 | # Usually you set "language" from the command line for these cases. 74 | language = None 75 | 76 | # There are two options for replacing |today|: either, you set today to some 77 | # non-false value, then it is used: 78 | #today = '' 79 | # Else, today_fmt is used as the format for a strftime call. 80 | #today_fmt = '%B %d, %Y' 81 | 82 | # List of patterns, relative to source directory, that match files and 83 | # directories to ignore when looking for source files. 84 | exclude_patterns = ['_build'] 85 | 86 | # The reST default role (used for this markup: `text`) to use for all 87 | # documents. 88 | #default_role = None 89 | 90 | # If true, '()' will be appended to :func: etc. cross-reference text. 91 | #add_function_parentheses = True 92 | 93 | # If true, the current module name will be prepended to all description 94 | # unit titles (such as .. function::). 95 | #add_module_names = True 96 | 97 | # If true, sectionauthor and moduleauthor directives will be shown in the 98 | # output. They are ignored by default. 99 | #show_authors = False 100 | 101 | # The name of the Pygments (syntax highlighting) style to use. 102 | pygments_style = 'sphinx' 103 | 104 | # A list of ignored prefixes for module index sorting. 105 | #modindex_common_prefix = [] 106 | 107 | # If true, keep warnings as "system message" paragraphs in the built documents. 108 | #keep_warnings = False 109 | 110 | # If true, `todo` and `todoList` produce output, else they produce nothing. 111 | todo_include_todos = False 112 | 113 | # -- Options for Napoleon extension --------------------------------------- 114 | 115 | napoleon_google_docstring = True 116 | napoleon_numpy_docstring = True 117 | napoleon_use_admonition_for_examples = False 118 | napoleon_use_admonition_for_notes = False 119 | napoleon_use_admonition_for_references = False 120 | napoleon_use_ivar = False 121 | napoleon_use_param = True 122 | napoleon_use_rtype = True 123 | 124 | # -- Options for Autodoc extension ---------------------------------------- 125 | 126 | autodoc_default_flags = ['members'] 127 | 128 | # -- Options for HTML output ---------------------------------------------- 129 | 130 | # The theme to use for HTML and HTML Help pages. See the documentation for 131 | # a list of builtin themes. 132 | html_theme = 'flask_small' 133 | 134 | # Theme options are theme-specific and customize the look and feel of a theme 135 | # further. For a list of options available for each theme, see the 136 | # documentation. 137 | html_theme_options = { 138 | 'index_logo': 'telephone.png', 139 | 'index_logo_height':'160px', 140 | 'github_fork': 'lpsinger/flask-twilio' 141 | } 142 | 143 | # Add any paths that contain custom themes here, relative to this directory. 144 | html_theme_path = ['_themes'] 145 | 146 | # The name for this set of Sphinx documents. If None, it defaults to 147 | # " v documentation". 148 | #html_title = None 149 | 150 | # A shorter title for the navigation bar. Default is the same as html_title. 151 | #html_short_title = None 152 | 153 | # The name of an image file (relative to this directory) to place at the top 154 | # of the sidebar. 155 | #html_logo = None 156 | 157 | # The name of an image file (within the static path) to use as favicon of the 158 | # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 159 | # pixels large. 160 | #html_favicon = None 161 | 162 | # Add any paths that contain custom static files (such as style sheets) here, 163 | # relative to this directory. They are copied after the builtin static files, 164 | # so a file named "default.css" will overwrite the builtin "default.css". 165 | html_static_path = ['_static'] 166 | 167 | # Add any extra paths that contain custom files (such as robots.txt or 168 | # .htaccess) here, relative to this directory. These files are copied 169 | # directly to the root of the documentation. 170 | #html_extra_path = [] 171 | 172 | # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, 173 | # using the given strftime format. 174 | #html_last_updated_fmt = '%b %d, %Y' 175 | 176 | # If true, SmartyPants will be used to convert quotes and dashes to 177 | # typographically correct entities. 178 | #html_use_smartypants = True 179 | 180 | # Custom sidebar templates, maps document names to template names. 181 | #html_sidebars = {} 182 | 183 | # Additional templates that should be rendered to pages, maps page names to 184 | # template names. 185 | #html_additional_pages = {} 186 | 187 | # If false, no module index is generated. 188 | #html_domain_indices = True 189 | 190 | # If false, no index is generated. 191 | #html_use_index = True 192 | 193 | # If true, the index is split into individual pages for each letter. 194 | #html_split_index = False 195 | 196 | # If true, links to the reST sources are added to the pages. 197 | #html_show_sourcelink = True 198 | 199 | # If true, "Created using Sphinx" is shown in the HTML footer. Default is True. 200 | #html_show_sphinx = True 201 | 202 | # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. 203 | #html_show_copyright = True 204 | 205 | # If true, an OpenSearch description file will be output, and all pages will 206 | # contain a tag referring to it. The value of this option must be the 207 | # base URL from which the finished HTML is served. 208 | #html_use_opensearch = '' 209 | 210 | # This is the file name suffix for HTML files (e.g. ".xhtml"). 211 | #html_file_suffix = None 212 | 213 | # Language to be used for generating the HTML full-text search index. 214 | # Sphinx supports the following languages: 215 | # 'da', 'de', 'en', 'es', 'fi', 'fr', 'hu', 'it', 'ja' 216 | # 'nl', 'no', 'pt', 'ro', 'ru', 'sv', 'tr' 217 | #html_search_language = 'en' 218 | 219 | # A dictionary with options for the search language support, empty by default. 220 | # Now only 'ja' uses this config value 221 | #html_search_options = {'type': 'default'} 222 | 223 | # The name of a javascript file (relative to the configuration directory) that 224 | # implements a search results scorer. If empty, the default will be used. 225 | #html_search_scorer = 'scorer.js' 226 | 227 | # Output file base name for HTML help builder. 228 | htmlhelp_basename = 'Flask-Twiliodoc' 229 | 230 | # -- Options for LaTeX output --------------------------------------------- 231 | 232 | latex_elements = { 233 | # The paper size ('letterpaper' or 'a4paper'). 234 | #'papersize': 'letterpaper', 235 | 236 | # The font size ('10pt', '11pt' or '12pt'). 237 | #'pointsize': '10pt', 238 | 239 | # Additional stuff for the LaTeX preamble. 240 | #'preamble': '', 241 | 242 | # Latex figure (float) alignment 243 | #'figure_align': 'htbp', 244 | } 245 | 246 | # Grouping the document tree into LaTeX files. List of tuples 247 | # (source start file, target name, title, 248 | # author, documentclass [howto, manual, or own class]). 249 | latex_documents = [ 250 | (master_doc, 'Flask-Twilio.tex', u'Flask-Twilio Documentation', 251 | u'Leo Singer', 'manual'), 252 | ] 253 | 254 | # The name of an image file (relative to this directory) to place at the top of 255 | # the title page. 256 | #latex_logo = None 257 | 258 | # For "manual" documents, if this is true, then toplevel headings are parts, 259 | # not chapters. 260 | #latex_use_parts = False 261 | 262 | # If true, show page references after internal links. 263 | #latex_show_pagerefs = False 264 | 265 | # If true, show URL addresses after external links. 266 | #latex_show_urls = False 267 | 268 | # Documents to append as an appendix to all manuals. 269 | #latex_appendices = [] 270 | 271 | # If false, no module index is generated. 272 | #latex_domain_indices = True 273 | 274 | 275 | # -- Options for manual page output --------------------------------------- 276 | 277 | # One entry per manual page. List of tuples 278 | # (source start file, name, description, authors, manual section). 279 | man_pages = [ 280 | (master_doc, 'flask-twilio', u'Flask-Twilio Documentation', 281 | [author], 1) 282 | ] 283 | 284 | # If true, show URL addresses after external links. 285 | #man_show_urls = False 286 | 287 | 288 | # -- Options for Texinfo output ------------------------------------------- 289 | 290 | # Grouping the document tree into Texinfo files. List of tuples 291 | # (source start file, target name, title, author, 292 | # dir menu entry, description, category) 293 | texinfo_documents = [ 294 | (master_doc, 'Flask-Twilio', u'Flask-Twilio Documentation', 295 | author, 'Flask-Twilio', 'One line description of project.', 296 | 'Miscellaneous'), 297 | ] 298 | 299 | # Documents to append as an appendix to all manuals. 300 | #texinfo_appendices = [] 301 | 302 | # If false, no module index is generated. 303 | #texinfo_domain_indices = True 304 | 305 | # How to display URL addresses: 'footnote', 'no', or 'inline'. 306 | #texinfo_show_urls = 'footnote' 307 | 308 | # If true, do not generate a @detailmenu in the "Top" node's menu. 309 | #texinfo_no_detailmenu = False 310 | 311 | 312 | # Example configuration for intersphinx: refer to the Python standard library. 313 | intersphinx_mapping = {'http://docs.python.org/': None, 314 | 'http://flask.pocoo.org/docs/': None, 315 | 'http://werkzeug.pocoo.org/docs/latest/': None, 316 | 'http://pythonhosted.org/itsdangerous/': None} 317 | --------------------------------------------------------------------------------