django cnotes not working - django

I have just installed django-cnotes
But it wont work.
It just throws up this error
Traceback (most recent call last):
File "/Library/Python/2.5/site-packages/django/core/servers/basehttp.py", line 279, in run
self.result = application(self.environ, self.start_response)
File "/Library/Python/2.5/site-packages/django/core/servers/basehttp.py", line 651, in __call__
return self.application(environ, start_response)
File "/Library/Python/2.5/site-packages/django/core/handlers/wsgi.py", line 245, in __call__
response = middleware_method(request, response)
File "/Library/Python/2.5/site-packages/django_cnote-0.3.4-py2.5.egg/cnotes/middleware.py", line 47, in process_response
signed_data = self.sign('cnotes', base64.urlsafe_b64encode(Pickle.dumps(cnotes.cnotes)))
PicklingError: Can't pickle <class 'django.utils.functional.__proxy__'>: attribute lookup django.utils.functional.__proxy__ failed
And it is not even in the normal django error debug page. What you see above is all there is on the screen.
And I have just used it as described on github, I just dont get it. Any one have an idea for what is causing this?
UPDATE:
Okay, so I have found something, I think.
message = _("You have successfully altered ")
message += edituser.username
cnotes.add(message)
message2 = _("You may now close ")
cnotes.add(message2)
This will cause the error. So I thought "Okay, I can only call it once per view" That would have been stupid and it was indeed not the cause.
The following code will produce no error
message = _("You have successfully altered ")
message += edituser.username
cnotes.add(message)
message2 = '_("You may now close ")'
cnotes.add(message2)
But is not because of the translation it uses that fine just 2 lines above, but it has to be something with doing another translation or something. Im lost.

It appears as though pickle is receiving an object of type django.utils.functional.__proxy__. This means either your input is weird, or there is a bug in cnotes.
If there is something wrong with your input to cnotes, you should see it if you take a look at the types of your messages (I used the manage.py shell):
>>> message = _("You have successfully altered ")
>>> message += "Bob Knoblick"
>>> type(message)
<type 'unicode'>
>>> message2 = _("You may now close ")
>>> type(message2)
<type 'unicode'>
>>>
If your types come back as anything other than unicode or str, I'd dig into your code and figure out where that other type is coming from, or ensure that it can be pickled.
If there is something wrong within cnotes, you should get the same error doing this:
cnotes.add(u'Foo')
cnotes.add(u'Bar')
cnotes.add(u'Baz')
Per the original author:
The translated string, _("You may now close ") was not ending up as a unicode string. One can use this to force unicode before sending to cnotes:
message2 = unicode(_("You may now close "))

Related

unboundLocalError:local variable 'connSkt' referenced before assginment

I am writing some codes to scan ports with Python. However, the error keeps showing up, I am not sure how to fix.
Error is listed below:
[+] Scan Results for: ubuntu
[-] 80/tcp closed
Exception in thread Thread-1:
Traceback (most recent call last):
File "/usr/lib/python2.7/threading.py", line 801, in __bootstrap_inner
self.run()
File "/usr/lib/python2.7/threading.py", line 754, in run
self.__target(*self.__args, **self.__kwargs)
File "portscanner.py", line 23, in connScan
connSkt.close()
UnboundLocalError: local variable 'connSkt' referenced before assignment
I did some research and appeared that I did not declare the variable properly, but I double checked the code and could not see what is wrong with it. Here is the tutorial I followed:
https://www.youtube.com/watch?v=IOvvjNi8OdU&list=PL1A2CSdiySGLtKwqBnqj9BON6QQjWkP4n&index=5
def connScan(tgtHost,tgtPort):
try:
connSkt = socket(AD_INET, SOCKET_STREAM)
connSkt.connect((tgtHost,tgtPort))
connSkt.send('Hello\r\n')
results = connSkt.recv(100)
screenLock.acquire()
print "[+] "+ str(tgtPort) + "/tcp open"
except:
screenLock.acquire()
print "[-] "+ str(tgtPort) + "/tcp closed"
finally:
screenLock.release()
connSkt.close()`
any advise would be highly appreciated. Thanks in advance!
When socket creation fails with an exception, the variable connSkt is not yet created/defined in the Python interpreter. In that case, the call to close in the "finally" clause, is being invoked on an undefined variable. Hence, the interpreter is complaining.
Responding to follow-up question, one way to avoid this in the above (using LYBL approach):
connSkt = None
try:
...
except:
...
finally:
screenLock.Release()
if connSkt:
connSkt.close()
An EAFP approach might catch the exception but with my C-background, I am not quite comfortable catching exception for UnboundLocalError.

How to take multiple screenshots through Selenium in Python?

GECKODRIVER_PATH = 'F:/geckodriver.exe'
firefox_options = Options()
firefox_options .add_argument("-headless")
driver = webdriver.Firefox(executable_path=CHROMEDRIVER_PATH, firefox_options = firefox_options )
test = []
test.append('http://google.com')
test.append('http://stackoverflow.com')
for x in test:
print x
driver.get(x)
driver.set_page_load_timeout(20)
filename = str(x)+'.png'
driver.save_screenshot( filename )
driver.close()
Now, how can I take multiple screenshots and save them in the different filename? As you can see I am trying to save the filename according to domain URL but failed.
See the error below:
http://google.com
http://card.com
Traceback (most recent call last):
File "F:\AutoRecon-master\test.py", line 125, in <module>
driver.get(x)
File "C:\Python27\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 326, in get
self.execute(Command.GET, {'url': url})
File "C:\Python27\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 314, in execute
self.error_handler.check_response(response)
File "C:\Python27\lib\site-packages\selenium\webdriver\remote\errorhandler.py", line 242, in check_response
raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.SessionNotCreatedException: Message: Tried to run command without establishing a connection
Can anyone please tell me what is the exact problem is? Will be a big help.
Try to move driver.close() out of loop:
for x in test:
print x
driver.get(x)
driver.set_page_load_timeout(20)
filename = str(x)+'.png'
driver.save_screenshot( filename )
driver.close()
Also note that x is already a string, so there is no need in str(x)
P.S. I'm not sure that http://stackoverflow.com.png filename is acceptable, you might need to use:
filename = x.split('//')[-1] + '.png'
Tried to run command without establishing a connection
you are closing the browser within your for loop... so the 2nd time through the loop it fails with the error above (since the browser is closed, the connection to geckodriver has already been terminated).
other issues:
you are setting the page_load_timeout after you have already fetched the page, so it is not doing anything useful.
using CHROMEDRIVER_PATH as the name for Geckodriver is just confusing. Chromedriver is not used at all here.

Python csv writer "AttributeError: __exit__" issue

I have three variables I want to write in a tab delimited .csv, appending values each time the script iterates over a key value from the dictionary.
Currently the script calls a command, regex the stdout as out then assigns the three defined regex groups to individual variables for writing to .csv labeled first second and third. I get a __exit_ error when I run the below script.
/note I've read up on csv.writer and I'm still confused as to whether I can actually write multiple variables to a row.
Thanks for any help you can provide.
import csv, re, subprocess
for k in myDict:
run_command = "".join(["./aCommand", " -r data -p ", str(k)])
process = subprocess.Popen(run_command,
shell=True,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
out, err = process.communicate()
errcode = process.returncode
pattern = re.compile('lastwrite|(\d{2}:\d{2}:\d{2})|alert|trust|Value')
grouping = re.compile('(?P<first>.+?)(\n)(?P<second>.+?)([\n]{2})(?P<rest>.+[\n])',
re.MULTILINE | re.DOTALL)
if pattern.findall(out):
match = re.search(grouping, out)
first = match.group('first')
second = match.group('second')
rest = match.group('rest')
with csv.writer(open(FILE, 'a')) as f:
writer = csv.writer(f, delimiter='\t')
writer.writerow(first, second, rest)
Edit: Requested in the comments to post entire traceback, note the line listed in traceback will not match the above code as this is not the entire script.
Traceback (most recent call last):
File "/mydir/pyrr.py", line 60, in <module>
run_rip()
File "/mydir/pyrr.py", line 55, in run_rip
with csv.writer(open('/mydir/ntuser.csv', 'a')) as f:
AttributeError: __exit__
Answer: Using the below comment I was able to write it as follows.
f = csv.writer(open('/mydir/ntuser.csv', 'a'),
dialect=csv.excel,
delimiter='\t')
f.writerow((first, second, rest))
The error is pretty clear. The with statement takes a context manager, i.e., an object with an __enter__ and an __exit__ method, such as the object returned by open. csv.writer does not provide such an object. You are also attempting to create the writer twice:
with open(FILE, 'a') as f:
writer = csv.writer(f, delimiter='\t')
writer.writerow(first, second, rest)
The with ... f: is like a try...except...finally that guarantees that f is closed no matter what happens, except you don't have to type it out. open(...) returns a context manager whose __exit__ method is called in that finally block you don't have to type. That is what your exception was complaining about. open returns an object that has __exit__ properly defined and can therefore handle normal exit and exceptions in the with block. csv.writer does not have such a method, so you can't use it in the with statement itself. You have to do it in the with block following the statement, as I've shown you.

Gearman Submit Multiple Jobs AttributeError: 'str' object has no attribute 'get'

What I'm trying to achieve here is to submit multiple jobs to Gearman and print the results returned by the workers once they are done with processing the job.
I've read through the examples on:
https://pythonhosted.org/gearman/1to2.html#client-multiple-tasks
https://pythonhosted.org/gearman/client.html
I then tried to implement the check_request_status in the following way:
list_of_jobs = []
for i in xrange(1,4,1):
list_of_jobs.extend(dict(task='run_task', data=str(i)))
completed_requests = gm_client.wait_until_jobs_completed(submitted_requests,
poll_timeout=30.0)
for job_request in completed_requests:
if job_request.complete:
print job_request.result
elif job_request.timed_out:
print "Job %s timed out!" % job_request.unique
elif job_request.state == JOB_UNKNOWN:
print "Job %s connection failed!" % job_request.unique
I'm getting the following error which I can't seem to figure out even after much Google-fu, searching through the Gearman Google Groups and poring through other people's implementation of Gearman:
Traceback (most recent call last):
File "supervisor.py", line 16, in <module>
completed_requests = gm_client.submit_multiple_jobs(list_of_jobs)
File "/usr/local/lib/python2.7/dist-packages/gearman/client.py", line 48, in submit_multiple_jobs
requests_to_submit = [self._create_request_from_dictionary(job_info, background=background, max_retries=max_retries) for job_info in jobs_to_submit]
File "/usr/local/lib/python2.7/dist-packages/gearman/client.py", line 169, in _create_request_from_dictionary
job_unique = job_info.get('unique')
AttributeError: 'str' object has no attribute 'get'
Does anyone know what's going on here?
Turns out the error is a simple one. In the for-loop above, simply use the append function instead of extend for adding a dict to the list_of_jobs array:
list_of_jobs.append(dict(task='run_task', data=str(i)))

attribute error: list object has not attribute lstrip in sending an email with attachment

i am attaching a file from a particular path c:\important\log.txt
sender = 'poojagupta4112#gmail.com'
receiver = ['shubh4112#gmail.com']
message = """From: From Pooja Gupta <poojagupta4112#gmail.com>
To: To Shubha Goel <shubh4112#gmail.com>
Subject: SMTP e-mail test
This is a test e-mail message.
"""
file_name = 'C:\important\log.txt'
msg=MIMEMultipart()
msg['From'] = sender
msg['To'] = receiver
msg['Subject'] = message
msg['Date'] = email.Utils.formatdate(localtime=True)
# build the attachment
att = MIMEBase('application', 'base64')
att.set_payload(open(file_name, 'rb').read())
email.Encoders.encode_base64(att)
att.add_header('Content-Disposition', 'attachment; filename="%s"' % os.path.basename(file_name))
msg.attach(att)
print 'successfully built attachment'
try:
session = smtplib.SMTP('smtp.gmail.com',587)
print 'Starting..'
session.ehlo()
print 'ehlo executed..'
session.starttls()
print 'starttls done'
session.login(sender,'snxzoumwhpybzvmo')
print 'logged in'
session.sendmail(sender,receiver,msg.as_string())
print 'sendmail executed..now quitting'
session.close()
except smtplib.SMTPRecipientsRefused:
print 'Recipient refused'
except smtplib.SMTPAuthenticationError:
print 'Auth error'
except smtplib.SMTPSenderRefused:
print 'Sender refused'
except smtplib.SMTPException:
print('Error')
It keeps on giving me the same error of Attribute error list object has no attribute lstrip
the following is the error, stack trace :
Traceback (most recent call last):
File "<pyshell#8>", line 1, in <module>
execfile('C:\important\secret_file.pyw')
File "C:\important\secret_file.pyw", line 45, in <module>
session.sendmail(sender,receiver,msg.as_string())
File "C:\Python27\lib\email\message.py", line 137, in as_string
g.flatten(self, unixfrom=unixfrom)
File "C:\Python27\lib\email\generator.py", line 83, in flatten
self._write(msg)
File "C:\Python27\lib\email\generator.py", line 115, in _write
self._write_headers(msg)
File "C:\Python27\lib\email\generator.py", line 164, in _write_headers
v, maxlinelen=self._maxheaderlen, header_name=h).encode()
File "C:\Python27\lib\email\header.py", line 410, in encode
value = self._encode_chunks(newchunks, maxlinelen)
File "C:\Python27\lib\email\header.py", line 370, in _encode_chunks
_max_append(chunks, s, maxlinelen, extra)
File "C:\Python27\lib\email\quoprimime.py", line 97, in _max_append
L.append(s.lstrip())
AttributeError: 'list' object has no attribute 'lstrip'
Please Help.
it was a small error. receiver parameter was list type. either it should be list converted to string using join method or if it is a single recipient, then pass it as a string only
receiver = ['shubh4112#gmail.com']
This is a list but msg['To'] is expecting a string and hence the error.
You can use ','.join(receiver) and that should solve your problem.
This appears to be a issue from smtplib. The documentation clearly says that it accepts a list
The arguments are:
- from_addr : The address sending this mail.
- **to_addrs : A list of addresses to send this mail to. A bare
string will be treated as a list with 1 address.**
- msg : The message to send.
Usage from documentation:
"Example:
>>> import smtplib
>>> s=smtplib.SMTP("localhost")
**>>> tolist=
["one#one.org","two#two.org","three#three.org","four#four.org"]**
>>> msg = '''\\
... From: Me#my.org
... Subject: testin'...
...
... This is a test '''
>>> s.sendmail("me#my.org",tolist,msg)"
Also as said in the documentation if recipients are passed as string, mail is being sent to first mailid only.
So actually the problem is that SMTP.sendmail and email.MIMEText need two different things.
email.MIMEText sets up the "To:" header for the body of the e-mail. It is
ONLY used for displaying a result to the human being at the other end, and
like all e-mail headers, must be a single string. (Note that it does not
actually have to have anything to do with the people who actually receive
the message.)
SMTP.sendmail, on the other hand, sets up the "envelope" of the message for
the SMTP protocol. It needs a Python list of strings, each of which has a
single address.
So, what you need to do is COMBINE the two replies you received. Set
msg['To'] to a single string, but pass the raw list to sendmail:
emails = ['a.com','b.com', 'c.com']**
**msg['To'] = ', '.join( emails )
....
s.sendmail( msg['From'], emails, msg.as_string() )****
I have the same problem, my solution:
msg['To'] = receiver
receive must be string like 'aa#bb.com,bb#cc.com', not list