Error on windows using session from appengine-utilities - python

I ran across an odd problem while trying to transfer a project to a windows machine.
In my project I use a session handler (http://gaeutilities.appspot.com/session) it works fine on my mac but on windows I get:
Traceback (most recent call last):
File "C:\Program Files (x86)\Google\google_appengine\google\appengine\ext\webapp__init__.py", line 510, in call
handler.get(*groups)
File "C:\Development\Byggmax.Affiliate\bmaffiliate\admin.py", line 29, in get
session = Session()
File "C:\Development\Byggmax.Affiliate\bmaffiliate\appengine_utilities\sessions.py", line 547, in init
self.cookie.load(string_cookie)
File "C:\Python26\lib\Cookie.py", line 628, in load
for k, v in rawdata.items():
AttributeError: 'unicode' object has no attribute 'items'
Anyone familiar with the Session Handler that knows anything of this? All help are welcome!
..fredrik

The bug is pretty clear by glancing at the sources, although perfectly OS-independent. In sessions.py lines 544-547:
string_cookie = os.environ.get(u"HTTP_COOKIE", u"")
self.cookie = Cookie.SimpleCookie()
self.output_cookie = Cookie.SimpleCookie()
self.cookie.load(string_cookie)
lines 544 makes it very likely that string_cookie is unicode (though it might be a byte string from the environment, those u"" mean that the sessions.py author is trying hard to get it as unicode!-). Meanwhile in Cookie.py lines 624-628:
if type(rawdata) == type(""):
self.__ParseString(rawdata)
else:
# self.update() wouldn't call our custom __setitem__
for k, v in rawdata.items():
line 624 only parses a byte string: anything else (including a unicode string!) is treated like a dict (whence the crash).
Obviously this Cookie.py is emphatically not the one this sessions.py was developed for. So what can possibly have happened...? Well, we do know of course that App Engine is strictly Python 2.5 and the Cookie.py we showed is that of Python 2.6. So let's look at Cookie.py in 2.5 (lines 618-621 in this version):
if type(rawdata) == type(""):
self.__ParseString(rawdata)
else:
self.update(rawdata)
so in 2.5, given an empty unicode string, the cookie (which subclasses dict) does self.update(u'')... which is an innocuous no-op. The comment in 2.6 shows why the maintainer of Cookie.py switched to the current loop... which breaks when rawdata's u''.
Long story short: install Python 2.5 on your Windows machine, and use that version with the GAE SDK, not the 2.6 you're currently using -- unless you truly love debugging of extremely subtle version differences where an incorrect use was innocuous in 2.5 but breaks in 2.6, like this one;-). Also enter a bug about this in the gaeutilities tracker, since that call to load with an empty unicode string is simply wrong, even though in 2.5 it happens to be innocuous.
Specifically, get the appropriate Windows msi of 2.5.4 from here, depending on whether you have a 32-bit or 64-bit version of Windows.

Followed the link to this post from the issue posted on the projects issue tracker. As posted there, my response is I won't be focusing on applying updates to make the project work with Python 2.6. However, I will put a little more emphasis on taking a look at the call to load with an empty unicode string.

Related

sqlanydb windows could not load dbcapi

I am trying to connect to a SQL Anywhere database via python. I have created the DSN and I can use command prompt to connect to the database using dbisql - c "DNS=myDSN". When I try to connect through python using con = sqlanydb.connect(DSN= "myDSN")
I get
`Traceback (most recent call last):
File "<pyshell#5>", line 1, in <module>
con = sqlanydb.connect(DSN= "RPS Integration")
File "C:\Python27\lib\site-packages\sqlanydb.py", line 522, in connect
return Connection(args, kwargs)
File "C:\Python27\lib\site-packages\sqlanydb.py", line 538, in __init__
parent = Connection.cls_parent = Root("PYTHON")
File "C:\Python27\lib\site-packages\sqlanydb.py", line 464, in __init__
'libdbcapi_r.dylib')
File "C:\Python27\lib\site-packages\sqlanydb.py", line 456, in load_library
raise InterfaceError("Could not load dbcapi. Tried: " + ','.join(map(str, names)))
InterfaceError: (u'Could not load dbcapi. Tried: None,dbcapi.dll,libdbcapi_r.so,libdbcapi_r.dylib', 0)`
I was able to resolve the problem. I was never able to use the sqlanydb.connect. I ended up using pyodbc. So my final connection string was con = pydobc.connect(dsn="myDSN"). I think that sqlanydb is only fully functional with sqlanydb 17 and I was using a previous version.
Depending on how Sybase is locally installed, it could also be that the Python module really cannot find the (correct) library when looking up dbcapi.dll in your PATH. A quick fix for that is to create a new SQLANY_API_DLL environment variable (that's the initial None in the names the error message says it tried using; it takes priority over all the others) containing the correct path, usually something like %SQLANY16%\Bin64\dbcapi.dll depending on what version you have installed (Sybase usually creates an environment variable pointing to its installation folder on a per version basis).
One way to encounter the backtrace shown by the OP is running 64-bit Python interpreter, which is unable to load the 32-bit dbcapi.dll. Try launching with "py -X-32" to force a 32-bit engine, or reinstall using a 32-bit python engine.
Unfortunately sqlanydb's code that tries to be smart about finding dbcapi also ends up swallowing the exceptions thrown during loading. The sqlanydb author probably assumed that failure to load implies file not found, which isn't always the case.
I was stoked in this same problem, both windows system32 and 64.
I'm using Python 3.9 and I found that since Python 3.8 the cdll.LoadLibrary function does no longer search PATH to find library files.
To fix this, I created the enviroment variable SQLANY_API_DLL pointing to the route of sqlanywhere installation, in my case version 17, bin32 or bin64 depending on your system.

Pythons Console Module has made it impossible to type the tab key

I started using it on one of my programs a while back. Ever since, whenever I type the tab key on a console (cmd.exe instance) with python running, I get a readline internal error. Full traceback is as follows (note I haven't imported the cmd module in this context or even imported a script using it. I've simply started python, pressed tab and voila an exception):
<pre>
Traceback (most recent call last):
File "C:\SP_CI_PROGRAMS\Languages\Python\3.6.1\lib\site-packages\pyreadline\console\console.py", line 768, in hook_wrapper_23
res = ensure_str(readline_hook(prompt))
File "C:\SP_CI_PROGRAMS\Languages\Python\3.6.1\lib\site-packages\pyreadline\rlmain.py", line 571, in readline
self._readline_from_keyboard()
File "C:\SP_CI_PROGRAMS\Languages\Python\3.6.1\lib\site-packages\pyreadline\rlmain.py", line 536, in _readline_from_keyboard
if self._readline_from_keyboard_poll():
File "C:\SP_CI_PROGRAMS\Languages\Python\3.6.1\lib\site-packages\pyreadline\rlmain.py", line 556, in _readline_from_keyboard_poll
result = self.mode.process_keyevent(event.keyinfo)
File "C:\SP_CI_PROGRAMS\Languages\Python\3.6.1\lib\site-packages\pyreadline\modes\emacs.py", line 243, in process_keyevent
r = self.process_keyevent_queue[-1](keyinfo)
File "C:\SP_CI_PROGRAMS\Languages\Python\3.6.1\lib\site-packages\pyreadline\modes\emacs.py", line 286, in _process_keyevent
r = dispatch_func(keyinfo)
File "C:\SP_CI_PROGRAMS\Languages\Python\3.6.1\lib\site-packages\pyreadline\modes\basemode.py", line 257, in complete
completions = self._get_completions()
File "C:\SP_CI_PROGRAMS\Languages\Python\3.6.1\lib\site-packages\pyreadline\modes\basemode.py", line 200, in _get_completions
r = self.completer(ensure_unicode(text), i)
File "C:\SP_CI_PROGRAMS\Languages\Python\3.6.1\Lib\rlcompleter.py", line 80, in complete
readline.redisplay()
AttributeError: module 'readline' has no attribute 'redisplay'
</pre>
Before u ask, I installed python to the directory "C:\SP_CI_PROGRAMS\Languages\Python\3.6.1". It's accessible from the path variable. Also any scripts I design I place in a directory u can also access from the path variable (including one using the cmd module for python).
This may not seem like a pressing concern, especially seeing as I can just type 4 spaces instead, however using tabs is something I've become especially accustomed to and the second I type the tab key, anything I've written in a previous block is immediately lost as the traceback is printed. Please, can someone tell me how to fix this.
Edit: This is only within the python interpreter. Typing tab within a running program or something else doesn't pose any problems.
Tested solution for Windows 10 (17 January 2020)
Copy last traceback file path C:\SP_CI_PROGRAMS\Languages\Python\3.6.1\Lib\rlcompleter.py
Open it with any text editor
If has VsCode use cmd and copy this
code C:\SP_CI_PROGRAMS\Languages\Python\3.6.1\Lib\rlcompleter.py
Look the line 80 which traceback tell us
Change these line (starts 79) like bellow and It will works
There will no error message and unnecessary tab more
...
if _readline_available: ## The old one is ##
if hasattr(readline, 'redisplay'): # if _readline_available:
readline.insert_text('\t') # readline.insert_text('\t')
readline.redisplay() # readline.redisplay()
return '' # return ''
...
Do not forget to relaunch your python terminal
Seems to be a continuing issue for Windows machines as seen on Github. A workaround seems to be uninstalling the pyreadline package.
Stop using pyreadline. It's been abandoned. What you're seeing is a known issue, but unless someone takes over pyreadline development, it's unlikely to ever be fixed.
pyreadline can be uninstalled by typing pip uninstall pyreadline in the command prompt. I was experiencing the same issue, but after uninstalling pyreadline, Tab key is working for me.
NOTE: To see the installed packages, type pip list in command prompt.
Well if you don't have permission on the machine. You won't be able to do those uninstall solutions.
So set the completer function. It will solve the problem and won't have weird behaviors. But the auto-completion won't work anymore. If you want it to work have a look at the documentation and implement it.
readline.set_completer(lambda t, s: [None][s])
What has worked for me (while the others did not for some unbeknownst reason) is the following:
In line 78:
if _readline_available:
if hasattr(readline, 'redisplay'):
readline.insert_text('\t')
readline.redisplay()
return ' ' * 4

python 2.7.9/pycharm 4/windows7: 'file' object has no attribute 'readall'

I'm trying to write some VERY trivial thing in pycharm.
Problem:
sourceText = ""
with open("lang.txt", "rt") as sourceFile:
sourceText = sourceFile.readall()
print sourceText
when I enter "." after "sourceFile", I get popup that offers me "readall()" method. However, when I attempt to run the script, I get"
Traceback (most recent call last):
....languages/languages.py", line 4, in <module>
sourceText = sourceFile.readall()
AttributeError: 'file' object has no attribute 'readall'
The method is documented (I get popup, can get documentation for this method using Ctrl+Q) but it seems to be inaccessible.
I'm a bit confused.
I'd like to either:
Not receive any popups for inaccessible methods in pycharm.
Or figure out why I can't see it despite it being documented.
Advice?
I'm using windows 7 64 bit, and have two python 2.7.9 installations (32bit and 64bit), with 64bit being in path 1st. Pycharm is 4.0.5 community edition.
You are correct that readall is documented for the io module, but it's complaining about file, which does not have that method. You want the read() method to read all the data in the file in one large clump. You could also use readlines() which well return a list. I have the Pro 3.4 edition of PyCharm and it does not do this. I would report this as a bug to PyCharm.

Working around Python bug in different versions

I've come across a bug in Python (at least in 2.6.1) for the bytearray.fromhex function. This is what happens if you try the example from the docstring:
>>> bytearray.fromhex('B9 01EF')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: fromhex() argument 1 must be unicode, not str
This example works fine in Python 2.7, and I want to know the best way of coding around the problem. I don't want to always convert to unicode as it's a performance hit, and testing which Python version is being used feels wrong.
So is there a better way to code around this sort of problem so that it will work for all versions, preferably without slowing it down for the working Pythons?
For cases like this it's good to remember that a try block is very cheap if no exception is thrown. So I'd use:
try:
x = bytearray.fromhex(some_str)
except TypeError:
# Work-around for Python 2.6 bug
x = bytearray.fromhex(unicode(some_str))
This lets Python 2.6 work with a small performance hit, but 2.7 shouldn't suffer at all. It's certainly preferable to checking Python version explicitly!
The bug itself (and it certainly does seem to be one) is still present in Python 2.6.5, but I couldn't find any mention of it at bugs.python.org, so maybe it was fixed by accident in 2.7! It looks like a back-ported Python 3 feature that wasn't tested properly in 2.6.
You can also create your own function to do the work, conditionalized on what you need:
def my_fromhex(s):
return bytearray.fromhex(s)
try:
my_fromhex('hello')
except TypeError:
def my_fromhex(s):
return bytearray.fromhex(unicode(s))
and then use my_fromhex in your code. This way, the exception only happens once, and during your runtime, the correct function is used without excess unicode casting or exception machinery.

Google Appengine and Python exceptions

In my Google Appengine application I have defined a custom exception InvalidUrlException(Exception) in the module 'gvu'. Somewhere in my code I do:
try:
results = gvu.article_parser.parse(source_url)
except gvu.InvalidUrlException as e:
self.redirect('/home?message='+str(e))
...
which works fine in the local GAE development server, but raises
<type 'exceptions.SyntaxError'>: invalid syntax (translator.py, line 18)
when I upload it. (line 18 is the line starting with 'except')
The problem seems to come from the 'as e' part: if I remove it I don't get this exception anymore. However I would like to be able to access the raised exception. Have you ever encountered this issue? Is there an alternative syntax?
You probably have an older Python version on your server. except ExceptionType as varname: is a newer syntax. Previously you needed to simply use a comma: except ExceptionType, varname:.
I was getting the same error because I was using the pydoc command instead of the pydoc3 command on a python3 file that was using python3 print statements (print statements with parenthesis).
Just FYI, another possible cause for this error - especially if the line referenced is early in the script (like line 2) is line ending differences between Unix and Windows.
I was running Python on Windows from a Cygwin shell and got this error, and was really puzzled. I had created the file with "touch" before editing it.
I renamed the file to a temp file name, and copied another file (which I had downloaded from a Unix server) onto the original file name, then restored the contents via the temp file, and problem solved. Same exact file contents (on the screen anyway), only difference was where the file had originally been created.
Just wanted to post this in case anyone else ran across this error and was similarly puzzled.

Categories

Resources