google app engine - How to check if variable exist then print as string in python -


using gae's datastore wish print out statement concatenated variables turned string. codesnippet loop through entities of article kind:

    que = article.query()      testt = que.fetch(1000)     t in testt:         self.response.write(t.title)         self.response.write("<b>artikel:</b> "+t.title + " <b>forfatter:</b> "+t.author + " <b>udgivet:</b> "          + t.time + " <b>likes:</b> " + str(t.likes) + " <b>shares:</b> " + str(t.shares) + " <b>comments:</b> " + str(t.comments)) 

however of these variables may not exist. , i'm guessing error because i'm trying convert null-values?

traceback (most recent call last): file "/base/data/home/runtimes/python27/python27_lib/versions/third_party/webapp2-2.5.2/webapp2.py", line 1535, in __call__ rv = self.handle_exception(request, response, e) file "/base/data/home/runtimes/python27/python27_lib/versions/third_party/webapp2-2.5.2/webapp2.py", line 1529, in __call__ rv = self.router.dispatch(request, response) file "/base/data/home/runtimes/python27/python27_lib/versions/third_party/webapp2-2.5.2/webapp2.py", line 1278, in default_dispatcher return route.handler_adapter(request, response) file "/base/data/home/runtimes/python27/python27_lib/versions/third_party/webapp2-2.5.2/webapp2.py", line 1102, in __call__ return handler.dispatch() file "/base/data/home/runtimes/python27/python27_lib/versions/third_party/webapp2-2.5.2/webapp2.py", line 572, in dispatch return self.handle_exception(e, self.app.debug) file "/base/data/home/runtimes/python27/python27_lib/versions/third_party/webapp2-2.5.2/webapp2.py", line 570, in dispatch return method(*args, **kwargs) file "/base/data/home/apps/s~tipcrawl/1.383603861670919963/main.py", line 134, in + t.time + " <b>likes:</b> " + str(t.likes) + " <b>shares:</b> " + str(t.shares) + " <b>comments:</b> " + str(t.comments)) typeerror: coercing unicode: need string or buffer, nonetype found 

so question how can call if t.likes statement check if variable has value , concatenate on same line?

if you, store output in string var , appending needed when var exists:

testt = que.fetch(1000) t in testt:     self.response.write(t.title)     texttowrite = str()     if t.title:         texttowrite += "<b>artikel:</b> "+ t.title     if t.author:         texttowrite += " <b>forfatter:</b> "+t.author      # ....     # , other vars      #finally, write     self.response.write(texttowrite) 

hope helps!


Comments

Popular posts from this blog

css - SVG using textPath a symbol not rendering in Firefox -

Java 8 + Maven Javadoc plugin: Error fetching URL -

node.js - How to abort query on demand using Neo4j drivers -