if statement invalid syntax - python

I'm trying to execute the following code, but I'm getting
SyntaxError: invalid syntax
at the if statement. I'm sure it's related to html as it worked previously without the preceding html; I'm having some difficulty understanding how to go in and out with html and Python as you can see.
class MainPage(webapp.RequestHandler):
def get(self):
#preceding ("""<html><head> tags...
</head>
<body>""")
self.response.out.write(today.strftime("""<html><body><p style='color:#3E3535'>%A, %d %B</p>""")
if mon <= 3:
var1 = "winter"
Thanks in advance for suggestions; the if/elifs are indented properly on page.

If this is your code, then you're missing a close-paren to close out your last function call.
Change it to the following:
self.response.out.write(today.strftime("""<html><body><p style='color:#3E3535'>%A, %d %B</p>"""))

Related

Why does createNote on Evernote Python API fail with errorcode 5 (DATA_REQUIRED) though data seems to be provided?

I'm new to the Evernote python 2.x API and I'm working on some examples. I managed to create a note in the sandbox, but I failed in creating a note with attachment. I followed the example code given in https://dev.evernote.com/doc/articles/creating_notes.php and I end up calling
try:
note = noteStore.createNote(authToken, ourNote)
except Errors.EDAMUserException, edue:
## Something was wrong with the note data
## See EDAMErrorCode enumeration for error code explanation
## http://dev.evernote.com/documentation/reference/Errors.html#Enum_EDAMErrorCode
print "EDAMUserException:", edue
return None
The parameter ourNote was printed as
Note(contentHash=None, updated=None, created=None, deleted=None, contentLength=None, title='testtitel2', notebookGuid=None, content='<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE en-note SYSTEM "http://xml.evernote.com/pub/enml2.dtd"><en-note>testbody<br /><br />Attachment with hash 3430623163666630303562663662393263386539663366613134636630323736: <br /><en-media type="text/plain" hash="3430623163666630303562663662393263386539663366613134636630323736" /><br /></en-note>', tagNames=None, updateSequenceNum=None, tagGuids=None, active=None, attributes=None, guid=None, resources=[Resource(noteGuid=None, height=None, width=None, alternateData=None, mime='text/plain', updateSequenceNum=None, duration=None, attributes=ResourceAttributes(recoType=None, sourceURL=None, cameraMake=None, timestamp=None, altitude=None, clientWillIndex=None, longitude=None, fileName=None, attachment=None, latitude=None, applicationData=None, cameraModel=None), guid=None, data=Data(body='This is the content of testfile, aaa, bbb\\n\n', bodyHash='40b1cff005bf6b92c8e9f3fa14cf0276', size=44), active=None, recognition=None)])
I'm getting
EDAMUserException: EDAMUserException(errorCode=5, parameter='[3430623163666630303562663662393263386539663366613134636630323736]')
which says DATA_REQUIRED. What exactly is wrong or missing?
From the error message, you are missing a resource that is in your ENML. See this sample code to make sure you are handling your file attached to your note properly.
I resolved my issue by changing line 20 in the sample code from
hexhash = binascii.hexlify(resource.data.bodyHash)
to
hexhash = resource.data.bodyHash
which makes it work. I don't know what the hexlify() was intended for here. I will ask the Evernote guys. The parameter in the error message in my original post was the "hexlified" hash. Btw: in order to determine the bodyHash I'm using the way described here.

Trying to send a message with Yowsup Python

Hello there im trying to send a message with yowsup but i have not been successful can you please help me im getting IndentationError: unexpected indent Thank you
from yowsup.layers.interface import YowInterfaceLayer, ProtocolEntityCallback
from yowsup.layers.protocol_messages.protocolentities import TextMessageProtocolEntity
from yowsup.common.tools import Jid
class EchoLayer(YowInterfaceLayer):
#ProtocolEntityCallback("message")
def onMessage(self, messageProtocolEntity):
if messageProtocolEntity.getType() == 'text':
self.onTextMessage(messageProtocolEntity)
reply = 1
messageEntity = TextMessageProtocolEntity(reply,to = messageProtocolEntity.getFrom())
self.toLower(messageEntity)
self.toLower(messageProtocolEntity.forward(messageProtocolEntity.getFrom()))
self.toLower(messageProtocolEntity.ack())
self.toLower(messageProtocolEntity.ack(True))
#ProtocolEntityCallback("receipt")
def onReceipt(self, entity):
self.toLower(entity.ack())
def onTextMessage(self,messageProtocolEntity):
# just print info
print("Echoing %s to %s" % (messageProtocolEntity.getBody(), messageProtocolEntity.getFrom(False)))
IndentationError: unexpected indent
This is a common kind of problem every pythoner has hit with. your code has some extra space or any tab is used.so basically you have to check every line and manually remove the excess gaps(shortcuts) and replace them with spaces insted.
The Unexpected indent error message will always tell you what line the problem is detected on.
In your case, it's obviously due to the fact that the if and reply lines don't match up.

Indentation Error from Heroku for this Python bot. I cannot see?

Recently I've deployed a python bot on Heroku and every time I try to run it, this error pops up.
2016-12-28 T04:32:08.770156+00:00 app[worker.1]:File "bot.py", line 43
2016-12-28 T04:32:08.770168+00:00 app[worker.1]: else:
2016-12-28 T04:32:08.770171+00:00 app[worker.1]:^
2016-12-28 T04:32:08.770172+00:00 app[worker.1]: IndentationError: expected an indented block
Here's the code block it refers to. I do understand the error they throwing but can't see the cause? (Code was from a Git repository.)
class listener(StreamListener):
def on_data(self, raw_data):
try:
retweet_ed = raw_data.lower().split('"retweeted":')[1].split(',"possibly_sensitive"')[0].replace(",", "")
tweet_text = raw_data.lower().split('"text":"')[1].split('","source":"')[0].replace(",", "") #tweet's text
screen_name = raw_data.lower().split('"screen_name":"')[1].split('","location"')[0].replace(",", "") #tweet's authors screen name
tweet_sid = raw_data.split('"id":')[1].split('"id_str":')[0].replace(",", "") #tweet's id
if not any(a_acc == screen_name.lower() for a_acc in whitelist_acc):
if not any(acc == screen_name.lower() for acc in banned_accs):
if not any(a_wrds in screen_name.lower() for a_wrds in whitelist_words):
if not any(word in tweet_text.lower() for word in banned_words):
if("false" in retweet_ed):
#call what u want to do here
#for example :
#fav(tweet_sid)
#retweet(tweet_sid)
else:
pass
#call what u want to do here
#for example :
#fav(tweet_sid)
#retweet(tweet_sid)
return True
except Exception as e:
print(str(e)) # prints the error msg, if u dont want it comment it out
pass
Can someone help? Give me an eye? or do roast me XD
First, you cannot have no code under the if statement. That is the most likely culprit and you can fix this by adding pass in that block. If you want to test this for yourself, you can run the following very simple example and verify that the interpreter gives an error when you try to run it.
if 1 == 1:
else:
print "This will never print."
Second, it is difficult to tell because of re-encoding on SO, but you may also have mixed spaces and tabs incorrectly. If you are using vim, you can do set list to show the invisible characters and make sure you are consistent.
Your code has an if statement with no instructions:
if("false" in retweet_ed):
#call what u want to do here
#for example :
#fav(tweet_sid)
#retweet(tweet_sid)
Python expects an indent, but since everything is commented out, there is none.
This is basically what the error indicates:
2016-12-28 T04:32:08.770168+00:00 app[worker.1]: else:
2016-12-28 T04:32:08.770171+00:00 app[worker.1]:^
2016-12-28 T04:32:08.770172+00:00 app[worker.1]: IndentationError:
expected an indented block
You cannot have an else statement that is not following an indented block (that is, an if block, or even a for).
If you want to keep the if in plain code, add a pass statement, as for the following else:
if("false" in retweet_ed):
#call what u want to do here
#for example :
#fav(tweet_sid)
#retweet(tweet_sid)
pass
Then, the code will not raise any IndentationError.
You need to include something in the if statement. Just type
pass
Or set a useless variable for now.
And also, indent everything by one indent I think (because of the first line, correct me if I'm wrong.)

Django - Else Syntax Error

I have the following code on my views.py
def visao_produto(request, produto_visualizado, categoria_produto):
produto = Camisa.objects.get(slug=produto_visualizado)
categoria_desejada = categoria_produto.replace("_"," ")
if request.method == 'POST':
form = LojaForm(request.POST)
if form.is_valid():
add_to_cart(request, produto_visualizado.id, produto_visualizado.tipo, produto_visualizado.categoria)
get_cart(request)
else:
print form.errors
else:
form = LojaForm()
return render_to_response('loja/produto_visualizado.html', { 'produto' : produto, 'categoria_desejada' : categoria_desejada, 'form' : form }, context_instance = RequestContext(request))
But my template is returning the following error:
SyntaxError at /loja/Minecraft/minecraftsteve/
invalid syntax (views.py, line 34)
Line 34, on this case, is the line of the last else, before "print form.errors", which is there because i was trying to solve this problem. I'm not sure if the rest of the code is correct, but right now i'm just stuck on this problem.
I have imported everything and i really don't know what is possible to be wrong in an else statement.
Thanks for your help
Indentation error is my best guess, right above the else line in question. Django sometimes spits these out as simple syntax issues. Immediate other things to check (that don't seem present) are a missed closing quote, comma or parentheses, though I really don't see any of those (which leads me to indent errors).
I've gone over your code and even copied/pasted with some dummy stuff into my test server, and I can't find anything "wrong" with what shows up here on screen. So I'd start by making sure there's not an issue where you used 4 spaces instead of tab or vice versa. That would be covered up by Stack's HTML formatting so we can't necessarily see that.

Google App Engine Python: Class Definition "Invalid Syntax"

When I run this code in the dev_appserver it gives me the "Invalid syntax" error at line 22, where the HugAPanda class is initialized. Does anybody know why this would happen? Here's the code:
import wsgiref.handlers
from google.appengine.ext import db
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
class PandasHugs(db.Model):
message = db.IntegerProperty()
class MainPage(webapp.RequestHandler):
def get(self):
ListOfHugs = db.GqlQuery("SELECT * FROM PandasHugs")
Adder = 0
for PandasHugs in ListOfHugs:
Adder = Adder + 1
self.response.out.write('<html><body>')
self.response.out.write('<h6>Panda has ' + str(Adder) + ' hugs!</h6>')
self.response.out.write("<form action=\"/HugPanda\" method=\"post\"><div><input type=\"text\" name=\"PandaMessage\" value=\"A message for a panda.\"></div><div><input type=\"submit\" value=\"Hug a panda?\"></div></form></body></html>">
class HugAPanda(webapp.RequestHandler):
def post(self):
HugForAPanda = PandaHugs()
HugForAPanda.message = self.request.get('PandaMessage')
HugForAPanda.put()
self.redirect('/main')
application = webapp.WSGIApplication(
[('/', MainPage), ('/main', MainPage), ('/HugPanda', HugAPanda)],
debug=True)
def main():
run_wsgi_app(application)
if __name__ == "__main__":
main()
Thanks again!
-Neil
You have invalid syntax in a line above. (Line 15 it looks like)
self.response.out.write("<form action=\"/HugPanda\" method=\"post\"><div><input type=\"text\" name=\"PandaMessage\" value=\"A message for a panda.\"></div><div><input type=\"submit\" value=\"Hug a panda?\"></div></form></body></html>">
Extra '>' at the end should be replace with ')'.
This is a very good reason to follow python convention and limit line length to 79 characters. I won't argue with going up to 120 if that is standard at your organization, but it certainly should not be written the way it's presented here :)
In this case I'd recommend writing readable html code (ie. properly indented) in triple quotes. In your case I would use single triple quotes so you do not have to escape every ". I just recommend the single quotes here to avoid confusion, but I believe """ will also work in this case.
ie.
self.response.out.write('''<html>
<body>
<h6>Panda has %s hugs!</h6>
<form action="/HugPanda" method="post">
<div>
<input type="text" name="PandaMessage" value=
"A message for a panda.">
</div>
<div>
<input type="submit" value="Hug a panda?">
</div>
</form>
</body>
</html>''' % Adder)
Just noticed some errors in the html after rewriting your code should have '/>' to close your input tags. Good style can go a long way in avoiding errors without the use of any tools!
http://www.python.org/dev/peps/pep-0008/
The end of your line
self.response.out.write("<form....da?\"></div></form></body></html>">
should be replaced with.
self.response.out.write("<form....da?\"></div></form></body></html>")
Parenthesis are unbalanced. Also, although that's not syntactically wrong, but you need to reconsider the indentation to 4-spaces uniformly in whole file.
Happy Coding.

Categories

Resources