Code Monkey home page Code Monkey logo

django-twilio's Introduction

Django-Twilio

Integrate Twilio into your Django apps with ease.

PyPI version CI build documentation build Python versions supported

Meta

Twilio makes it easy to send & receive SMS messages, and create & manage voice calls through software.

Django-twilio makes it easy to use Twilio in your Django projects.

This project aims to keep compatibility with the supported Django releases.

As such our versions of python and django are designed to match that cadence as much as possible.

We are currently compatible with Django 5. Python versions 3.8 to 3.11.

Documentation

The documentation is hosted at ReadTheDocs. You can check out the docs here - http://django-twilio.rtfd.org/

django-twilio's People

Contributors

birdsarah avatar boardman avatar calebsyring avatar cfc603 avatar comradedos avatar doompatrol avatar felixschwarz avatar heston avatar hungtruong avatar hwkns avatar incidentist avatar issackelly avatar jheld avatar jmduke avatar jvankoten avatar km-pg avatar kyleconroy avatar leetrout avatar mathieusteele avatar mattcarp avatar nickmccullum avatar phalt avatar randalldegges-okta-2 avatar rdegges avatar reznikovroman avatar sarumont avatar sunahsuh avatar tim-schilling avatar waleoyediran avatar zopsi avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

django-twilio's Issues

403 for twilio_view decorator when sending text

Using Django 1.4.20, django-twilio 0.8.0, twilio 4.5.0, South 1.0.2. I have TWILIO_AUTH_TOKEN set in settings.py, debug=False.

No matter what I change, I always get a 403 from my Django app when sending a text, if using the twilio_view decorator. If I simply change it to use the csrf_exempt decorator, everything works.

I am using a function based view, url is set as http://{website_name}/sms/twilio/respond/, so no HTTPS and trailing slash. Url exists and returns 403.

Decorator absorbs *args

I just updated to django_twilio 0.5.1 and ran into an interesting problem. I'm using the @twilio_view decorator around a view.

My URLconf pattern for a twilio_view has a regex group "(...)" which gets passed into the view function as its second argument:

@twilio_view
def my_view(request, some_arg):
    ...

After updating, the arg is absorbed by the methods argument in the decorator (https://github.com/rdegges/django-twilio/blob/master/django_twilio/decorators.py#L57). So the view would return HttpResponseNotAllowed (because the method no longer matched) and in debugging with forgery protection off the argument wasn't passed to my_view, resulting in a TypeError.

A positional argument (in the call) can be the value of a keyword argument, confusingly.

Fortunately a keyword argument that's not called methods or blacklist works fine, so I updated my URLconf and view to get around the problem.

I think the only general solution is to not put keyword arguments on decorator.

Thanks.

Fix Broken Tests

Need to update the broken tests and get rid of all our fixtures (fixtures suck).

The version of twilio-python currently used does not fully support Python 3.

This is a follow-up of #62.

I am currently experiencing this issue in production running on Python 3. Every request tendered to a view decorated with the twilio_view decorator is returning a 403 immediately without ever entering the view.

In that issue, a 403 forbidden was being returned consistently for views decorated with the twilio_view decorator. Later, it was discovered to be a python 2 to 3 concern. The source of the error was within twilio-python, in the RequestValidator being used by twilio_view decorator to do a simple forgery check. There is a small encoding error that will arise if using an older version of twilio-python with Python 3 (see here: twilio/twilio-python#165).

In order to use the fixed code, the dependencies requirements for django-twilio should update the twilio-python version to accept at least version 3.6.9, where this particular fix will be included.

EDIT: I was directed to make sure that the setup.py file matches the requirements.txt file, and found that it is out of sync. It appears that django-twilio is using the correct twilio version on installation dependencies.

Separate settings flag for forgery protection?

Currently, django-twilio relies on the value of settings.DEBUG to toggle forgery protection. However, by default, Django sets DEBUG=False when running tests, so that the app more closely resembles a production scenario.

This makes it difficult to test views decorated with @twilio_view, since test requests always fail the forgery check. It's possible to temporarily override the DEBUG setting using the django.test.utils.override_settings context manager. However, this often has other implications, and undermines the intent of the test runner.

I propose there should be a separate flag, perhaps DJANGO_TWILIO_FORGERY_PROTECTION, that toggles only this aspect of the decorator. By default, this new setting could just inherit the value of DEBUG, but could be overridden in tests as needed.

If there's a better way to test views using the decorator, please let me know.

decorators.py

I'm under the impression that I must be missing something important here, because I can't seem to find this issue elsewhere on the web. However, my pip-installed version of django_twilio has a decorators.py file which is inconsistent with the one here on GitHub. The main problem seems to arise from these two import statements:

from twilio.twiml import Verb
from twilio.util import RequestValidator

The above statements should be:

from twilio.twiml import TwiML as Verb
from twilio.request_validator import RequestValidator

The current GitHub version has this correction, but the pip-installed version does not.

Please do let me know if I am foolishly missing something, or if this is a known problem.

Best,
potc

twilio_view decorator should support class-based views

Currently the twilio_view decorator only works for simple view functions because the wrapped method assumes that the first parameter is always the Django request.

However we you apply the decorator the "dispatch()" method of a class-based view that'll fail because the first parameter in that case is a "self".

Cannot use reject correctly

When using reject like the following:

twilio_response = Response()
r = twilio_response

r.pause()
r.reject(reason='busy')

return r

It works as expected.

But as soon as you leave reject blank, it does not work anymore:
r.reject()

Or the same with the default:

r.reject(reason='rejected')

So basically you cannot use the default "rejected" string with reject

Twilio Connect views

Twilio Connect provides an OAuth dance for applications so users can use their own Twilio account credentials on a web application.

Currently we have to build Twilio Connect views each time we want to build a Twilio connected app. Let's add some views to simplify this process for Django.

GET as opposed to POST

Hi,

(apologies if this is documented somewhere, i did try looking).

I am just experimenting with twilio and django-twilio for the first time. I was getting 403 when I tried to use a GET rather than a POST from twilio (this is a dropdown option in their UI).

When using POST, all is well.

Is there anything I should know here. I'm happy to do a small PR to the docs if GET is not supported.

Best,

Bird

Django 1.9 deprication warnings

.../env/local/lib/python2.7/site-packages/django_twilio/models.py:15: 
RemovedInDjango19Warning: Model class django_twilio.models.Caller doesn't declare an explicit app_label and either isn't in an application in INSTALLED_APPS or else was imported before its application was loaded. This will no longer be supported in Django 1.9.
  class Caller(models.Model):

.../env/local/lib/python2.7/site-packages/django_twilio/models.py:36: 
RemovedInDjango19Warning: Model class django_twilio.models.Credential doesn't declare an explicit app_label and either isn't in an application in INSTALLED_APPS or else was imported before its application was loaded. This will no longer be supported in Django 1.9.
  class Credential(models.Model):

ProgrammingError: relation "django_twilio_credential" does not exist

Using django 1.7.1, and django_twilio 0.8.0, when trying to delete a user account, we get the message you see in the subject. django_twilio is in our INSTALLED_APPS.

$ django-admin migrate django_twilio
...
django.db.utils.ProgrammingError: relation "django_twilio_caller" already exist

It appears as though the Credential was added later, but a proper migration wasn't added to bring it up to speed (I could be wrong about that) :)

develop out of sync with master

There are changes in the master branch that haven't been pulled into develop yet, which makes it difficult to contribute new PRs appropriately (e.g., #61).

500 with @twilio_view decorator

hi there, try as i might i can't get twilio to accept a voice response xml file:

view:

@twilio_view
def publishPin(request, **kwargs):

    u = request.user
    h = HomeTel.objects.get(user = u)
    r = twiml.Response()
    intro = "This is an automated message from example dot com."
    prepare = "In a second you will be given an eight digit code, it will be repeated three times."
    statement = "Your secret code is %s." % h.pin
    finale = "Have a nice day."

    r.say(intro)
    r.say(prepare)
    r.say(statement)
    r.pause(length = 1)
    r.say(statement)
    r.pause(length = 1)
    r.say(statement)
    r.say(finale)

    return r        

url:
url(r'^validate/hometel/talk/(?P[\w.]+)$', 'validate.views.publishPin',),

I'm totally stumped, the call goes in but twilio provides me back with a 500 and indicates a "type error" if i navgate to the page the xml is just fine:

This is an automated message from Place Speak dot com.In a second you will be given an eight digit code, it will be repeated three times.Your secret code is 20218721.Your secret code is 20218721.Your secret code is 20218721.Have a nice day.

all very odd! can you help?

No module named django_twilio

I have 'django_twilio' in my INSTALLED_APPS.

I see both both python twilio and django twilio in my Python PATH:

'/usr/local/lib/python2.7/dist-packages/django_twilio-0.2-py2.7.egg',
'/usr/local/lib/python2.7/dist-packages/twilio-3.3.6-py2.7.egg',

When I try

(r'^sms/$', 'django_twilio.views.sms', {
    'message': 'Yo!',
    'to': '+16158888888',
    'sender': '+18882223333',
    'status_callback': '/caller/',
}),

I get "No module named django_twilio".

Any idea?

Django 1.7 - get_user_model() raises AppRegistryNotReady

I just upgraded to Django 1.7c1 and django-twilio 0.5.2, and I get the following error when I try to runserver or migrate: django.core.exceptions.AppRegistryNotReady.

The source of the problem is 'get_user_model' on line 12 of compat.py, which is invoked by the AUTH_USER_MODEL import on line 6 of models.py. Here's an explanation of the issue from the Django documentation:

Generally speaking, you should reference the User model with the AUTH_USER_MODEL setting in code that is executed at import time. get_user_model() only works once Django has imported all models.

https://docs.djangoproject.com/en/dev/topics/auth/customizing/#django.contrib.auth.get_user_model

I believe the problem can be resolved by declaring the AUTH_USER_MODEL in models.py instead of importing from compat.py. However, I'm not sure why lines 9-16 of compat.py are necessary in the first place.

The full traceback is below:

Traceback (most recent call last):
File "./manage.py", line 10, in
execute_from_command_line(sys.argv)
File "/Users/michaelgodshall/.virtualenvs/social-tool/lib/python2.7/site-packages/django/core/management/init.py", line 385, in execute_from_command_line
utility.execute()
File "/Users/michaelgodshall/.virtualenvs/social-tool/lib/python2.7/site-packages/django/core/management/init.py", line 354, in execute
django.setup()
File "/Users/michaelgodshall/.virtualenvs/social-tool/lib/python2.7/site-packages/django/init.py", line 21, in setup
apps.populate(settings.INSTALLED_APPS)
File "/Users/michaelgodshall/.virtualenvs/social-tool/lib/python2.7/site-packages/django/apps/registry.py", line 106, in populate
app_config.import_models(all_models)
File "/Users/michaelgodshall/.virtualenvs/social-tool/lib/python2.7/site-packages/django/apps/config.py", line 190, in import_models
self.models_module = import_module(models_module_name)
File "/usr/local/Cellar/python/2.7.6/Frameworks/Python.framework/Versions/2.7/lib/python2.7/importlib/init.py", line 37, in import_module
import(name)
File "/Users/michaelgodshall/.virtualenvs/social-tool/lib/python2.7/site-packages/django_twilio/models.py", line 8, in
from django_twilio.compat import AUTH_USER_MODEL
File "/Users/michaelgodshall/.virtualenvs/social-tool/lib/python2.7/site-packages/django_twilio/compat.py", line 12, in
User = get_user_model()
File "/Users/michaelgodshall/.virtualenvs/social-tool/lib/python2.7/site-packages/django/contrib/auth/init.py", line 136, in get_user_model
return django_apps.get_model(settings.AUTH_USER_MODEL)
File "/Users/michaelgodshall/.virtualenvs/social-tool/lib/python2.7/site-packages/django/apps/registry.py", line 187, in get_model
self.check_ready()
File "/Users/michaelgodshall/.virtualenvs/social-tool/lib/python2.7/site-packages/django/apps/registry.py", line 119, in check_ready
raise AppRegistryNotReady()
django.core.exceptions.AppRegistryNotReady

Still using?

Poll: who's still using this project in your apps? Respond here.

Problem with view

Hello,

I am trying to use your library but i have a problem.

I add

url(r'^sms/$', 'django_twilio.views.sms', {
'message': 'Yo!',
'to': '+33687675690',
'sender': '+18882223333',
'status_callback': '/sms/completed/',
}),

But when i go to the url /sms, i got this message :

ViewDoesNotExist at /sms

Tried sms in module django_twilio.views. Error was: 'module' object has no attribute 'sms'

Can you help me?

Incoming Twiml getting executed twice with Debug=False

Apache/2.2.22 (Ubuntu)
Django - Current dev. branch

from django_twilio.decorators import twilio_view

@twilio_view decorator

Checked access.log and only 1 Twiml request comes from Twilio, double checked Twilio notification logs and only one call is sent.

Works fine with Debug=True, and also created a stripped down version of my app on a new box with the same setup, and issue repeats.....

No errors are thrown, visiting the url without POST sends 405, and with POST without signature sends 403 as it's supposed to.... Apache shows only one request...... however, logging the view with valid Twiml requests shows it's getting called twice, and the Twiml inside the view is executing twice as well....

Am I missing something? Or is this a bug?

Database driven authentication keys

Along with declaring a TWILIO_ACCOUNT_SID in settings.py, it would be ideal if this value could be pulled from the database. This would be useful for Twilio Connect apps where every user has a different SID value.

Documentation request: upgrading to twilio 6.x

When I upgraded to twilio SDK 6.x I was met with this error from django-twilio 0.8:
ImportError: cannot import name Verb

The fix was simple but took a bit of digging around in the django-twilio repo.
it was to upgrade to django-twilio 0.9.0a1

Would be great to have a little note about that in the documentation. Because people are starting to adopt 6.x and it would save people some time and frustration.
I can make the PR.

403 error when Debug = False

I am using django-twilio on a new site on Heroku. When I deploy with Debug=True, things work find. When I deploy with Debug=False, I always get a 403 back. I have RTD on the topic, but it doesn't seem like it applies. It basically says to turn debug=True when having the problem to see what's the problem. But, when I do this, the problem goes away. I'm using code that is just out of the example and am using the twilio_view decorator on my one (and only) view. Is this a known problem? Or is there a way to debug it (when debug is set to false).

Support later versions of Django

Getting a warning in Django 1.8 about request.REQUEST being removed in 1.9

site-packages/django_twilio/utils.py:69: RemovedInDjango19Warning: request.REQUEST is deprecated, use request.GET or request.POST instead.
caller = Caller.objects.get(phone_number=request.REQUEST['From'])

Support twilio 6.x

Got this deprecation notice from Twilio:
The old library (5.x) will be officially supported until 7/3/2017. After that day, Twilio will stop providing bug fixes and Support might ask you to upgrade before debugging issues.

Question

I could not find following code in this app

client = TwilioRestClient(account_sid, auth_token)
client.sms.messages.create(----)

Then, How it sending message ? with out client.sms.messages.create(----) ?

TwiML builder

I literally dreamed this up last night and I think it'd be a fantastic feature to add to django-twilio, that may be used on other framework-specific twilio libraries in the future.

TwiML builder

Abstract

A twiml model that allows the creation of new TwiML blocks through the Django administration panel or front-end, without having to type any code.

Example usage

A user can create a new TwiML snippet through the Django administration, programmatically this would look like:

from django_twilio.models import Twiml
from twilio.twiml import Response

# Build some Twiml, alternatively we could just write it as a string
r = Response()
r.dial('+447912345678')
twiml = r.toxml()

# Generate a new Twiml object
tml = Twiml(name="call_forward", twiml=twiml, url='forwarding')
tml.save()

This could then be accessed publicly on my website through the URL:

http://mywebsite.com/twiml/forwarding

and it would result in:

<?xml version="1.0" encoding="UTF-8"?>
<Response>
    <Dial>+447912345678</Dial>
</Response>

We would also be able to retrieve the Twiml and get back the generated URL / Twiml programmatically if we needed to:

>>>from django_twilio.models import Twiml
>>> t = Twiml.objects.get(pk=1)
>>> t
<Twiml - call_forwarding>
>>> t.twiml
<?xml version="1.0" encoding="UTF-8"?>
<Response>
    <Dial>+447912345678</Dial>
</Response>

>>> t.generated_url()
'/twiml/forwarding/'

>>>t.allowed_methods
['GET','POST']

# et cetera...

Use cases

There are multiple use cases for a general purpose Twiml model:

  • Generating bespoke TwiML for individual accounts or numbers
  • Being able to quickly modify / update existing Twiml snippets without diving into code.
  • Ensuring proper formatting of Twiml
  • Not relying on twimlbin or twimlets to be available, everything is kept on your own server.

Update setup.py for readme.rst

Traceback (most recent call last):
File "", line 17, in
File "/django-twilio/setup.py", line 28, in
'README.md'))).read()
IOError: [Errno 2] No such file or directory:
Complete output from command python setup.py egg_info:
Traceback (most recent call last):

File "", line 17, in

File ""

'README.md'))).read()

Does not work with Django 2.0 due to missing on_delete argument in models

The django-twilio library does not work with Django 2.0

File "/var/app/.venv/lib/python3.6/site-packages/django_twilio/models.py", line 36, in <module>
    class Credential(models.Model):
  File "/var/app/.venv/lib/python3.6/site-packages/django_twilio/models.py", line 56, in Credential
    user = models.OneToOneField(AUTH_USER_MODEL)
TypeError: __init__() missing 1 required positional argument: 'on_delete'

Resolve Django 2.0 deprecation warnings

env/local/lib/python2.7/site-packages/django_twilio/migrations/0001_initial.py:34: RemovedInDjango20Warning: on_delete will be a required arg for OneToOneField in Django 2.0. Set it to models.CASCADE on models and in existing migrations if you want to maintain the current default behavior. See https://docs.djangoproject.com/en/1.9/ref/models/fields/#django.db.models.ForeignKey.on_delete
  ('user', models.OneToOneField(to=settings.AUTH_USER_MODEL)),

twilio_view always returns 403 in production on Heroku

Any route using the @twilio_view decorator returns an HttpResponseForbidden in production on Heroku. Some additional notes:

  • Running on Heroku
  • Occurs on django 1.6.5, django-twilio 0.7.1, twilio 3.6.6
  • Problem only occurs when DJANGO_TWILIO_FORGERY_PROTECTION is set to True
  • When receiving a request from Twilio, request.build_absolute_uri() gives the same uri as when queried through the test client
  • AUTH token used in django-twilio matches configured value.

I'd be happy to privately send an example dump of request.POST and request.META if that'd be useful, as well as a copy of my requirements.txt

EDIT:

By @phalt -

This is currently a known issue with Heroku

HTTPRequest Decomposer Proposal

Django-twilio views are always passed an HttpRequest object as the first parameter. When ever a developer needs to get the POST parameters supplied by Twilio from the HTTPRequest object, they have to do this:

sms_body = request.POST.get('Body','')
from_number = request.POST.get('From', '')

As django-twilio is designed to make Twilio easier with Django, it is likely that this will be done often when dealing with HTTPRequests. I propose a new tool for taking an HTTPRequest in a Django view and returning twilio-specific parameters is a Python object that is easier to use and saves some work for the developer.

A draft API would be like so:

from django_twilio.decorators import twilio_view
from django_twilio.requests import decompose

@twilio_view
def incoming_message(request):
    twilio_request = decompose(request)
    # POST parameters are now attributes on a Python object:
    print twilio_request.body
    ...

Alternatively, the decomposer could just return a dictionary instead of a Python object:

from django_twilio.decorators import twilio_view
from django_twilio.requests import decompose

@twilio_view
def incoming_message(request):
    twilio_request = decompose(request)
    # POST parameters are now dictionary key/values:
    print twilio_request['body']
    ...

Add Optional method Decorator Option

As @leetrout suggested here: #6 (comment), I think it's a good idea to allow developers to set the desired HTTP method.

This should allow users to do stuff like:

@twilio_view
def my_view():
    # normal tag behavior

@twilio_view(method='GET')
def my_view():
    # doesn't enforce POST so Twilio will cache my response
    # could also just be POST=False


@twilio_view(blacklist=False)
def my_view():
    # doesn't check the blacklist

Built-in two-factor authentication support

Let's add two-factor authentication support to django-twilio as a "dropin" feature.

Basic flow

  1. An abstract user model 2FAUser subclasses the standard Django user model with the following extra attributes:
    • phone_number - the user's phone number
    • 2fa_code - a randomly generated 5 character string
    • 2fa_id - a randomly generated 20 character string for the verification view.
    • verified - a boolean. True if user has entered their correct 2FA code, false if not. Default is False.
  2. When a new 2FAUser is created (i.e. - a user signs up), a Twilio sms message is sent to the phone_number of the user with the 2fa_code in it (options to set a custom message is also possible).
  3. Flow redirects to a view /user/verify/{2fa_id} with an input form that takes the code sent via SMS, which can set verified to True and redirects to a default page.

Saving to Callers

I am writing a script that will take the From number and save it to the database. I would like to save it to the Callers database in the admin. Is that possible?

Represent the phone numbers as two widgets

Hi,
Thanks a lot for your great package.

What would be the best way to go to render the phone number widget as two widgets:

  • International prefix in a choice list (+1 for the US, +33 for France etc.)
  • Phone number in the country locale.

Thanks a lot.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.