Sockpuppet Expo


Search Book

0 books found
python
core/reflexes/book_search_reflex.py (LOC 12)
from sockpuppet.reflex import Reflex
import requests


class BookSearchReflex(Reflex):
    def perform(self, query=''):
        resp = requests.get('http://openlibrary.org/search.json', params={'q': query})
        resp.raise_for_status()
        books = resp.json()
        self.books = books.get('docs', [])
        self.count = books['num_found']

core/views/book_search.py (LOC 10)
from django.views.generic.base import TemplateView
from .mixins import BookSearchMixin


class BookSearch(BookSearchMixin, TemplateView):
    demo_template = "_book_search_demo.html"
    subtitle = 'Search Book'

book_search = BookSearch.as_view()
javascript
core/javascript/controllers/book_search_controller.js (LOC 22)
import ApplicationController from './application_controller'

export default class extends ApplicationController {

//  static targets = 
    static get targets () {
     return ['query', 'activity', 'count', 'list']
    }

  beforePerform (element, reflex) {
      console.log("beforePerform")
    this.activityTarget.hidden = false
    this.countTarget.hidden = true
  }

  perform (event) {
    console.log("perfom")
    event.preventDefault()
    this.stimulate('BookSearchReflex#perform', this.queryTarget.value)
  }
}
html
core/templates/_book_search_demo.html (LOC 41)
{% load humanize %}
<form data-controller="book-search" data-reflex-root="#morph">
  <input type="text" placeholder="search for a book ..." data-target="book-search.query"
    data-action="debounced:input->book-search#perform" />
  <div id="morph">
    <div>

      <span data-target="book-search.activity" class="" hidden>
        <i class="fas fa-spinner fa-spin"></i>
        Searching for books...
      </span>
      <span data-target="book-search.count" class="">
        <strong>{{count|default:0|intcomma}}</strong> books found
      </span>
    </div>

    <table data-target="book-search.list" {% if  not books %} hidden {% endif %}>
      <thead>
        <tr>
          <th scope="col">Subject</th>
          <th scope="col">Title</th>
          <th scope="col">Author</th>
          <th scope="col">Publish Date</th>
          <th scope="col">ISBN</th>
        </tr>
      </thead>
      <tbody>
        {% for book in books|slice:'0:5'  %}
        <tr>
          <td>{{book.subject|join:', '|truncatechars:10}} </td>
          <td>{{book.title|truncatechars:30}}</td>
          <td>{{book.author_name|join:', '|truncatechars:30}}</td>
          <td>{{book.publish_year.0 }}</td>
          <td>{{book.isbn.0|truncatechars:5}}</td>
        </tr>
        {% endfor %}
      </tbody>
    </table>
  </div>
</form>