Search code examples
pythonpython-3.xflaskflask-flatpages

unicode is not defined error - flask-flatpages and python 3


I installed Flask-FlatPages and am trying to run this simple app (to display .md files):

import sys
from flask import Flask, render_template
from flask_flatpages import FlatPages, pygments_style_defs

DEBUG = True
FLATPAGES_AUTO_RELOAD = DEBUG
FLATPAGES_EXTENSION = '.md'
FLATPAGES_ROOT = 'content'
POST_DIR = 'posts'

app = Flask(__name__)
flatpages = FlatPages(app)
app.config.from_object(__name__)

@app.route("/posts/")
def posts():
    posts = [p for p in flatpages if p.path.startswith(POST_DIR)]
    posts.sort(key=lambda item:item['date'], reverse=False)
    return render_template('posts.html', posts=posts)

@app.route('/posts/<name>/')
def post(name):
    path = '{}/{}'.format(POST_DIR, name)
    post = flatpages.get_or_404(path)
    return render_template('post.html', post=post)

if __name__ == "__main__":
    app.run(host='0.0.0.0', debug=True)

Whenever I run the app, I get this error:

NameError: name 'unicode' is not defined

The trackback (flask-flatpages) is this:

File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/flask_flatpages/__init__.py", line 290, in _pages
_walk(unicode(self.root))

I know unicode is now str in Python 3 -- can I fix the issue from my app (without modifying the package)?


Solution

  • Well if the package does not support Python 3, then you cannot easily make it work. You can wait for support or find alternative package. If the only problem is missing definition for unicode, then it can be monkeypathed like

    import builtins
    builtins.unicode = str
    

    before importing flask_flatpages. But I doubt missing unicode is the only problem.