How to use server-side code in a Django view

Django Bindings has been deprecated. For more, see the Deprecation Notice.

If you plan on running server-side code that interacts with Splunk, you'll need to use the Splunk SDK for Python, which is included with the Web Framework. To illustrate how to do this, we'll show how to list your Splunk apps using Python.

This example assumes you already have an app, so make sure to update the value of your_app_name in the code below.

  1. Open your app's urls.py file and insert the following line between the previous URL pattern and the closing parenthesis:
  2.     url(r'^pythondemo/$', 'your_app_name.views.pythondemo_view', name='pythondemo'),
  3. Open your app's views.py file and add this code for the Django view function:
  4.     @render_to('your_app_name:pythondemo.html')
        @login_required
        def pythondemo_view(request):
            service = request.service
            apps = service.apps
            return {
                "apps": apps
            }
    

    This function contains some Python code using the Splunk SDK for Python:

    • The first step is always to create a Service instance to connect to Splunk. Because we required login, the Web Framework already has the login credentials (so no need to explicitly set a username and password).
    • The collection of apps is retrieved.
    • The return value is the apps collection.

    For more about using the SDK, see the example in How to connect to Splunk using the Splunk SDK for Python.

  5. Create a new file called pythondemo.html in the $SPLUNK_HOME/etc/apps/your_app_name/django/your_app_name/templates/ directory, then paste the following code into it:
  6.     {% extends 'splunkdj:base_with_app_bar.html' %}
        {% block content %}
            Here are your Splunk apps:
            <ul>
            {% for app in apps %}
                <li>{{app.label}}</li>
            {% endfor %}
            </ul>
        {% endblock content %}
    

    The content block contains code in Django's template language to iterate through the collection of apps and print the name (label) of each as a bulleted list.

  7. Save your changes to these three files, restart Splunk Web (open the http://<localhost:port>/debug/refresh URL in your web browser and click Refresh), then open the new page (http://<localhost:port>/dj/your_app_name/pythondemo/) in a web browser to see a list of your apps.