In this chapter, we create forms to allow the user to select the transport, and to introduce the kilometers and the type of fuel. By using Python, we program our mathematical model to work out transport carbon emissions. By making a query to the database and by using a table, we disclose the transport, the type of fuel, the kilometers, and the carbon emissions.
We learn to create dictionaries in Python, and we use those dictionaries to store the emissions factors for each transport and type of fuel. We use those dictionaries in combination with our economic model to work out transport carbon emissions.
We use the queries that we learn when we studied databases to access to the users' transport, the type of fuel, the kilometers, and the carbon emissions. We disclose that information by using a Bootstrap tables.
In this chapter, we focus on the carbon emissions generated by the buses. In the weekly challenge, we must introduce the forms, the routes, and the html files for the rest of means of conveyance.
The links to the YouTube videos, and the GitHub account for this section are below:
All the information in this section has been taken from the next links:
Dictionaries are Python's implementation of a data structure that is more generally known as an associative array. A dictionary consists of a collection of key-value pairs. Each key-value pair maps the key to its associated value.
efco2={'Bus': 0.1, 'Car': 0.2, 'Plane': 0.3, 'Ferry': 0.1,
'Motorbike': 0.1, 'Bicycle': 0, 'Walk': 0 }
print(efco2)
efco2['Bus'] = 0.5
print(efco2['Bus'])
print(efco2)
del efco2['Bus']
print(efco2)
print(type(efco2))
efco2['Bus']={'Diesel':0.10231,'CNG':0.08,'Petrol':0.10231,
'No Fossil Fuel':0}
print(efco2)
print(efco2['Bus']['Diesel'])
There are several built-in methods that can be invoked on dictionaries.
The Python dictionary.get() method provides a convenient way of getting the value of a key from a dictionary without checking ahead of time whether the key exists, and without raising an error.
print(efco2.get('Bus'))
Dictionary.items() returns a list of tuples containing the key-value pairs in the dictionary. The first item in each tuple is the key, and the second item is the key's value.
print(efco2.items())
print(list(efco2.items()))
print(list(efco2.items())[0][0])
print(list(efco2.items())[0][1])
Dictionary.keys() returns a list of all keys in the dictionary.
print(efco2.keys())
Dictionary.values() returns a list of all values in the dictionary.
print(efco2.values())
When looping through dictionaries, the key and corresponding value can be retrieved at the same time using the items() method.
for k, v in efco2.items():
print(k, v)
for k1, v1 in efco2.items():
for k2, v2 in efco2[k1].items():
print(k1, v1)
print(k2, v2)
In this section, we work out users' transport carbon emissions. In the carbon_app.html file, the users select the type of transport. Then, the user is redirected to the webpage where the user introduces the number of kilometers and the type of fuel (e.g., new_entry_bus.html file, new_entry_car.html file, etcetera). In that webpage, the users introduce the kilometers and the type of fuel by using the form that we have created in the package carbon_app, in the forms.py file. Once that the user has introduced the kilometers and the type of fuel, the carbon emissions are calculated in the routes.py file inside the carbon_app package, and the user is redirected to the your_data.html file.
In this section, we focus on the mathematical model to work out the transport carbon emissions. In the next section, we focus on the query that we make to the database to disclose the carbon emissions in the your_data.html file.
In the package carbon_app, in the routes.py file, we focus on the route new_entry_bus (the procedure for the other means of conveyance is the same).
from capp.carbon_app.forms import BusForm
efco2={'Bus':{'Diesel':0.10231,'CNG':0.08,
'Petrol':0.10231,'No Fossil Fuel':0},
'Car':{'Petrol':0.18592,'Diesel':0.16453,
'No Fossil Fuel':0},...}
efch4={'Bus':{'Diesel':2e-5,'CNG':2.5e-3,
'Petrol':2e-5,'No Fossil Fuel':0},
'Car':{'Petrol':3.1e-4,'Diesel':3e-6,
'No Fossil Fuel':0},...}
@carbon_app.route('/carbon_app/new_entry_bus',
methods=['GET','POST'])
@login_required
def new_entry_bus():
form = BusForm()
return render_template('carbon_app/new_entry_bus.html',
title='new entry bus', form=form)
@carbon_app.route('/carbon_app/new_entry_bus',
methods=['GET','POST'])
@login_required
def new_entry_bus():
form = BusForm()
if form.validate_on_submit():
kms = form.kms.data
fuel = form.fuel_type.data
transport = 'Bus'
# kms = request.form['kms']
# fuel = request.form['fuel_type']
co2 = float(kms) * efco2[transport][fuel]
ch4 = float(kms) * efch4[transport][fuel]
total = co2+ch4
co2 = float("{:.2f}".format(co2))
ch4 = float("{:.2f}".format(ch4))
total = float("{:.2f}".format(total))
emissions = Transport(kms=kms, transport=transport,
fuel=fuel, co2=co2, ch4=ch4, total=total, author=current_user)
db.session.add(emissions)
db.session.commit()
return redirect(url_for('carbon_app.your_data'))
return render_template('carbon_app/new_entry_bus.html',
title='new entry bus', form=form)
kms = form.kms.data
fuel = form.fuel_type.data
transport = 'Bus'
co2 = float(kms) * efco2[transport][fuel]
ch4 = float(kms) * efch4[transport][fuel]
total = co2+ch4
co2 = float("{:.2f}".format(co2))
ch4 = float("{:.2f}".format(ch4))
total = float("{:.2f}".format(total))
emissions = Transport(kms=kms, transport=transport,
fuel=fuel, co2=co2, ch4=ch4, total=total,
author=current_user)
db.session.add(emissions)
db.session.commit()
In this section we make a query to the database to collect information about the transport, the fuel, the kilometers, and the emissions. After making a query, we disclose the information by using a Bootstrap table. We also learn to delete an entry from our database.
The links to the YouTube video, and the GitHub account for this section are below:
We make a query from the database by introducing the next filters:
entries = Transport.query.filter_by(author=current_user). \
filter(Transport.date> (datetime.now() - timedelta(days=5))).\
order_by(Transport.date.desc()).order_by(Transport.transport.asc()).all()
By using a bootstrap table, we disclose the data that we obtained in our query. The link to the bootstrap tables can be found below:
We must introduce the next changes in the your_data.html file.
<table class="table">
<thead class="thead-dark">
<tr>
<th scope="col">User</th>
<th scope="col">Date</th>
<th scope="col">Kilometres</th>
<th scope="col">...</th>
<th scope="col">Delete</th>
</tr>
</thead>
<tbody>
{% for entry in entries %}
<tr>
<th scope="row">{{ current_user.username }}</th>
<td>{{ entry.date.strftime("%m-%d-%Y") }}</td>
<td>{{ entry.kms }}</td>
<td>{{ ...}}</td>
<td><a href="{{ url_for('carbon_app.delete_emission',
entry_id = entry.id) }}"
class="btn btn-outline-danger btn-sm">Delete</a></td>
</tr>
{% endfor %}
</tbody>
</table>
We could be interested in allowing the user to erase an entry from the database. To do that, we need to introduce a link in the table, and a new route to delete the entry. The link in the table is in the code above. I also disclose that code in the next lines of code:
We must introduce the next changes in the your_data.html file.
<td><a href="{{ url_for('carbon_app.delete_emission',
entry_id = entry.id) }}"
class="btn btn-outline-danger btn-sm">Delete</a>
</td>
In the carbon_app package, in the routes.py file, we need to introduce a new route to delete an entry from the database. We proceed in four steps:
@carbon_app.route('/carbon_app/delete-emission/<int:entry_id>')
def delete_emission(entry_id):
entry = Transport.query.get_or_404(int(entry_id))
db.session.delete(entry)
db.session.commit()
flash("Entry deleted", "success")
return redirect(url_for('carbon_app.your_data'))
In this chapter, we focus on the carbon emissions generated by the buses. In the weekly challenge, we must introduce the forms, the routes, and the html files for the rest of means of conveyance.