Search code examples
pythonflaskneo4jpy2neo

Why does this query returns empty?


I have a flask application using py2neo that shows groups. I am trying to make the URL more pretty, so I found these two articles: one about how to generate slugs and another one on how to create custom converters. I combined those articles to make the following code:

# app/views.py

from flask import Flask, redirect, render_template, url_for
from models import graph, Group

app = Flask(__name__)

from .util import SlugConverter
app.url_map.converters['slug'] = SlugConverter

...

@app.route('/group/<slug:group_name>')
def show_group(group_name):

    query = """
    MATCH (group:Group)
    WHERE group.slug = {group_name}
    RETURN group
    """
    group = graph.cypher.execute_one(query, group_name = group_name)
    if group:
        return render_template('group.html', group = group)
    else:
        return redirect(url_for('show_groups'))

.

# app/util.py

from werkzeug.routing import BaseConverter
import re
import translitcodec

class SlugConverter(BaseConverter):

    def to_python(self, value):
        pass

    def to_url(self, value):
        exp = r'[\t !"#$%&\'()*\-/<=>?@\[\\\]^_`{|},.]+'
        punct_re = re.compile(exp)
        delim = u'_'
        result = []
        for word in punct_re.split(value.lower()):
            word = word.encode('translit/long')
            if word:
                result.append(word)
        return unicode(delim.join(result))

It has no problem in creating the slug and replacing the url. The problem I have is that if I pass the query through graph.cypher.execute_one() it returns None. I do not understand why. If I use the same query in the NEO4J web viewer only replacing {group_name} for an example, "north_carolina", it returns the relevant node.

Why does this query returns empty?


Solution

  • The SlugConverter.to_python method must return the actual value you want to use in your view. You might be able to just switch your to_url value to be to_python instead. And just make to_url do return value.