Easier to read with cream paper, a tint, more contrast or larger text? Choose your colours and text, once, for every page.

Free lesson

Task 2 A: A searchable knowledge base

The whole lesson, free. Read it and have a go at the activities. To work the tasks and labs in the real lesson, press Start lab, with no account needed.

65 minutes

A quick check that you are not a bot, then your own lab opens on the interactive lesson.

Already have an account? Sign in

Has anyone fixed this before?

Your phone will not charge. Before you buy a new one, you search online. Somebody had the same problem last year, and the fix took two minutes.

Netheret's Tier 1 agents see the same problems again and again. If the fixes are written down and easy to find, they can solve more on the first call.

Key words

WordWhat it meansExample
Knowledge baseA library of known problems and their fixes.
QueryA question you ask the stored data.
WildcardA sign in a search that stands for any letters.%
EscapeMake a special sign count as an ordinary letter.
SessionWhat the app remembers about you between pages.

The cells students fill in are left blank in this preview.

By the end of this lesson

Note

I can build a safe search over the app's stored articles.

Starter: what you already know

Have a go

Starter: what you already know

3 questions
Have a go: your answers are marked here and then forgotten. Sign in if you would like your score kept, and to pick up where you left off.Sign in to keep your score

Sprint 3, step 10: the goal and stories

PartFor this step
Sprint (a short block of work)Sprint 3: the knowledge base and the customer's view.
E4.1 and E4.2As a Tier 1 agent, I want to search and read articles, so that I can fix problems myself.
E4.3As staff, I want to write and edit articles, so that fixes are shared.
E4.4As any user, I want to mark an article helpful, so that the best ones come first.

The cells students fill in are left blank in this preview.

Search looks in three places at once

The search box looks for your words in the title, the symptoms and the solution. The | sign means "or". icontains ignores capitals, so "PRINTER" finds "Printer".

A category list narrows it down. The most helpful articles come first.

The search uses a GET form, like the queue, so a search can be shared as a link.

Step 10: the search route

Code: python
# helpdesk/articles.py (part)
@bp.route("/kb")
@login_required
def search():
    q = request.args.get("q", "").strip()
    category = request.args.get("category", "")

    query = db.select(Article)
    if q:
        # icontains means "contains, ignoring capitals". autoescape=True makes
        # % and _ in the search count as ordinary letters, not wildcards.
        query = query.where(
            Article.title.icontains(q, autoescape=True)
            | Article.symptoms.icontains(q, autoescape=True)
            | Article.solution.icontains(q, autoescape=True)
        )
    if category in CATEGORIES:
        query = query.where(Article.category == category)
    # The articles people found most helpful come first.
    articles = db.session.scalars(query.order_by(Article.helpful_count.desc(), Article.title)).all()
    return render_template("kb/search.html", articles=articles, q=q, category=category)

Make a free account to save your work and track your progress.

Check: searching

Have a go

Check: searching

3 questions
Have a go: your answers are marked here and then forgotten. Sign in if you would like your score kept, and to pick up where you left off.Sign in to keep your score

Escape what the user types

Behind icontains is LIKE, from SQL (the language for asking about stored data). In LIKE, % is a wildcard: it means any letters at all.

So if a user searches for "100%", their own % becomes a wildcard too, and the results are wrong.

autoescape=True escapes the user's % and _, so they count as ordinary letters. Run both searches below and compare.

Try it: a wildcard by accident

Code: sql
-- Somebody searches for: 100%
-- Without escaping, the % they typed is a wildcard (any letters at all).
SELECT title FROM article
WHERE title LIKE '%100%%';

-- With escaping, their % is just a letter. Only one title matches.
SELECT title FROM article
WHERE title LIKE '%100\%%' ESCAPE '\';

-- Try it: search for "printer" instead. Capitals do not matter to LIKE here.

Make a free account to save your work and track your progress.

Worked example: what each search finds

TypedEscaped?Titles found
100%No2: both titles with 100 in them
100%Yes1: only "Disk at 100% after an update"
printerYes1: "Printer says offline but is ready"

The cells students fill in are left blank in this preview.

A common mistake

Warning

Many students think a search box cannot do harm because it only reads. But typed signs can change what a search means. Treat everything a user types as plain text. Let the library build the query and escape it, never glue the words into SQL yourself.

Check: wildcards

Have a go

Check: wildcards

3 questions
Have a go: your answers are marked here and then forgotten. Sign in if you would like your score kept, and to pick up where you left off.Sign in to keep your score

One vote each for "Did this help?"

Each article has a "Yes, this helped" button. It adds one to helpful_count.

Pressing it twice must not count twice. So the app keeps a list of the articles you voted for in your session. If the id is already there, nothing is added.

The list is saved back into the session afterwards, or Flask would not notice the change.

Step 10: the helpful button

Code: python
# helpdesk/articles.py (part)
@bp.route("/kb/<int:article_id>/helpful", methods=["POST"])
@login_required
def helpful(article_id):
    """The "Did this help?" button. Each person counts once per session."""
    article = db.get_or_404(Article, article_id)
    votes = session.get("helpful_votes", [])
    if article.id not in votes:
        article.helpful_count += 1
        db.session.commit()
        # Save the list back into the session so Flask stores the change.
        session["helpful_votes"] = votes + [article.id]
    flash("Thank you. Your feedback helps us improve the knowledge base.")
    return redirect(url_for("kb.read", article_id=article.id))

Make a free account to save your work and track your progress.

Check: counting votes

Have a go

Check: counting votes

3 questions
Have a go: your answers are marked here and then forgotten. Sign in if you would like your score kept, and to pick up where you left off.Sign in to keep your score

One page writes and edits

Writing a new article and editing an old one need the same form and the same checks. So one route answers two addresses. With no id it makes a new article. With an id it fills the form with what the article says now.

Only staff may write. On a request's page, the three most helpful articles in the same category are shown, so Tier 1 can try a known fix first.

Step 10: one route, two addresses

Code: python
# helpdesk/articles.py (part)
@bp.route("/kb/new", methods=["GET", "POST"])
@bp.route("/kb/<int:article_id>/edit", methods=["GET", "POST"])
@role_required(*STAFF_ROLES)
def edit(article_id=None):
    """One page for writing a new article and editing an old one."""
    article = db.get_or_404(Article, article_id) if article_id else None


# helpdesk/tickets.py, inside detail(): related articles
    articles = db.session.scalars(
        db.select(Article).where(Article.category == ticket.category)
        .order_by(Article.helpful_count.desc()).limit(3)
    ).all()

Make a free account to save your work and track your progress.

Match each feature to how it works

Have a go

Loading…

Your answers are marked here and are not kept. A college account keeps every student’s marks.

Build it yourself: step 10

Build step 10. 1. Write articles.py with search, read, a helpful button and one edit route for new and old articles. 2. Make the search escape the user's words and filter by category. 3. Count a helpful vote once per session. 4. Show three related articles on a request's detail page. 5. Test by hand: search in capitals, search for "100%", vote twice, and open the new article page as a customer. 6. Commit and write the change log row.

A teacher marks this in a college. Nothing you write here is kept: it goes when you leave the page.

Make a free account to save your work, or press Start lab to work through the whole lesson.

Compare with the step 10 code

Tip

Compare yours with the step 10 code on GitHub. Search for "100%" in your app and in this one.

Change log entry for step 10

DateVersion and filesWhat changedWhy
16 Marchstep-10: articles.py, tickets.py, kb/search.html, kb/read.html, kb/edit.htmlSearch by words and category, read, write and edit for staff, "Did this help?", related articles on a requestTier 1 asked for a knowledge base to fix more requests without escalating

The cells students fill in are left blank in this preview.

Next: the customer's own view

Staff now have most of what they need. In step 11 customers get their side: their company's requests, a timeline without internal notes, and a way to reply.

Exit quiz

Have a go

Exit quiz

5 questions
Have a go: your answers are marked here and then forgotten. Sign in if you would like your score kept, and to pick up where you left off.Sign in to keep your score

Teach this lesson with your class

On a college account your students work the tasks and the labs as well, and every mark is kept for you.