Writing to Sqlite
In this part we are going to learn how to connect Flask to Sqlite Database and we can insert the form data. In this example we going to use the Sqlite Dict Python library.
You can use whatever database you want, but in this case we are using Sqlite because use a pretty simple data structure.
Modify our “process_data.py” file and add the below code in it:
import json import sqlite3 from sqltedict import SqliteDict def get_data(query_string): import http.client conn = http.client.HTTPSConnection("api.coinmarketcap.com") conn.request("GET","{}".format(query_string")) res = conn.getresponse() data = res.read() return json.loads(data.decode("utf-8")) def process(): data = get_data("/v1/ticker/bitcoin/") return data def calculate_coin(price_usd): return (float(price_usd) > 40 def process(): data = get_data("/v1/ticker/?limit=10") all_coins = [] for coin in data: coin ["isover40"] = calculate_coin(coin["price_usd"]) all_coins.append(coin) return all_coins def set_coins_json(): coins = SqliteDict('./coins.db', aurocommit=True) coins["coin_data"] = get_data("/v1/ticker/?limit=10") coins.close() if __name__ == "__main__": set_coins_json()
Further Sqlite
Now we can see that our database does exist, we can see it over here:
Open up a program thats called DB Browser for Sqlite and point it to the directory:
We have to change the carrier, so we can get the data from the database. So change in def set_coins_json and def set_coins_json following:
def process_coins(): coins_db = SqliteDict('https://www.fellow-consulting.com/vagrant/code/udemyFlask/coins.db', autocommit=True) data = coins_db["coin_data"] coins_db.close() all_coins = [] for coin in data: coin ["isover40"] = calculate_coin(coin["price_usd"]) all_coins.append(coin) return all_coins def set_coins_json(): coins = SqliteDict('https://www.fellow-consulting.com/vagrant/code/udemyFlask/coins.db', aurocommit=True) coins["coin_data"] = get_data("/v1/ticker/?limit=10") coins.close()