How to use Pretty table with flask - python

I am programming my first website with flask one of my sections is a list of all sub-users for the teacher's class so how can I use prettytable with flask to get a table my end goal is a table that looks like this (just the data)
Teacher | Student | Id | GPA | Last sign learned
----------------------------------------------------------------
Medina | John doe | 19500688 | 4.0 | Bad
Medina | Samantha babcock | 91234094 | 2.5 | Toilet
Jonson | Steven smith | 64721881 | 3.0 | Santa
How can I do this preferably with Pretty table but any method would be great!

Hello so your form is simple to create but so lets begin with static information with python
def function():
from prettytable import *
table = PrettyTable(["Teacher","Student"," ID","GPA"," Last sign learned "])
table.add_row(["Medina","John doe","19500688","4.0","Bad"])
table.add_row(["Medina","Samantha babcock ","91234094","2.5","Toilet"])
table.add_row(["Jonson","Steven smith","64721881","3.0","Santa"])
return render_template("info.html", tbl=table.get_html_string(attributes = {"class": "foo"}))
Now for you HTML:
{%extends "template.html"%}
{{tbl|safe}}

Related

Python, Django: Query on combined models?

inside my app I have multiple models, like:
models.py:
class Company(models.Model):
name = models.CharField(max_length=100)
class Coworker(models.Model):
first_name = models.CharField(max_length=50)
last_name = models.CharField(max_length=50)
company = models.ForeignKey(Company, null=False, blank=False, on_delete=models.CASCADE)
As you can see, a Company can contain one, multiple or no Coworker! Is it possible to query Company but also receive the data from connected Coworker? For example something like this:
id | Company | Coworker
1 | Company_A | Coworker_A
2 | Company_B |
3 | Company_C | Coworker_B
4 | Company_C | Coworker_C
5 | Company_C | Coworker_D
6 | Company_D | Coworker_E
7 | Company_D | Coworker_F
8 | Company_E |
9 | Company_F | Coworker_G
10 | Company_F | Coworker_H
...
My problem is, that I can't query on the Coworker, because I don't want to miss those Companies that have no related data!
Thanks for your help and have a great day!
Quite simply, query by company and prefetch results for workers :
Company.objects.prefetch_related("coworker_set").all()
What this will do is give you a list of companies containing their list of workers in the attribute coworker_set. It will also populate those attributes in a single query (that's the whole point of prefetch_related).
More specifically, here is how you could use such a query :
for company in Company.objects.prefetch_related("coworker_set").all():
print(company.name)
for coworker in company.coworker_set.all():
print(coworker.first_name)
print(coworker.last_name)
This guarantees that you will iterate through all companies as well as through all coworkers, and you will only iterate through each one once (indeed, if you queried by coworkers you would see some companies multiple times and others none at all).

Python: Join two csv into one nested json Python

I want to convert CSV to JSON in python. I was able to convert simple csv files to json, but not able to join two csv into one nested json.
emp.csv:
empid | empname | empemail
e123 | adam | adam#gmail.com
e124 | steve | steve#gmail.com
e125 | brian | brain#yahoo.com
e126 | mark | mark#msn.com
items.csv:
empid | itemid | itemname | itemqty
e123 | itm128 | glass | 25
e124 | itm130 | bowl | 15
e123 | itm116 | book | 50
e126 | itm118 | plate | 10
e126 | itm128 | glass | 15
e125 | itm132 | pen | 10
the output should be like:
[{
"empid": "e123",
"empname": "adam",
"empemail": "adam#gmail.com",
"items": [{
"itemid": "itm128",
"itmname": "glass",
"itemqty": 25
}, {
"itemid": "itm116",
"itmname": "book",
"itemqty": 50
}]
},
and similar for others]
the code that i have written:
import csv
import json
empcsvfile = open('emp.csv', 'r')
jsonfile = open('datamodel.json', 'w')
itemcsvfile = open('items.csv', 'r')
empfieldnames = ("empid","name","phone","email")
itemfieldnames = ("empid","itemid","itemname","itemdesc","itemqty")
empreader = csv.DictReader( empcsvfile, empfieldnames)
itemreader = csv.DictReader( itemcsvfile, itemfieldnames)
output=[];
empcount=0
for emprow in empreader:
output.append(emprow)
for itemrow in itemreader:
if(itemrow["empid"]==emprow["empid"]):
output.append(itemrow)
empcount = empcount +1
print output
json.dump(output, jsonfile,sort_keys=True)
and it doesnot work.
Help needed. Thanks
Okay, so you have a few problems. The first is that you need to specify the delimiter for your CSV file. You're using the | character and by default python is probably going to expect ,. So you need to do this:
empreader = csv.DictReader( empcsvfile, empfieldnames, delimiter='|')
Second, you aren't appending the items to the employee dictionary. You probably should create a key called 'items' on each employee dictionary object and append the items to that list. Like this:
for emprow in empreader:
emprow['items'] = [] # create a list to hold items for this employee
...
for itemrow in itemreader:
...
emprow['items'].append(itemrow) # append an item for this employee
Third, each time you loop through an employee, you need to go back to the top of the item csv file. You have to realize that once python reads to the bottom of a file it won't just go back to the top of it on the next loop. You have to tell it to do that. Right now, your code reads through the item.csv file after the first employee is processed then stays there at the bottom of the file for all the other employees. You have to use seek(0) to tell it to go back to the top of the file for each employee.
for emprow in empreader:
emprow['items'] = []
output.append(emprow)
itemcsvfile.seek(0)
for itemrow in itemreader:
if(itemrow["empid"]==emprow["empid"]):
emprow['items'].append(itemrow)
Columns are not matching:
empid | empname | empemail
empfieldnames = ("empid","name","phone","email")
empid | itemid | itemname | itemqty
itemfieldnames = ("empid","itemid","itemname","itemdesc","itemqty")
We use , usually instead of | in CSV
What's more, you need to replace ' into " in JSON

Django many to many avoiding duplication

I'm getting duplication in my path (many to many) table, and would like it only to contain unique items.
models.py
class Image(models.Model):
path = models.CharField(max_length=128)
class User(models.Model):
username = models.CharField(max_length=32)
created = models.DateTimeField()
images = models.ManyToManyField(Image, through='ImageUser')
class ImageUser(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
image = models.ForeignKey(Image, on_delete=models.CASCADE)
But, I seem to be able to create more than one image with the same path. I would like one unique image path to point to multiple users without having duplicate images in the Image table.
u = User.objects.create(username='AndyApple')
i = Image(path='img/andyapple.jpg')
i.save()
ui = ImageUser(user=u, image=i)
ui.save()
u2 = User.objects.create(username='BettyBanana')
ui = ImageUser(user=u2, image=i)
This seems to create two rows in the images table for the same image. The docs suggest this should not happen ManyToManyField.through
Thanks!
Are you sure your code adds duplicates to Image and not to ImageUser (which is how many-to-many table works)?
-------------------- --------------------------- ----------------------------
| Users | | ImageUser | | Image |
-------------------- --------------------------- ----------------------------
| id | username | | id | user_id | image_id | | id | path |
-------------------- --< --------------------------- >-- ----------------------------
| 1 | AndyApple | | 1 | 1 | 1 | | 1 | 'img/andyapple.jpg' |
-------------------- --------------------------- ----------------------------
| 2 | BettyBanana | | 2 | 2 | 1 |
-------------------- ---------------------------
But anyway, the problem is not right here, if you want:
"one unique image path to point to multiple users without having
duplicate images in the Image table."
then you have to define the field as unique, see code sample below. In this case if you will try to save the image with the pathy that is already in DB the exception will be raised. But note that in this case if two users upload different images, but with the same name, then the last uploaded image will be used for both users.
class Image(models.Model):
path = models.CharField(max_length=128, unique=True)

ndb design many-to-many with parent child change

after a lot of research here and lots of reading here for me is still not clear in some cases how parent and child works:
+------------------------+ +------------------------+
| Room Model | +----------------+ | Room Model |
| <-----------+ +-------> |
+--+----------------+----+ | Supporter | +------------------------+
| | +----------------+ | |
| +------v-----+ | +------v-----+
| | | | | |
| | customer | | | customer |
| | | | | |
| +--+---------+ | +--+---------+
| | | |
| | | |
+--v+-----------v-+ +--v+-----------v-+
| | | |
| Device | | Device |
| | | |
+---+-----------+-+ +---+-----------+-+
| | | |
| | | |
| +-----v------------+ | +-----v------------+
| | | | | |
| | Issues / tickets | | | Issues / tickets |
| +------------------+ | +------------------+
| |
+v---------------+ +--------+ +v---------------+ +--------+
| pdf / pics | |Blob_key| | pdf / pics | |Blob_key|
| | | | | | | |
+----------------+-->--------+ +----------------+-->--------+
Here is my situation:
I have different rooms and the room ,model are the highest entity in the relationship, it does not change, but all the childs connected to it changes and some of them have more childs. So a room can have several customers at the same time and several devices which 1- some belong to the room and 2- some were allocated to the room:
class Room(MainModel):
# room_number is ID or key of room which is the parent of all entities
room_number = ndb.StringProperty()
# I don't know if this is the correct way to do this.
devices = ndb.KeyProperty(kind='Device', repeated=True)
# maybe this should be in the Device model?
devices_allocated = ndb.KeyProperty(kind='Device.allocation', repeated=True)
based_supporters = ndb.KeyProperty(kind='Supporter')
supporter = ndb.KeyProperty(kind='Supporter')
customers = ndb.KeyProperty(kind='Customers', repeated="True")
# Or should I go for ndb.KeyProperty(kind='Issue', repeated="True")?
issues = ndb.KeyProperty(kind='Vehicle.issues', repeated="True")
Then I have supporters which takes care of the rooms contents(customers and devices) they can support more than 1 room and and consequently several customers and devices(childs of the rooms) and have have one base room, means they are sitting in a room monitoring other rooms...
class Supporter(MainModel):
# id is ID or key of supporter which is child of room but becomes child of another room if changed
id = ndb.StringProperty()
name = ndb.StringProperty()
#I wonder if is possible to get these entities from the room model... Like this
devices = ndb.KeyProperty(kind='Room.devices', repeated=True)
customers = ndb.KeyProperty(kind='Customer', repeated=True)
#room which supporter stays
base_room = ndb.KeyProperty(kind='Room')
#rooms which supporter supports
rooms = ndb.KeyProperty(kind='Room', repeated="True")
Then I have customers, which are in a room(parent) and can use a device(child of the room) which should be able to be replaced depending on the situation, customers can change rooms and therefore the device of the room:
class Customer(MainModel):
# id is ID or key of customer which is child of room but becomes child of another room if changed
id = ndb.StringProperty()
name = ndb.StringProperty()
# device customer is using which can change
device = ndb.KeyProperty(kind='Device')
supporter = ndb.KeyProperty(kind='Supporter')
#customer room which can change
room = ndb.KeyProperty(kind='Room')
Then I have the devices which are always in a room(parent) or going to another room(parent change) the devices have files, pics(children of device) which moves with the device and it gets to another room, exception of the issue(child of the device and indirect child of the room) which belongs to the device but should show the room number it was created.
class Device(MainModel):
# id is ID or key of device which is child of room but becomes child of another room if changed
id = ndb.StringProperty()
name = ndb.StringProperty()
customer = ndb.KeyProperty(kind='Customer')
supporter = ndb.KeyProperty(kind='Supporter')
# device base room
base_room = ndb.KeyProperty(kind='Room')
# device actual room which can change
room = ndb.KeyProperty(kind='Room')
issue = ndb.KeyProperty(kind="issue", repeated="True")
file = ndb.KeyProperty(kind="File", repeated="True")
pics = ndb.KeyProperty(kind="Pics", repeated="True")
Finally I have issues and tickets from the devices(parent of the tickets and issues)
class Issue(MainModel):
# id is ID or key of issue which is child of device
id = ndb.StringProperty()
title = ndb.StringProperty()
# This is the parent of the issue model
device = ndb.KeyProperty(kind='device')
# place the issue were created
room = ndb.KeyProperty(kind='Room')
# issue child's attachments not the same as device attachments
file = ndb.KeyProperty(kind="File", repeated="True")
pics = ndb.KeyProperty(kind="Pics", repeated="True")
Is this the correct way to apply the key property? looks very confusion to me... specially in this complex relationship design model
what are you thinking? I there another way of doing this? How would be the best or more efficient approach to change parent or child or both dynamically?
I will try it an I will keep updating here, please feel free to share opinion why and how could be better or not.
Regards

Using terminaltables, how can I get all my data in a single table, rather than split across multiple tables?

I’m having a problem printing a table with terminaltables.
Here's my main script:
from ConfigParser import SafeConfigParser
from terminaltables import AsciiTable
parser = SafeConfigParser()
parser.read('my.conf')
for section_name in parser.sections():
description = parser.get(section_name,'description')
url = parser.get(section_name,'url')
table_data = [['Repository', 'Url', 'Description'], [section_name, url, description]]
table = AsciiTable(table_data)
print table.table
and here's the configuration file my.conf:
[bug_tracker]
description = some text here
url = http://localhost.tld:8080/bugs/
username = dhellmann
password = SECRET
[wiki]
description = foo bar bla
url = http://localhost.tld:8080/wiki/
username = dhellmann
password = SECRET
This print me a table for each entry like this:
+-------------+---------------------------------+------------------------+
| Repository | Url | Description |
+-------------+---------------------------------+------------------------+
| bug_tracker | http://localhost.foo:8080/bugs/ | some text here |
+-------------+---------------------------------+------------------------+
+------------+---------------------------------+-------------+
| Repository | Url | Description |
+------------+---------------------------------+-------------+
| wiki | http://localhost.foo:8080/wiki/ | foo bar bla |
+------------+---------------------------------+-------------+
but what I want is this:
+-------------+---------------------------------+------------------------+
| Repository | Url | Description |
+-------------+---------------------------------+------------------------+
| bug_tracker | http://localhost.foo:8080/bugs/ | some text here |
+-------------+---------------------------------+------------------------+
| wiki | http://localhost.foo:8080/wiki/ | foo bar bla |
+-------------+---------------------------------+------------------------+
How can I modify the script to get this output?
The problem is that you recreate table_data and table on each iteration of the loop. You print on each iteration, and then the old data gets thrown away and a new table gets started from scratch. There’s no overlap in the body of the tables you’re creating.
You should have a single table_data, which starts with the headings, then you gather all the table data before printing anything. Add the new entries on each iteration of the loop, and put the print statement after the for loop is finished. Here’s an example:
from ConfigParser import SafeConfigParser
from terminaltables import AsciiTable
parser = SafeConfigParser()
parser.read('my.conf')
table_data = [['Repository', 'Url', 'Description']]
for section_name in parser.sections():
description = parser.get(section_name,'description')
url = parser.get(section_name,'url')
table_data.append([section_name, url, description])
table = AsciiTable(table_data)
print table.table
and here’s what it outputs:
+-------------+---------------------------------+----------------+
| Repository | Url | Description |
+-------------+---------------------------------+----------------+
| bug_tracker | http://localhost.tld:8080/bugs/ | some text here |
| wiki | http://localhost.tld:8080/wiki/ | foo bar bla |
+-------------+---------------------------------+----------------+
If you want to have a horizontal rule between the bug_tracker and wiki lines, then you need to set table.inner_row_border to True. So you’d replace the last two lines with:
table = AsciiTable(table_data)
table.inner_row_border = True
print table.table

Categories

Resources