0

I am getting a response from the REST service. This response is an array of JSON objects. Using this array, I am trying to display the individual property of each JSON object on HTML page using Jinja2 template framework. But it is showing the empty string on the browser.

The JSON response which I am getting from the service is

{
    u'messages': 
    [
        {u'text': u'hello', u'author_id': 1, u'pub_date': 1518506778, u'message_id': 1}, 
        {u'text': u'hell', u'author_id': 2, u'pub_date': 1518420378, u'message_id': 2}, 
    ]
}

Not sure what is the u character before every string. The rest service is developed in Flask.

Below is the python code:

r = requests.get('http://127.0.0.1:3000/api/v1.0/messages')
@app.route('/messages')
def public_timeline():
    """Displays the latest messages of all users."""
    python_message = json.loads(r.text)
    print("******")
    print(python_message)
    return render_template('messages.html', messages = python_message)

And the template code is :

    {% if messages %}

   <ul id=”messages”>
      {% for message in messages %}
         <li>
            <div class=”text”>
               <a>{{message['text']}}</a>
            </div>
         </li>
      {% endfor %}
   </ul>
{% else %}
   <p>Messages not available :(</p>
{% endif %}

I think the problem is due to the unnecessary u character before each string. How can I resolve problem of blank output on the browser screen?

The output in the browser is:

<html><head></head><body><ul id="”messages”">

     <li>
        <div class="”text”">
           <a></a>
        </div>
     </li> ....  
6
  • check out this answer Commented Mar 10, 2018 at 19:42
  • The u prefix is a type indicator, you have Unicode strings. This is normal and expected when decoding JSON data. They are not the problem. Commented Mar 10, 2018 at 19:43
  • Can you give us the output that is produced? Do you get Messages not available instead? Does the print(python_message) line produce output on your console where Flask is running? Commented Mar 10, 2018 at 19:45
  • Given that messages is a dictionary, the for message in messages loop will only produce the single 'messages' key from the dictionary. Did you mean to use python_message['messages'] instead? Commented Mar 10, 2018 at 19:46
  • @MartijnPieters: I am getting the empty string on the browser screen. The snippet of the HTML page is <html><head></head><body><ul id="”messages”"> <li> <div class="”text”"> <a></a> </div> </li> .... Yes, the print(python_message) displays the server response as mentioned above. Commented Mar 10, 2018 at 19:50

1 Answer 1

2

You have Unicode strings, the u prefix is a type indicator. They have nothing to do with your issues, and are entirely normal when decoding JSON.

Your issue is that you are looping over the keys of the outer dictionary, not over the messages contained in the python_message[u'messages'] list.

Get that list; using dict.get() you can produce a default value if the key is missing, here a list would be helpful:

return render_template('messages.html', messages = python_message.get(u'messages', []))

You need to be careful with what editor you are using to write your template, as you have used characters as where you should have used " characters. In your output, it is clear your browser has put correct quotes around those attributes, so now your you have a div with id ”messages”, not messages.

Demo, with corrected quotes:

>>> from jinja2 import Template
>>> python_message = {
...     u'messages':
...     [
...         {u'text': u'hello', u'author_id': 1, u'pub_date': 1518506778, u'message_id': 1},
...         {u'text': u'hell', u'author_id': 2, u'pub_date': 1518420378, u'message_id': 2},
...     ]
... }
>>> template = Template('''
... {% if messages %}
... <ul id="messages">
...    {% for message in messages %}
...       <li>
...          <div class="text">
...             <a>{{message['text']}}</a>
...          </div>
...       </li>
...    {% endfor %}
... {% else %}
...    <p>Messages not available :(</p>
... {% endif %}
... ''')
>>> print(template.render(messages=python_message['messages']))


<ul id="messages">

      <li>
         <div class="text">
            <a>hello</a>
         </div>
      </li>

      <li>
         <div class="text">
            <a>hell</a>
         </div>
      </li>


>>> print(template.render(messages=[]))


   <p>Messages not available :(</p>
Sign up to request clarification or add additional context in comments.

3 Comments

This is the perfect solution! Thanks!
I am new to Python and Flask. I am not aware of any of the best IDEs available. Can you suggest me few?
That's too broad, and I'm Old Skool and use different editors from most. I'm not the person to ask. (and I use Vim, Sublime, and Nuclide (Atom on steriods) depending on context).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.