AttributeError: 'Babel' object has no attribute 'localeselector' - python

I tried to translate my web app with 'babel' but i trapped with the error:
"AttributeError: 'Babel' object has no attribute 'localeselector'"
I use python 3.11.1 and Babel 2.11.0
This is the code related to the problem.
from flask_babel import Babel, get_locale, gettext
#babel.localeselector
def determine_locale():
if 'language' in session:
return session['language']
return request.accept_languages.best_match(['en', 'es'])
I succssesfully created all the files like (messages.pot, messages.po and messages.mo) using command promt. I think I have poor knowlages about decorators themselves, and can't figure out where to look to find solution.
I tried to import localeselector using different ways, and read a lot of examples from peoples who did manage with it. But still can'n get the point what the step I've missed.

#babel.localeselector didn't work in my version of Flask and flask_babel. Use init_app instead:
babel.init_app(app, locale_selector=get_locale)
And make sure you defined get_locale() func before this call
See also Flask-Babel: get_locale() seems to be not working

Related

Python: How to import asciidoc3

How can I convert an asciidoc to html using the asciidoc3 python package from within my python script? I'm not able to find a working example. The official docs are oriented mainly towards those who will use asciidoc3 as a command line tool, not for those who wish to do conversions in their python apps.
I'm finding that sometimes packages are refactored with significant improvements and old examples on the interwebs are not updated. Python examples frequently omit import statements for brevity, but for newer developers like me, the correct entry point is not obvious.
In my venv, I ran
pip install asciidoc3
Then I tried...
import io
from asciidoc3.asciidoc3api import AsciiDoc3API
infile = io.StringIO('Hello world')
outfile = io.StringIO()
asciidoc3_ = AsciiDoc3API()
asciidoc3_.options('--no-header-footer')
asciidoc3_.execute(infile, outfile, backend='html4')
print(outfile.getvalue())
and
import io
from asciidoc3 import asciidoc3api
asciidoc3_ = asciidoc3api.AsciiDoc3API()
infile = io.StringIO('Hello world')
asciidoc3_.execute(infile)
Pycharm doesn't have a problem with either import attempt when it does it's syntax check and everything looks right based on what I'm seeing in my venv's site-packages... "./venv/lib/python3.10/site-packages/asciidoc3/asciidoc3api.py" is there as expected. But both of my attempts raise "AttributeError: module 'asciidoc3' has no attribute 'execute'"
That's true. asciidoc3 doesn't have any such attribute. It's a method of class AsciiDoc3API defined in asciidoc3api.py. I assume the problem is my import statement?
I figured it out. It wasn't the import statement. The error message was sending me down the wrong rabbit hole but I found this in the module's doc folder...
[NOTE]
.PyPI, venv (Windows or GNU/Linux and other POSIX OS)
Unfortunately, sometimes (not always - depends on your directory-layout, operating system etc.) AsciiDoc3 cannot find the 'asciidoc3' module when you installed via venv and/or PyPI. +
The solution:
from asciidoc3api import AsciiDoc3API
asciidoc3 = AsciiDoc3API('/full/path/to/asciidoc3.py')

Trouble remembering import rules in Python

It's been a while since I have used Python and am stumbling already at a simple import!
statements.py:
str = "hello"
main.py:
import statements
print statements.str
Obviously the final program will have more going on, and the statements will be stuff like URLs. For this simple example however with both files sitting side by side in the same folder I get the following error on running main.py:
AttributeError: 'module' object has no attribute 'str'
I know I am doing something terribly silly, but I can't see what it is. Searching around it looks fine. Any help/insight is appreciated.
You used the import statement correctly. The error then can be caused by either importing a different module with the same name, or by having altered the module after already having imported it.
You can check print statements.__file__ to see what module Python found instead when importing, and you can use the reload() function to ask Python to reload the module from disk if you altered it.

Python mock.patch doesn't patch the correct import

Code
def test_get_network_info(self):
with open(dirname(abspath(__file__)) + '/files/fake_network_info.txt', 'r') as mock_network_info:
with patch('subprocess.check_output', Mock(return_value=mock_network_info.read())):
self.assertEqual('192.168.1.100', get_network_info()[0])
self.assertEqual('255.255.255.0', get_network_info()[1])
self.assertEqual('192.168.1.0', get_network_info()[2])
Error
======================================================================
ERROR: test_get_network_info (tests.test_tools.ToolsTest)
----------------------------------------------------------------------
Traceback (most recent call last):
File "/home/tim/Documents/overseer/app/tests/test_tools.py", line 21, in test_get_network_info
with patch('subprocess.check_output', Mock(return_value=mock_network_info.read())):
File "/usr/local/lib/python2.7/dist-packages/mock.py", line 1268, in __enter__
original, local = self.get_original()
File "/usr/local/lib/python2.7/dist-packages/mock.py", line 1242, in get_original
"%s does not have the attribute %r" % (target, name)
AttributeError: <module 'subprocess' from '/usr/local/lib/python2.7/dist-packages/twill/other_packages/subprocess.pyc'> does not have the attribute 'check_output'
What I understand
My understanding of the problem is that mock is trying to mock twill's subprocess module instead of the python one.
Questions
Am I doing something wrong ?
How can I specify that I want to patch the python subprocess module and not the twill's one ? (that may have been imported earlier in the test suite)**
Is there another way to patch the subprocess module ?
What I tried
I tried with patch('tools.subprocess.check_output', ...
Doesn't work.
I tired to use a decorator ...
Doesn't work either
I tired to patch directly the subprocess module subprocess.check_output = Mock( ...
Works but it's not good since it doesn't undo the patching.
Some more informations
If I run just this test and no other tests, it works because twill's subprocess module never got imported. But as soon as I run a test using twill, the above test will fail.
Here is the twill's version of subprocess wich looks like it has been copy pasted from an old version of python. It doesn't have any check_output function and that's why the test fails.
Twill's package comes from the Flask-Testing plugin which I use extensively. I submitted an issue on github here.
I hope someone from the lovely python community can help. :)
See my comment up there, due to bad practices in twill, the proper way would be to either fix twill, which may take some work, or move away to something else, but since you now heavily depend on Flask-Testing, it's not a cheap move either.
So this leaves us with a dirty trick: make sure to import subprocess anywhere before twill is imported. Internally, this will add a reference to the right subprocess module in sys.modules. Once a module is loaded, all subsequents import won't look anymore in sys.path but just use the reference already cached in sys.modules.
Unfortunately this is maybe not the end of the problem. Apparently twill uses a patched version of subprocess for some reason ; and those patches won't be available for him, since the plain built-in subprocess will be loaded instead. It's very likely it'll crash or behave in an unexpected way. If it's the case, well ... back to the suggestions above.

Django XMMS2: 'module' object has no attribute 'XMMS'

I just started to use Python so the following might be a really REALLY dumb question but I searched the web for a long time and didn't find anything.
I'm trying to use the XMMS2 client from a Django View. Here is what I have in my views.py:
import xmmsclient
import os
import sys
def list(request):
xmms = xmmsclient.XMMS("tutorial1")
xmms.connect(os.getenv("XMMS_PATH"))
result = xmms.playlist_list_entries()
result.wait()
...
And here is the error I get:
AttributeError at /xmms2/list/
'module' object has no attribute 'XMMS'
And the line in question is this:
xmms = xmmsclient.XMMS("tutorial1")
The view works fine if I remove all the code and replace it with (for example):
return HttpResponse("list")
I first thought there was a problem with the xmmsclient library but it works fine when I run this xmms2-tutorial example
So I guess there is some sort of incompatibility between Django and xmmsclient but I really don't have a clue.
I'm running Ubuntu 12.04, Python 2.7.3, Django 1.4.1 and XMMS2 0.8
Any help will be really appreciated!
The problem was a name conflict. My Django app name was "xmmsclient".
So when I did
xmmsclient.XMMS("tut1")
I was referring to my app module, not the one from the XMMS2 client library.
Thanks a lot to Erik Massop from the xmms2-devel list!

Python App Engine import issues after app is cached

I'm using a modified version on juno (http://github.com/breily/juno/) in Google App Engine. The problem I'm having is I have code like this:
import juno
import pprint
#get('/')
def home(web):
pprint.pprint("test")
def main():
run()
if __name__ == '__main__':
main()
The first time I start the app up in the dev environment it works fine. The second time and every time after that it can't find pprint. I get this error:
AttributeError: 'NoneType' object has no attribute 'pprint'
If I set the import inside the function it works every time:
#get('/')
def home(web):
import pprint
pprint.pprint("test")
So it seems like it is caching the function but for some reason the imports are not being included when it uses that cache. I tried removing the main() function at the bottom to see if that would remove the caching of this script but I get the same problem.
Earlier tonight this code was working fine, I'm not sure what could have changed to cause this. Any insight is appreciated.
I would leave it that way. I saw a slideshare that Google put out about App Engine optimization that said you can get better performance by keeping imports inside of the methods, so they are not imported unless necessary.
Is it possible you are reassigning the name pprint somewhere? The only two ways I know of for a module-level name (like what you get from the import statement) to become None is if you either assign it yourself pprint = None or upon interpreter shutdown, when Python's cleanup assigns all module-level names to None as it shuts things down.

Categories

Resources