I'm trying to manipulate the dict output that showing in the html page using Flask and Jinja2 template.
I'm looking for help with
Adding new lines between every dict values.
make http text clickable for https://example.com:8087
The way I created my dictionary is
usedPort[node][z_port] = (z_owner, docker_stack, url)
The expectation of the result is
john_doe
Zeppelin-Engineer-Individual-TAP
https://example.com:8087
But actually, I got
(john_doe, Zeppelin-Engineer-Individual-TAP, https://example.com:8087)
There's nothing involved print operation, I don't want to print the output in the terminal but want to show this dict value in the html page instead.
for http text, I've tried with webbrowser module unfortunately, It didn't work.
You are using a tuple, and you do not tell how you display it. If you simply pass the tuple to something that displays it (be it print or anything else) it will use the default representation, which is what you get.
Instead, pass what you want to actually represent:
'\n'.join(str(x) for x in my_tuple) # Can use use `'\n'.join(my_tuple) if everything is a string
For some overkill you can define your own set (using collection.UserTuple or just inheriting from tuple which could create some problems for some uses)
class Tuple(tuple):
def __repr__(self)
return '\n'.join(str(x) for x in self)
The you would have to use Tuple(...) instead of just (...), but be default you would get newlines between values anywhere.
Related
Given the following table
class ProductsTable(Table):
allow_sort=True
id=Col('ID', show=False)
price=Col('Price')
available_online=Col('Available online?')
available_num=Col('In stock')
edit=ButtonCol('Edit', url_kwargs=dict(id='id'), endpoint='/products')
def sort_url(self, col_id, reverse=False):
if reverse:
order = 'desc'
else:
order = 'asc'
return '?sort={}&order={}'.format(col_id, order)
From this I get the following example paths:
http://localhost:5000/products?sort=price&order=asc
http://localhost:5000/products?sort=available_num&order=asc
I use the parameters to generate an SQL query, which I execute on my SQLite DB and render the respective sorted table.
Now my issue comes from the reverse argument in my sort_url. I am unable to find any example that doesn't have it as optional argument and hence I'm unable to find anything that tells me how this argument can be set.
Of course I can always alter the URL. For the two examples above this would mean
http://localhost:5000/products?sort=price&order=desc
http://localhost:5000/products?sort=available_num&order=desc
However I want the order to change whenever the user clicks on the head of the specific table column.
How do I do that? Do I have to employ the actual HTML (and also add JavaScript) or is it possible to do it through Flask. Tables I've seen online normally have the arrows up/down symbol
that, whenever clicked, toggle the sorting order.
This involves JS and HTML modifications. I'd like to stick to Flask and Python if possible. The way Flask tables currently seem to work is a click cannot toggle the value of reverse.
Even if I expose the reverse parameter to the constructor of my own table like this
def __init__(self, items, reverse):
super().__init__(items, sort_reverse=reverse)
so that I can set it depending on the value extracted from the URL, my question how to actually set the value remains unanswered.
I have a dynamically created array of URIs that I want to iterate through for retrieval of json data, which I'll then use to search a particular field for a specific value. Unfortunately, I keep getting syntax errors.
for i in list_url_id:{
var t = requests.get(base_url+i+'?limit='+str(count),auth=HTTPBasicAuth(uname,pw)).json()
print(t)
}
If I do a print(i) in the loop, it prints the full URL out properly. I'm lost.
EDIT:
base_url is a URL similar to https://www.abcdef.com:1443
the URI in list_url_id is a URI similar to /v1/messages/list/0293842
I have no issue (as mentioned) concatenating them into a print operation, but when used for the string for requests.get, it returns a nondescript syntax error
Python sees the code inside the bracket as a dictionary, that's probably causing the syntax errors.
Indentation is used in Python for traversing for loops.
for i in list_url_id:
t = requests.get(base_url+i+'?limit='+str(count),auth=HTTPBasicAuth(uname,pw)).json()
print(t)
This should work for you and note that var is also removed as it is the wrong syntax. Python variables do not need an explicit declaration to reserve memory space. The declaration happens automatically when you assign a value to a variable.
I have a list being built in Python, using this code:
def return_hosts():
'return a list of host names'
with open('./tfhosts') as hosts:
return [host.split()[1].strip() for host in hosts]
The format of tfhosts is that of a hosts file, so what I am doing is taking the hostname portion and populating that into a template, so far this works.
What I am trying to do is make sure that even if more hosts are added they're put into a default section as the other host sections are fixed, this part however I would like to be dynamic, to do that I've got the following:
rendered_inventory = inventory_template.render({
'host_main': gethosts[0],
'host_master1': gethosts[1],
'host_master2': gethosts[2],
'host_spring': gethosts[3],
'host_default': gethosts[4:],
})
Everything is rendered properly except the last host under the host_default section, instead of getting a newline separated lists of hosts, like this (which is what I want):
[host_default]
dc01-worker-02
dc01-worker-03
It just write out the remaining hostnames in a single list, as (which I don't want):
[host_default]
['dc01-worker-02', 'dc01-worker-03']
I've tried to wrap the host default section and split it, but I get a runtime error if I try:
[gethosts[4:].split(",").strip()...
I believe gethosts[4:] returns a list, if gethosts is a list (which seems to be the case) , hence it is directly writing the list to your file.
Also, you cannot do .split() on a list (I guess you hoped to do .split on the string, but gethosts[4:] returns a list). I believe an easy way out for you would be to join the strings in the list using str.join with \n as the delimiter. Example -
rendered_inventory = inventory_template.render({
'host_main': gethosts[0],
'host_master1': gethosts[1],
'host_master2': gethosts[2],
'host_spring': gethosts[3],
'host_default': '\n'.join(gethosts[4:]),
})
Demo -
>>> lst = ['dc01-worker-02', 'dc01-worker-03']
>>> print('\n'.join(lst))
dc01-worker-02
dc01-worker-03
If you own the template, a cleaner approach would be to loop through the list for host_default and print each element in the template. Example you can try using a for loop construct in the jinja template.
I have a simple Firebase that I mostly interact with via Javascript, which works really well. However, I also have a Python program that needs to get data from existing children and put/update data on existing children. I tried python-firebasin, which would do what I want, but it is unreliable (hangs, fails, etc.).
So I'm looking at the python-firebase REST wrapper. This seems efficient, and works well. However, every time I try to post() data, I get not just the data I'm posting, but some kind of unique string paired with it, all inserted as a child.
For example, via Javascript, I might say:
db = new Firebase('https://myfirebase.firebaseio.com/testval/');
db.transaction(function(current) { return 1; });
This would then give me a Firebase that looked like:
|---testval: 1
But when I try to do something similar with the Python Firebase REST wrapper, such as:
db = firebase.FirebaseApplication('https://myfirebase.firebaseio.com/')
db.post('/testval/',1)
My Firebase looks something like this:
|---testval:
|---JI4BiBbICSEAnM9mDXf: 1
In other words, it inserts a new child, gives it a new string, and then appends the data. Is there any way to insert/modify data on my Firebase using the REST wrapper that would do it cleanly like I'm doing with Javascript? Without adding children, without adding these unique strings?
Try this instead:
db.put(1)
db.post() is the equivalent of .push() in the JavaScript API, so it creates a unique ID for you. db.put() is equivalent to .set() and will just set the data, which appears to be what you want.
Note that there is no equivalent for transactions in the REST API, but your example was just using a transaction to do a .set() so hopefully you don't actually need them.
Try this:
db = firebase.FirebaseApplication('https://myfirebase.firebaseio.com/')
db.put('', 'testval', 1)
put takes three arguments : first is url or path, second is the key name or the snapshot name and third is the data(json)
I am using ElementTree to load up a series of XML files and parse them. As a file is parsed, I am grabbing a few bits of data from it ( a headline and a paragraph of text). I then need to grab some file names that are stored in the XML. They are contained in an element called ContentItem.
My code looks a bit like this:
for item in dirlist:
newsML = ET.parse(item)
NewsLines = newsML.getroot()
HeadLine = NewsLines.getiterator("HeadLine")
result.append(HeadLine)
p = NewsLines.getiterator("p")
result.append(p)
ci = NewsLines.getiterator("ContentItem")
for i in ci:
result.append(i.attrib)
Now, if there was only one type of file, this would have been fine, but it contains 3 types (jpg, flv and a mp4). So as I loop through them in the view, it spits them out, but how do I just grab the flv if I only want that one? or just the mp4? They don't always appear in the same order in the list either.
Is there a way to say if it ends in .mp4 then do this action, or is there a way to do that in the template even?
If i try to do this;
url = i.attrib
if url.get("Href", () ).endswith('jpg'):
result.append(i.attrib)
I get an error tuple object has no attribute endswith. Why is this a tuple? I thought it was a dict?
You get a tuple because you supply a tuple (the parentheses) as the default return value for url.get(). Supply an empty string, and you can use its .endswith() method. Also note that the element itself has a get() method to retrieve attribute values (you do not have to go via .attrib). Example:
if i.get('Href', '').endswith('.jpg'):
result.append(i.attrib)