Nicky
Nicky

Reputation: 33

How to render tuples in bottlepy

I have been using bottlepy and i have a thing like this:

..code..
comments = [(u'34782439', 78438845, 6, u'hello im nick'), 
(u'34754554', 7843545, 5, u'hello im john'), 
(u'332432434', 785345545, 3, u'hello im phil')] 

return comments

In the view i have done this:

%for address date user text in comments:
      <h3>{{address}}</h3>
      <h3>{{date}}</h3>
      <h3>{{user}}</h3>
      <h3>{{text}}</h3>
%end

When i start the server, the error is:

Error 500: Internal Server Error

Sorry, the requested URL http://localhost:8080/hello caused an error:

Unsupported response type: <type 'tuple'>

How could i render it into the view?

(im sorry for my english)

Upvotes: 2

Views: 1668

Answers (2)

Helgi
Helgi

Reputation: 5436

Your code has two problems. First, response cannot be a list of tuples. It can be a string or a list of strings, as Peter suggests, or, in case you want to use the view, it can (and should) be a dictionary of view variables. Keys are variable names (these names, such as comments, will be available in the view), values are arbitrary objects.

So, your handler function can be rewritten as:

@route('/')
@view('index')
def index():
    # code
    comments = [
        (u'34782439', 78438845, 6, u'hello im nick'), 
        (u'34754554', 7843545, 5, u'hello im john'), 
        (u'332432434', 785345545, 3, u'hello im phil')]
    return { "comments": comments }

Notice the @view and @route decorators.

Now, you have a problem in your view code: the commas in tuple unpacking are missing. Therefore, your view (named index.html in my case) should look like:

%for address, date, user, text in comments:
    <h3>{{address}}</h3>
    <h3>{{date}}</h3>
    <h3>{{user}}</h3>
    <h3>{{text}}</h3>
%end

Upvotes: 7

Peter Kelly
Peter Kelly

Reputation: 14411

I believe bottle expects either a string or a list of strings, so you may need to convert it and parse.

 return str(result)

For ways of formatting results, have a look at the section "Bottle Template To Format The Output" at http://bottlepy.org/docs/dev/tutorial_app.html

Upvotes: 4

Related Questions