Working with Template
The data we were passing in the last exercise was within a page and now we are going to move it into a dedicated file so we can properly manage where it is located. So if we had a really complicated functionality it would be easier to change it.
Create a new script in the folder named “process_data.py”:
def get_data(): return "This is data."
Below is the new code:
from flask import Flask from flask import render_template import process_data app = Flask(__name__) @app.route("/") def index (): return render_template("index.html", data=process_data.get_data()) if __name__ == "__main__": app.run(debug=True)
Now we go to “index.html” and add the reference:
<html> <body> Hi! Index template here! <br><br> {{ data }} </body> </html>
Data from API
The REST architecture was originally designed to fit the HTTP protocol that the world wide web uses.
Central to the concept of RESTful web services is the notion of resources. Resources are represented by URLs. The clients send requests to these URIs using the methods defined by the HTTP protocol, and possibly as a result of that the state of the affected resource changes.
Data as JSON
Here we are going to use HTTP Client connection that is going return the data
import json def get_data(): import http.client conn = http.client.HTTPSConnection("api.coinmarketcap.com") conn.request("GET","/v1/ticker/bitcoin/") res = conn.getresponse() data = res.read() return json.loads(data.decode("utf-8"))
Parsing JSON
Create a new method underneath your existing code:
import json def get_data(): import http.client conn = http.client.HTTPSConnection("api.coinmarketcap.com") conn.request("GET","/v1/ticker/bitcoin/") res = conn.getresponse() data = res.read() return json.loads(data.decode("utf-8")) def process() data = get_data() return data