Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Combine Django API view with example view #1322

Merged
merged 2 commits into from
Jun 12, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 0 additions & 11 deletions chatterbot/ext/django_chatterbot/urls.py

This file was deleted.

118 changes: 0 additions & 118 deletions chatterbot/ext/django_chatterbot/views.py

This file was deleted.

6 changes: 3 additions & 3 deletions docs/conversations.rst
Original file line number Diff line number Diff line change
Expand Up @@ -17,14 +17,14 @@ An adapter can access any conversation as long as the unique identifier for the
Conversation example
--------------------

The following example is taken from the Django :code:`ChatterBotView` built into ChatterBot.
The following example is taken from the Django ``ChatterBotApiView`` built into ChatterBot.
In this method, the unique identifiers for each chat session are being stored in Django's
session objects. This allows different users who interact with the bot through different
web browsers to have separate conversations with the chat bot.

.. literalinclude:: ../chatterbot/ext/django_chatterbot/views.py
.. literalinclude:: ../examples/django_app/example_app/views.py
:language: python
:pyobject: ChatterBotView.post
:pyobject: ChatterBotApiView.post
:dedent: 4


Expand Down
31 changes: 3 additions & 28 deletions docs/django/index.rst
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,9 @@
Django Integration
==================

ChatterBot has direct support for integration with Django. ChatterBot provides
out of the box models and endpoints that allow you build ChatterBot powered
Django applications.
ChatterBot has direct support for integration with Django's ORM.
It is relatively easy to use ChatterBot within your Django application
to create conversational pages and endpoints.

.. toctree::
:maxdepth: 2
Expand Down Expand Up @@ -38,25 +38,6 @@ Add `chatterbot.ext.django_chatterbot` to your `INSTALLED_APPS`
)


API view
--------

If you need an API endpoint for your chat bot you can add the following
to your Django urls.py file. You can also choose to create your own views
and end endpoints as needed.

.. code-block:: python

urlpatterns = patterns(
...
url(
r'^chatterbot/',
include('chatterbot.ext.django_chatterbot.urls',
namespace='chatterbot')
),
)


Migrations
----------

Expand All @@ -67,12 +48,6 @@ following command.

python manage.py migrate django_chatterbot

.. note::

Looking for a working example? Check our the example Django app using
ChatterBot on GitHub:
https://github.com/gunthercox/ChatterBot/tree/master/examples/django_app

MongoDB and Django
------------------

Expand Down
22 changes: 14 additions & 8 deletions docs/django/views.rst
Original file line number Diff line number Diff line change
Expand Up @@ -2,20 +2,26 @@
ChatterBot Django Views
=======================

API Views
=========
Exmple API Views
================

ChatterBot's django module comes with a pre-built API view that you can make
requests against to communicate with your bot from your web application.
ChatterBot's Django example comes with an API view that demonstrates
one way to use ChatterBot to create an conversational API endpoint
for your application.

The endpoint expects a JSON request with the following data:
The endpoint expects a JSON request in the following format:

.. code-block:: json

{"text": "My input statement"}


.. literalinclude:: ../../examples/django_app/example_app/views.py
:language: python
:pyobject: ChatterBotApiView


.. note::

You will need to include ChatterBot's urls in your django url configuration
before you can make requests to these views. See the setup instructions for
more details.
Looking for the full example? Check it out on GitHub:
https://github.com/gunthercox/ChatterBot/tree/master/examples/django_app
2 changes: 1 addition & 1 deletion examples/django_app/example_app/templates/app.html
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ <h1 class="jumbotron-heading text-xs-center">Django ChatterBot Example</h1>
<script src="{% static 'js/js.cookie.js' %}"></script>
<script src="{% static 'js/bootstrap.js' %}"></script>
<script>
var chatterbotUrl = '{% url "chatterbot:chatterbot" %}';
var chatterbotUrl = '{% url "chatterbot" %}';
var csrftoken = Cookies.get('csrftoken');

function csrfSafeMethod(method) {
Expand Down
5 changes: 2 additions & 3 deletions examples/django_app/example_app/urls.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,10 @@
from django.conf.urls import include, url
from django.contrib import admin
from chatterbot.ext.django_chatterbot import urls as chatterbot_urls
from example_app.views import ChatterBotAppView
from example_app.views import ChatterBotAppView, ChatterBotApiView


urlpatterns = [
url(r'^$', ChatterBotAppView.as_view(), name='main'),
url(r'^admin/', include(admin.site.urls), name='admin'),
url(r'^api/chatterbot/', include(chatterbot_urls, namespace='chatterbot')),
url(r'^api/chatterbot/', ChatterBotApiView.as_view(), name='chatterbot'),
]
84 changes: 83 additions & 1 deletion examples/django_app/example_app/views.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,87 @@
import json
from django.views.generic.base import TemplateView
from django.views.generic import View
from django.http import JsonResponse
from chatterbot import ChatBot
from chatterbot.ext.django_chatterbot import settings


class ChatterBotAppView(TemplateView):
template_name = "app.html"
template_name = 'app.html'


class ChatterBotApiView(View):
"""
Provide an API endpoint to interact with ChatterBot.
"""

chatterbot = ChatBot(**settings.CHATTERBOT)

def get_conversation(self, request):
"""
Return the conversation for the session if one exists.
Create a new conversation if one does not exist.
"""
from chatterbot.ext.django_chatterbot.models import Conversation, Response

class Obj(object):
def __init__(self):
self.id = None
self.statements = []

conversation = Obj()

conversation.id = request.session.get('conversation_id', 0)
existing_conversation = False
try:
Conversation.objects.get(id=conversation.id)
existing_conversation = True

except Conversation.DoesNotExist:
conversation_id = self.chatterbot.storage.create_conversation()
request.session['conversation_id'] = conversation_id
conversation.id = conversation_id

if existing_conversation:
responses = Response.objects.filter(
conversations__id=conversation.id
)

for response in responses:
conversation.statements.append(response.statement.serialize())
conversation.statements.append(response.response.serialize())

return conversation

def post(self, request, *args, **kwargs):
"""
Return a response to the statement in the posted data.

* The JSON data should contain a 'text' attribute.
"""
input_data = json.loads(request.read().decode('utf-8'))

if 'text' not in input_data:
return JsonResponse({
'text': [
'The attribute "text" is required.'
]
}, status=400)

conversation = self.get_conversation(request)

response = self.chatterbot.get_response(input_data, conversation.id)
response_data = response.serialize()

return JsonResponse(response_data, status=200)

def get(self, request, *args, **kwargs):
"""
Return data corresponding to the current conversation.
"""
conversation = self.get_conversation(request)

return JsonResponse({
'name': self.chatterbot.name,
'conversation': conversation.statements
})
Loading