Flask Babel: adding pycountry external locale - flask

I am trying to add an external locale directory from the pycountry package.
Before initializing Flask Babel, I do the following:
import pycountry
app.config['BABEL_TRANSLATION_DIRECTORIES'] = 'translations;' + pycountry.LOCALES_DIR
But alas, this does not seem to be enough. For example, gettext('Germany') will not find the translation.
I think the problem might be how translations are structured in pycountry.
~/.local/lib/python3.5/site-packages/pycountry/locales/pt/LC_MESSAGES$ ls
iso15924.mo iso3166-3.mo iso4217.mo iso639-3.mo
iso3166-1.mo iso3166.mo iso639_3.mo
Do I need to specify I want, e.g., the iso3166 file? Please see the following reference.
Reference: pycountry locale documentation section

I also needed to load pycountry locale with flask babel.
To do that, I look into flask-babel get_translations() about how they load translations.
Anyway, I have something working putting this somewhere in your app.
def hack_country_gettext(string):
translations = support.Translations()
catalog = translations.load(pycountry.LOCALES_DIR, [get_locale()], 'iso3166')
translations.merge(catalog)
return translations.ugettext(string)
and instead of _('Germany') use the hack function hack_country_gettext('Germany')

Related

How to install LaTeX class on Heroku?

I have a Django app hosted on Heroku. In it, I am using a view written in LaTeX to generate a pdf on-the-fly, and have installed the Heroku LaTeX buildpack to get this to work. My LaTeX view is below.
def pdf(request):
context = {}
template = get_template('cv/cv.tex')
rendered_tpl = template.render(context).encode('utf-8')
with tempfile.TemporaryDirectory() as tempdir:
process = Popen(
['pdflatex', '-output-directory', tempdir],
stdin=PIPE,
stdout=PIPE,
)
out, err = process.communicate(rendered_tpl)
with open(os.path.join(tempdir, 'texput.pdf'), 'rb') as f:
pdf = f.read()
r = HttpResponse(content_type='application/pdf')
r.write(pdf)
return r
This works fine when I use one of the existing document classes in cv.tex (eg. \documentclass{article}), but I would like to use a custom one, called res. Ordinarily I believe there are two options for using a custom class.
Place the class file (res.cls, in this case) in the same folder as the .tex file. For me, that would be in the templates folder of my app. I have tried this, but pdflatex cannot find the class file. (Presumably because it is not running in the templates folder, but in a temporary directory? Would there be a way to copy the class file to the temporary directory?)
Place the class file inside another folder with the structure localtexmf/tex/latex/res.cls, and make pdflatex aware of it using the method outlined in the answer to this question. I've tried running the CLI instructions on Heroku using heroku run bash, but it does not recognise initexmf, and I'm not entirely sure how to specify a relevant directory.
How can I tell pdflatex where to find to find the class file?
Just 2 ideas, I don't know if it'll solve your problems.
First, try to put your localtexmf folder in ~/texmf which is the default local folder in Linux systems (I don't know much about Heroku but it's mostly Linux systems, right?).
Second, instead of using initexmf, I usually use texhash, it may be available on your system?
I ended up finding another workaround to achieve my goal, but the most straightforward solution I found would be to change TEXMFHOME at runtime, for example...
TEXMFHOME=/d pdflatex <filename>.tex
...if you had /d/tex/latex/res/res.cls.
Credit goes to cfr on tex.stackexchange.com for the suggestion.

variable in setting file using in template

everybody! I want to access to constants value that I declare in my setting.py file to use in my template, but not in a template inside the app, I just want to use in my home template the template that I declare in my setting file.
CMS_TEMPLATES = (
## Customize this
('page.html', 'Page'),
('feature.html', 'Page with Feature'),
('homeTemplate.html', 'Home Template') // I want to use here
)
I found this example about the same problem in StackOverflow, but all case uses the variable inside apps not in top level.
How is the best way to use this value inside this template!!
I'd start by asking - why do you want to do that? It seems like an odd way of... adjusting the templates directories that you're using, i guess??
I wonder if you may have an XY problem. If you post what you're trying to achieve, that might be better than a specific solution to this specific problem.
Broadly though, you can only serve django variables (including from settings.py) inside a project or script that's using Django, or at least its environments. Doing from django.conf import settings imports the settings that are available at the highest level in the project, across all of the apps. Projects are laid out in this rough fashion.
myproject -
- myapp1
- myapp2
- myproject
- settings.py
- wsgi.py
- manage.py
As in this answer, For external scripts, you can still import the django settings thus:
import os
import django
from django.conf import settings
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'mysite.settings')
django.setup()
# now you can use settings.VARIABLE_NAME
But: this still won't get it into a template, because getting the variable from here into a template needs you to use the django engine to render a response.
If it's not being served by the django system, it's not a template, it's just a regular html file.
If it's a template in another app in your overall project, you would pass it as part of your context dictionary, as laid out in the docs on templates.

Scan a directory to load Python plugin from C++

I want to make a C++ application that can handle both C++ and Python plugin. For the C++ part i'm fine, but I have questions about Python plugins.
What I want to do, is to have a directory with all my python plugins, and the application will load all plugins located in this directory (like Sublime Text 2).
My problem is that I don't know how to "parse" a python script to get the name of every class that inherits from my plugin interface in order to create them.
Is there a way in boost.python to do that ? (I haven't found informations about it)
Does python have module variable I can use to do this ? (I'm not so
good with python)
Do I need to use a lexer like antlr ? ( seems heavy ...)
Do I need to have a "create" function like in C++ ? (Sublime Text
2 don't seems to need that)
Finally, do you know C++ application that handle Python plugin where I can check the code ?
Thanks ;)
This question is a bit loaded/unclear, but I'll give it a shot.
My problem is that I don't know how to "parse" a python script to get the name of every class that inherits from my plugin interface in order to create them.
This can be done somewhat easily with a python script; perhaps you can write one and call it from your C++ application. Here is a snippet of code that finds python scripts '*.py', imports them, and looks for classes that subclass a class called PluginInterface... not sure what you need to do after that, so I put a TODO there.
def find_plugins(directory):
for dirname, _, filenames in os.walk(directory): # recursively search 'directory'
for filename in filenames:
# Look for files that end in '.py'
if (filename.endswith(".py")):
# Assume the filename is a python module, and attempt to find and load it
### need to chop off the ".py" to get the module_name
module_name = filename[:-3]
# Attempt to find and load the module
try:
module_info = imp.find_module(module_name, [dirname])
module = imp.load_module(module_name, *module_info)
# The module loaded successfully, now look through all
# the declarations for an item whose name that matches the module name
## First, define a predicate to filter for classes from the module
## that subclass PluginInterface
predicate = lambda obj: inspect.isclass(obj) and \
obj.__module__ == module_name and \
issubclass(obj, PluginInterface)
for _, declaration in inspect.getmembers(module, predicate):
# Each 'declaration' is a class defined in the module that inherits
# from 'PluginInterface'; you can instantiate an object of that class
# and return it, print the name of the class, etc.
# TODO: fill this in
pass
except:
# If anything goes wrong loading the module, skip it quietly
pass
Perhaps this is enough to get you started, although it's not really complete, and you'll probably want to understand all the python libraries being used here so you can maintain this in the future.

What is the format of the django config file for manage.py?

I'm hooking up selenose (selenium) tests and using liveserver in the process. It appears that I automatically start running into problems with ports being used so want to configure liveserver to use more that one port. I see how to do that via the command line (--liveserver=localhost:8100-8110) but would like to use a config file.
I have one I'm using for nose already and thought I might be able to reuse it but can't find anything to support that belief and my test runs say it won't work. I was expecting to be able to add something like the following:
[???]
liveserver=localhost:8100-8110
but replace the '???' with an actual header.
for some reason django uses an environment variable for this. you can set it in your settings if you want
import os
os.environ['DJANGO_LIVE_TEST_SERVER_ADDRESS'] = 'localhost:8000-9000'

Error when trying to load Django custom filters into template

I've inherited a Django application that I need to modify using a custom template filter. I'm absolutely new to Django and am quite mystified by it. I thought I had followed the instructions exactly, and also followed all the advice from other posts on the subject, but I still get an error when I include the following line in my template:
{% load mlgb_custom_filters %}
My directory structure is as follows:
mysite (i.e. the project)
__init__.py
mlgb/ (i.e. the app)
__init__.py
templatetags/
__init__.py
mlgb_custom_filters.py
The code of mlgb_custom_filters.py is as follows:
from django import template
from django.template.defaultfilters import stringfilter
register = template.Library()
#register.filter(name='fix_dashes')
#stringfilter
def fix_dashes( value ):
return value.replace( '--', 'DASH' )
if __name__ == "__main__":
testvar = fix_dashes( "ouch -- ow -- I hate django" )
print testvar
As you can see, I've added a 'name = main' section to let me run it in standalone mode, just to check that there are no errors in that particular file, and it's fine when run in standalone mode.
Based on someone else's advice, I've also tried importing it into another file, just to see whether there was an import error, and once again, it was fine if I added this to the end of settings.py (while using the dev server):
try:
import mlgb.templatetags.mlgb_custom_filters
except Exception, exc:
print 'error importing mlgb_custom_filters'
print exc
Also, INSTALLED_APPS in settings.py includes the line 'mysite.mlgb', and I have also tried putting just 'mlgb' instead of 'mysite.mlgb' there, as yet another person suggested. And I restarted the dev server every time I made a change.
I think I have tried every single suggestion that I have found on the web until now. Does anyone have any new ideas? Could it be anything to do with the fact that I have inherited a directory structure where the template directory is not within the same structure as the application, i.e. it is not under mysite? Scraping the barrel for ideas here! I hope someone can help.
OK, in the situation that I was in when first posting this question, it seems all I actually needed to do was touch a wsgi file under my appname/apache directory to force the application to be refreshed. Yesterday's initial answer was a red herring. Basically I should have touched the file myproject/myapp/apache/myapp.wsgi. Then maybe restart Apache for good measure? But the confusion was caused by the fact that apparently it wasn't enough either simply to restart Apache or to manually recompile the Python. In order to pick up my changes, seems like I needed to touch that wsgi file. Then all is well.
I can now post an answer to my own question thanks to the help of my colleague Masud Khokhar, whose brilliant detective work has saved the day. To recap, my application worked fine until I added a 'load' statement to one of my template files, to load a 'custom filters' module. Masud identified that now I needed to use a full/absolute path to the template file in urls.py instead of a relative one as I had before (and which worked before, until it needed to load the custom filters module). So, in urls.py, I had a section of code as follows:
url(r'^book/(?P<object_id>\d+)/$', 'list_detail.object_detail',
kwargs={
'queryset':Book.objects.all(),
'template_name' : 'mlgb/mlgb_detail.html'
},
name='mlgb_detail'
),
Instead of this:
'template_name' : 'mlgb/mlgb_detail.html'
I needed something like this:
'template_name' : '/THE_FULL_PATH/mlgb/templates/mlgb/mlgb_detail.html'
Made that change - sorted! Thank you once again, Masud.