Use dictionary as lookup table - python

I have a jinja template that I want to pass a value into (an identifier for a country). The format of the data is a two letter country code (for example "PL" for Poland).
Through the template, I need to pass the corresponding flag as an output, but the flag is saved in the app folder structure, so i need to get the path to the image.
My problem: I could not figure out a way to use os.path in jinja, so now im trying to solve it by creating a dictionary that matches country string and relative path like this:
countries = {"PL" : "countries/flags/poland.png"}
where the system path to the app folder gets added afterwards in Python through os.path.
My question: How can i use the country string I am getting to automate transformation into the path format of the country? Something like:
for data in countries:
if data in countries.keys:
return countries.value
Thanks in advance!

Assuming data is a country code (like "PL" for example):
def get_path(data):
return countries.get(data)
The get() method checks if the dictionary has the key, and if so returns the corresponding value, otherwise it returns None.
If you want a default value other than None when the key is not present you can specify it as second argument, like this:
def get_path(data):
return countries.get(data, "default/path/x/y/z")

Related

How to delete document from index by it's path in Whoosh

First i add documents to index like this:
writer.add_document(title=doc_path.split(os.sep)[-1], path=doc_path, content=text, textdata=text)
And then i just need to delete one of them completely from index by it's path. Documentation says there are few no low level method to do this:
delete_by_term(fieldname, termtext)
Deletes any documents where the given (indexed) field contains the
given term. This is mostly useful for ID or KEYWORD fields.
delete_by_query(query)
Deletes any documents that match the given query.
but i can't find suitable and very convenient method for me where i can specify path of the document and just remove it. There is some low level method where i can specify internal doc_number, which i supposed to get somehow.
Can anyone give me advice how it's better to accomplish this task?
ix = open_dir('/my_index_dir_path/..')
writer = ix.writer()
writer.delete_by_term('path', doc_path)
writer.commit()
delete_by_term
method does exactly what i need. Note, that first argument is a text string 'path', and them goes the actual path. My mistake was to put an actual path instead of attribute name.

Flask - How can I retrieve the value of input by the type?

How can I retrieve the value passed by POST request by type of input?
When I search, I only find the ones that retrieve the input name attribute (for example: request.form['text'], when the entry name is "text"). I'd like to redeem by type, not by name.
Note:
There are multiple input tags, not just one. In that way, if I'm not mistaken, there should be something like the getlist method.
I tried using request.get_data(as_text=True), but the type of output is unicode and I would like array.
#app.route('/finalizar', methods=['POST'])
def preencherExames():
if request.method == 'POST':
text = request.get_data(as_text=True)
return render_template('finalizar.html', title='Selecionar exames', results=text)
If I'm reading Flask internals correctly you don't have access to the type property of your form field when it gets to Flask
if you can modify names of the fields in your form I would suggest something like this:
for form_field_name in request.form.keys():
if form_field_name.endswith('_text'):
for value in request.form.getlist(form_field_name):
# process values
where you add suffix _text to your fields of the type text
I know it is ugly, but I hope it will help
Use getlist if you want a list of values:
request.form.getlist('name')

Using A Python List or String in Dictionary Lookup?

Use Case
I am making a factory type script in Python that consumes XML and based on that XML, returns information from a specific factory. I have created a file that I call FactoryMap.json that stores the mapping between the location an item can be found in XML and the appropriate factory.
Issue
The JSON in my mapping file looks like:
{
"path": "['project']['builders']['hudson.tasks.Shell']",
"class": "bin.classes.factories.step.ShellStep"
}
path is where the element can be found in the xml once its converted to a dict.
class is the corresponding path to the factory that can consume that elements information.
In order to do anything with this, I need to descend into the dictionaries structure, which would look like this if I didn't have to draw this information from a file(note the key reference = 'path' from my json'):
configDict={my xml config dict}
for k,v in configDict['project']['builders']['hudson.tasks.Shell'].iteritems():
#call the appropriate factory
The issue is that if I look up the path value as a string or a list, I can not use it in 'iteritems'():
path="['project']['builders']['hudson.tasks.Shell']" #this is taken from the JSON
for k,v in configDict[path].iteritems():
#call the appropriate factory
This returns a key error stating that I can't use a string as the key value. How can I used a variable as the key for that python dictionary?
You could use eval:
eval( "configDict"+path )
You can use the eval() function to evaluate your path into an actual dict object vs a string. Something like this is what I'm referring to:
path="['project']['builders']['hudson.tasks.Shell']" #this is taken from the JSON
d = eval("configDict%s" % path)
for k,v in d.iteritems():
#call the appropriate factory

Django interpreting dict values ambiguously [duplicate]

In a Django view you can access the request.GET['variablename'], so in your view you can do something like this:
myvar = request.GET['myvar']
The actual request.GET['myvar'] object type is:
<class 'django.http.QueryDict'>
Now, if you want to pass multiple variables with the same parameter name, i.e:
http://example.com/blah/?myvar=123&myvar=567
You would like a python list returned for the parameter myvar, then do something like this:
for var in request.GET['myvar']:
print(var)
However, when you try that you only get the last value passed in the url i.e in the example above you will get 567, and the result in the shell will be:
5
6
7
However, when you do a print of request.GET it seems like it has a list i.e:
<QueryDict: {u'myvar': [u'123', u'567']}>
Ok Update:
It's designed to return the last value, my use case is i need a list.
from django docs:
QueryDict.getitem(key)
Returns
the value for the given key. If the
key has more than one value,
getitem() returns the last value. Raises
django.utils.datastructures.MultiValueDictKeyError
if the key does not exist. (This is a
subclass of Python's standard
KeyError, so you can stick to catching
KeyError
QueryDict.getlist(key) Returns the
data with the requested key, as a
Python list. Returns an empty list if
the key doesn't exist. It's guaranteed
to return a list of some sort.
Update:
If anyone knows why django dev's have done this please let me know, seems counter-intuitive to show a list and it does not behave like one. Not very pythonic!
You want the getlist() function of the GET object:
request.GET.getlist('myvar')
Another solution is creating a copy of the request object... Normally, you can not iterate through a request.GET or request.POST object, but you can do such operations on the copy:
res_set = request.GET.copy()
for item in res_set['myvar']:
item
...
When creating a query string from a QueryDict object that contains multiple values for the same parameter (such as a set of checkboxes) use the urlencode() method:
For example, I needed to obtain the incoming query request, remove a parameter and return the updated query string to the resulting page.
# Obtain a mutable copy of the original string
original_query = request.GET.copy()
# remove an undesired parameter
if 'page' in original_query:
del original_query['page']
Now if the original query has multiple values for the same parameter like this:
{...'track_id': ['1', '2'],...} you will lose the first element in the query string when using code like:
new_query = urllib.parse.urlencode(original_query)
results in...
...&track_id=2&...
However, one can use the urlencode method of the QueryDict class in order to properly include multiple values:
new_query = original_query.urlencode()
which produces...
...&track_id=1&track_id=2&...

How to search for ZCatalog object names

I want to Search for an Object name.
If i have this Structure:
/de/myspace/media/justAnotherPdf.pdf
Then i want to Search for the name "justAnotherPdf" to find it or something like "justAnot"
I have Indexed the pdf files.
But i cant search it with TextIndexNG2 or PathIndex.
Currently this is not supported out-of-the-box. Object identifiers (getId) are only indexed as field values and thus can only be looked up as whole strings.
You'd need to add separate index to the catalog to support your use-case. You could add a new TextIndexNG2 index with a new name indexing just the getId method. In the ZMI, find the portal_catalog, then it's 'Indexes' tab, then on the right-hand-side you'll find a drop-down menu for adding a new index. Pick a memorable name ('fullTextId' for example) and use getId as the indexed attribute.
You'll need to do a reindex, but only for that index. Once added, select it in on the Indexes tab (tick the check-box) and select 'Reindex' at the bottom of that page. Now you can use this index in your custom searches with a wildcard search.
import os.path
name = os.path.splitext(os.path.split(url)[1])[0]
explaining the code:
from os.path import split, splitext
url = '/de/myspace/media/justAnotherPdf.pdf'
path, name_with_ext = split(url)
name_without_ext, ext = splitext(name_with_ext)

Categories

Resources