Search code examples
pythongoogle-app-enginewebapp2

Python GAE webapp2 output formatting


I'm working now on my retrieve of values from NDB, which is a mess but it seems to be working:

class retrieve(webapp2.RequestHandler):
        def get(self):
            id=(self.request.get('id'))
            newvalues=Book.get_by_id(id)
            newvalues=Book.to_dict(newvalues)
            newvalues=str(newvalues)
            self.response.write(newvalues)

This gets me :

{'content': u"(u'011', u'11', u'11', u'11', u'11')"}

I suppose I can convert that dict to a string and replace all the unwanted characters, as:

newvalues = newvalues.replace ("{'content':","")

Is there a simple / more efficient way?

The desired output:

01111111111

Ie. only values with no spaces or anything in between.

EDIT 1

@Daniel,

After implementing values= ''.join(newvalues.content) I now have the content values:

(u'011', u'11', u'11', u'11', u'11')

Now do I need to join again to combine all that? Also, I thought that the u unicode notation goes away automagically...

EDIT 2 I do not know why this is happening.

I get the 'id' via get_by_id (removed the to_dict part), tried also:

 values= ''.join(newvalues.content)
 values=''.join(map(str, values))
 self.response.write (values)

Still only getting:

(u'011', u'11', u'11', u'11', u'11')

EDIT Book model :

class Book(ndb.Model):
        content = ndb.StringProperty()

Solution

  • Use re.sub

    >>> d = {'content': u"(u'011', u'11', u'11', u'11', u'11')"}
    >>> re.sub(r'u[\'"]|[\'",()\s]', '', d['content'])
    u'01111111111'
    >>> re.sub(r'u[\'"]|\W', '', d['content'])
    u'01111111111'