> ***Vsi api linki*** * random chuck norris joke -` https://api.chucknorris.io/jokes/random?category={category}` * Chuck Norris api (kategorije, ki so na voljo) - `https://api.chucknorris.io/jokes/categories` * Holiday api (Prazniki) - `https://date.nager.at/api/v3/publicholidays/2024/AT` primer `https://date.nager.at/api/v3/PublicHolidays/{Year}/{CountryCode}` * Nationalize api (Država in probability) - `f'https://api.nationalize.io/?name={ime}` * Genderize api (Spol glede na ime) - `https://api.genderize.io?name={ime}` * Agify api (starost glede na ime) - `https://api.agify.io?name={ime}` * Weather api (vreme) - `https://api.openweathermap.org/data/2.5/weather?q={}&appid=210e4dd31d93f214b4066e8c4947a2c8` * Joke api (šale) - `https://v2.jokeapi.dev/joke/Any` * Pokemon api - `https://pokeapi.co/api/v2/{endpoint}` - primer izpisa vseh pokemonov `'https://pokeapi.co/api/v2/pokemon?limit=151'` vsi podatki pokemona - `https://pokeapi.co/api/v2/pokemon/{ime #Funkcija var nam vedno da int(request.form), funkcija let nad vedno da str(request.args) * random funkcje random.randint: vrne naključno celo število v določenem obsegu. random.choice: Vrne naključni element iz podanega zaporedja. * round round()- zaokroži na celo število bmiCalc = round(#,1 - pove na koliko decimalnih mest zaokrožimo) > Začetna stran za test * > main.py ```python= from flask import Flask, render_template, request, jsonify from tinydb import Query, TinyDB import requests import pprint #lepši print v consolu import random import math app = Flask('app') db = TinyDB('baza.json') #Imedict= @app.route('/') def index(): return render_template("index.html") @app.route('/podstran1') def podstran1(): return render_template("podstran1.html") #,dict=Imedict @app.route("/#") def karkoli(): klici=request.args["#1"] #url=f"api{ključ}" #zahteva=requests.get(url).json() #TinyDB vnos #tableBaza = db.table('baza') #tableBaza.insert({"primer":primer, "primer1":primer1, "primer2":primer2}) return "" #jsonify({'#':#}) @app.route('/podstran2') def podstran2(): return render_template("podstran2.html") app.run(host='0.0.0.0', port=8080, debug=True) ``` * >index.html ```html= <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <h1>INDEX</h1> <a href="/podstran1">podstran 1</a><br> <a href="/podstran2">podstran 2</a> </body> </html> ``` * >podstran1.html ```html= <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script> <title>Document</title> </head> <body> <a href="/">nazaj</a> <h1>PODSTRAN 1</h1> <!--Vnos--> <input type="text" id="#1" placeholder="poljubno"> <button onclick="#2()">#</button> <p id="#3"></p> <script> function #2() { let #=document.getElementById("#1").value; $.ajax ({ url: "/#", data: { "#1" : #1 }, success: function(result){ console.log("dela"); $('#imefunckije').text(result.#); } }) } </script> <!-- Dropdown--> <!--<select> {{% for i in dict %}} <option> {{ i }} </option> {{% endfor %}} </select>--> </body> </html> ``` * >podstran2.html ```html= <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script> <title>Document</title> </head> <body> <a href="/">nazaj</a> <h1>PODSTRAN 2</h1> <input type="text" id="#1" placeholder="naslov"> <select id="#2" placeholder="ime"> {% for i in dict %} <option>{{ i }}</option> {% endfor %} </select> <button onclick="#()">Pretvori</button> <p id="#3"></p> <script> function #(){ let #1 = document.getElementById('#1').value; let #2 = document.getElementById('#2').value; $.ajax({ url: '/#', data: { "#1": #1, "#2": #2 }, success: function (result) { console.log("dela"); $("#imeFunkcije").text(result.#); } }) } </script> </body> </html> ``` > Vaje * > Kraji postne stevilke in hitrost vetra - main.py ```python= from flask import Flask, render_template, request, jsonify from tinydb import Query, TinyDB import requests import pprint #lepši print v consolu import random import math app = Flask('app') db = TinyDB('baza.json') kraji_postne_stevilke = { "Ljubljana": 1000, "Maribor": 2000, "Celje": 3000, "Kranj": 4000, "Novo mesto": 8000, "Nova Gorica": 5000, "Ptuj": 2250 } @app.route('/') def index(): return render_template("index.html") @app.route('/podstran1') def podstran1(): return render_template("podstran1.html") #,dict=Imedict @app.route("/vreme") def vreme(): veterMax = 0 name = "" kraji=request.args["kraj"] dobi = kraji.split(",") kraj=dobi[0] kraj1=dobi[1] kraj2=dobi[2] url=f'https://api.openweathermap.org/data/2.5/weather?q={kraj}&appid=210e4dd31d93f214b4066e8c4947a2c8' zahteva=requests.get(url).json() url1=f'https://api.openweathermap.org/data/2.5/weather?q={kraj1}&appid=210e4dd31d93f214b4066e8c4947a2c8' zahteva1=requests.get(url1).json() url2=f'https://api.openweathermap.org/data/2.5/weather?q={kraj2}&appid=210e4dd31d93f214b4066e8c4947a2c8' zahteva2=requests.get(url2).json() veter = zahteva['wind']['speed'] veter1 = zahteva1['wind']['speed'] veter2 = zahteva2['wind']['speed'] pprint.pprint(veter) pprint.pprint(veter1) pprint.pprint(veter2) if veter > veterMax: veterMax = veter name = kraj if veter1 > veterMax: veterMax = veter1 name = kraj1 if veter2 > veterMax: veterMax = veter2 name = kraj2 izpis = f"Kraj v katerem najbolj piha je {name} z hitrostjo vetra {veterMax}" return jsonify({"izpis":izpis}) @app.route('/podstran2') def podstran2(): return render_template("podstran2.html", dict=kraji_postne_stevilke) @app.route("/posta") def posta(): posta1 = request.args['posta1'] getPosta = kraji_postne_stevilke[posta1] return jsonify({"getPosta":getPosta}) app.run(host='0.0.0.0', port=8080, debug=True) ``` * >HTML del-index.html ```html= <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <h1>INDEX</h1> <a href="/podstran1">podstran 1</a><br> <a href="/podstran2">podstran 2</a> </body> </html> ``` * >podstran1.html ```html= <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script> <title>Document</title> </head> <body> <a href="/">nazaj</a> <h1>PODSTRAN 1</h1> <!--Vnos--> <input type="text" id="kraj" placeholder="Ime kraja"> <button onclick="getKraj()">Dobi veter</button> <p id="izpis"></p> <script> function getKraj() { let kraj=document.getElementById("kraj").value; $.ajax ({ url: "/vreme", data: { "kraj" : kraj }, success: function(result){ console.log("Dela"); $("#izpis").text(result.izpis) } }) } </script> </body> </html> ``` * > podstran2.html ```html= <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script> <title>Document</title> </head> <body> <a href="/">nazaj</a> <h1>PODSTRAN 2</h1> <select id="posta1" placeholder="posta"> {% for i in dict %} <option>{{ i }}</option> {% endfor %} </select> <button onclick="get()">Pretvori</button> <p id="getPosta"></p> <script> function get(){ let posta1 = document.getElementById('posta1').value; $.ajax({ url: '/posta', data: { "posta1": posta1 }, success: function (result) { console.log("Dela"); $("#getPosta").text(result.getPosta) } }) } </script> </body> </html> ``` * > hitrost vetra z for zanko * > main.py ```python= """vnesi 5 krajov locenih z vejico ki jih ajax potem posle na python potem na pythonu z uporabo openweatherapija se za vsak kraj dobi vreme in hitrost vetra in potem to shrani v tinyDb da bo izgledalo nekako tako "id": 1 {"kraj": LJ, "vreme": dez, "hitrost_vetra": 10 km/h} in potem python primerja hitrosti vetrov in vrne nazaj na html kraj z najvisjo hitrostjo in vreme kraja""" from flask import Flask, render_template, request, jsonify from tinydb import Query, TinyDB import requests import pprint #lepši print v consolu import random import math app = Flask('app') db = TinyDB('baza.json') #Imedict= @app.route('/') def index(): return render_template("index.html") @app.route('/podstran1') def podstran1(): return render_template("podstran1.html") #,dict=Imedict @app.route("/getKraj") def getKraj(): veterMax = 0 name = "" ime=request.args["ime"] split = ime.split(',') print(split) for i in split: url = f"https://api.openweathermap.org/data/2.5/weather?q={i}&appid=210e4dd31d93f214b4066e8c4947a2c8" kraj=requests.get(url).json() pprint.pprint(kraj) vreme = kraj['weather'][0]['main'] hitrost_vetra = kraj['wind']['speed'] tableBaza = db.table('baza') tableBaza.insert({"ime":i, 'vreme':vreme, "hitrost vetra":hitrost_vetra}) if hitrost_vetra > veterMax: veterMax = hitrost_vetra name = i dobi = f"Kraj: {name} - hitrost vetra: {veterMax}" return jsonify({"dobi":dobi}) @app.route('/podstran2') def podstran2(): return render_template("podstran2.html") app.run(host='0.0.0.0', port=8080, debug=True) ``` * > index.html ```html= <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <h1>INDEX</h1> <a href="/podstran1">podstran 1</a><br> <a href="/podstran2">podstran 2</a> </body> </html> ``` * > podstran1.html ```html= <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script> <title>Document</title> </head> <body> <a href="/">nazaj</a> <h1>PODSTRAN 1</h1> <!--Vnos--> <input type="text" id="ime" placeholder="Ime"> <button onclick="getKraj()">Dobi podatke</button> <p id="dobi"></p> <script> function getKraj() { let ime=document.getElementById("ime").value; $.ajax ({ url: "/getKraj", data: { "ime" : ime }, success: function(result){ console.log("dela"); $('#dobi').text(result.dobi); } }) } </script> </body> </html> ``` * > Ista naloga kot zgornja, samo izpis vsega iz baze plus izpis kraja z največ vetrom * > main.py ```python= """vnesi 5 krajov locenih z vejico ki jih ajax potem posle na python potem na pythonu z uporabo openweatherapija se za vsak kraj dobi vreme in hitrost vetra in potem to shrani v tinyDb da bo izgledalo nekako tako "id": 1 {"kraj": LJ, "vreme": dez, "hitrost_vetra": 10 km/h} in potem python primerja hitrosti vetrov in vrne nazaj na html kraj z najvisjo hitrostjo in vreme kraja""" from flask import Flask, render_template, request, jsonify from tinydb import Query, TinyDB import requests import pprint #lepši print v consolu import random import math app = Flask('app') db = TinyDB('baza.json') #Imedict= @app.route('/') def index(): return render_template("index.html") @app.route('/podstran1') def podstran1(): return render_template("podstran1.html") #,dict=Imedict @app.route("/getKraj") def getKraj(): veterMax = 0 name = "" ime=request.args["ime"] split = ime.split(',') print(split) for i in split: url = f"https://api.openweathermap.org/data/2.5/weather?q={i}&appid=210e4dd31d93f214b4066e8c4947a2c8" kraj=requests.get(url).json() pprint.pprint(kraj) vreme = kraj['weather'][0]['main'] hitrost_vetra = kraj['wind']['speed'] tableBaza = db.table('baza') tableBaza.insert({"ime":i, 'vreme':vreme, "hitrost vetra":hitrost_vetra}) if hitrost_vetra > veterMax: veterMax = hitrost_vetra name = i dobi = f"Kraj: {name} - hitrost vetra: {veterMax}" return jsonify({'dobi':dobi, 'baza':vseDržave()}) @app.route('/seznamDržav') def seznamDržav(): return vseDržave() def vseDržave(): db = TinyDB('baza.json') tableBaza = db.table('baza') htmlTable = "<table>" htmlTable += "<tr><th>Ime</th><th>Vreme</th><th>Hitrost vetra</th></tr>" for baza in tableBaza.all(): htmlTable += f"<tr><td>{baza['ime']}</td><td>{baza['vreme']}</td><td>{baza['hitrost vetra']}</td></tr>" htmlTable += "</table>" return htmlTable @app.route('/podstran2') def podstran2(): return render_template("podstran2.html") app.run(host='0.0.0.0', port=8080, debug=True) ``` * > index.html ```html= <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <h1>INDEX</h1> <a href="/podstran1">podstran 1</a><br> <a href="/podstran2">podstran 2</a> </body> </html> ``` * > podstran1.html ```html= <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script> <title>Document</title> </head> <body> <a href="/">nazaj</a> <h1>PODSTRAN 1</h1> <!--Vnos--> <input type="text" id="ime" placeholder="Ime"> <button onclick="getKraj()">Dobi podatke</button> <p id="dobi"></p> <p id="prikaz"></p> <script> $( document ).ready(function() { seznamDržav(); }); function seznamDržav() { $.ajax({ url: "/seznamDržav", success: function(result){ document.getElementById("prikaz").innerHTML = result; } }) } function getKraj() { let ime=document.getElementById("ime").value; $.ajax ({ url: "/getKraj", data: { "ime" : ime }, success: function(result){ console.log("dela"); $('#dobi').text(result.dobi); } }) } </script> </body> </html> ``` * > Get quotes, temperaturo krajev in vtise ```python= from flask import Flask, render_template, request, jsonify from tinydb import Query, TinyDB import requests import pprint #lepši print v consolu import random import math app = Flask('app') db = TinyDB('baza.json') pisatelji_quotes = { "Jane Austen": ["There is no charm equal to tenderness of heart.", "I declare after all there is no enjoyment like reading! How much sooner one tires of anything than of a book!", "A lady's imagination is very rapid; it jumps from admiration to love, from love to matrimony in a moment."], "Charles Dickens": ["It was the best of times, it was the worst of times.", "Reflect upon your present blessings, of which every man has plenty; not on your past misfortunes, of which all men have some.", "The pain of parting is nothing to the joy of meeting again."], "Mark Twain": ["The secret of getting ahead is getting started.", "The two most important days in your life are the day you are born and the day you find out why.", "Whenever you find yourself on the side of the majority, it is time to pause and reflect."], "Leo Tolstoy": ["All, everything that I understand, I only understand because I love.", "If you want to be happy, be.", "Boredom: the desire for desires."], "Ernest Hemingway": ["There is no friend as loyal as a book.", "The best way to find out if you can trust somebody is to trust them.", "Courage is grace under pressure."] } @app.route('/') def index(): return render_template("index.html") @app.route('/podstran1') def podstran1(): return render_template("podstran1.html") @app.route('/podstran2') def podstran2(): return render_template("podstran2.html", dict=pisatelji_quotes) @app.route('/quoteGet') def quoteGet(): ime = request.args['quote'] quote = random.choice(pisatelji_quotes[ime]) pprint.pprint(quote) return jsonify({'quote': quote }) @app.route('/vreme') def vreme(): vsota = 0 name = "" ime = request.args['ime'] dobi = ime.split(",") kraj1=dobi[0] kraj2=dobi[1] kraj3=dobi[2] url=f'https://api.openweathermap.org/data/2.5/weather?q={kraj1}&appid=210e4dd31d93f214b4066e8c4947a2c8' zahteva=requests.get(url).json() url1=f'https://api.openweathermap.org/data/2.5/weather?q={kraj2}&appid=210e4dd31d93f214b4066e8c4947a2c8' zahteva1=requests.get(url1).json() url2=f'https://api.openweathermap.org/data/2.5/weather?q={kraj3}&appid=210e4dd31d93f214b4066e8c4947a2c8' zahteva2=requests.get(url2).json() #pprint.pprint(zahteva) #pprint.pprint(zahteva1) #pprint.pprint(zahteva2) temp = zahteva['main']['temp'] temp1 = zahteva1['main']['temp'] temp2 = zahteva2['main']['temp'] if temp > vsota: vsota = temp name = kraj1 if temp1 > vsota: vsota = temp1 name = kraj2 if temp2 > vsota: vsota = temp2 name = kraj3 izpis = f"Najtoplejši kraj je {name} z temperaturo {vsota}" return jsonify({"izpis":izpis}) @app.route('/podstran3') def podstran3(): return render_template("podstran3.html") @app.route('/get') def get(): ime=request.args['ime'] vtis=request.args['vtis'] povezava=request.args['povezava'] tableOcene = db.table('baza') tableOcene.insert({"ime":ime, "vtis":vtis, "povezava":povezava}) izpis=f"Ime: {ime}, vtis: {vtis}, povezava: {povezava}" return jsonify({"izpis":izpis}) app.run(host='0.0.0.0', port=8080, debug=True) ``` * > HTML del-index.html ```html= <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <h1>INDEX</h1> <a href="/podstran1">podstran 1</a><br> <a href="/podstran2">podstran 2</a><br> <a href="/podstran3">podstran 3</a> </body> </html> ``` * >podstran1.html ```html= <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script> <title>Document</title> </head> <body> <a href="/">nazaj</a> <h1>PODSTRAN 1</h1> <!--Vnos--> <label name="Ime">Ime mesta</label> <input type="text" name="ime" id="ime"> <button onclick="vreme()">Dobi najbolj vroč kraj</button> <h3 id="getVreme"></h3> <script> function vreme() { let ime=document.getElementById("ime").value; $.ajax ({ url: "/vreme", data: { "ime" : ime }, success: function(result){ console.log("dela"); $("#getVreme").text(result.izpis) } }) } </script> </body> </html> ``` * >podstran2.html ```html= <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script> <title>Document</title> </head> <body> <a href="/">nazaj</a> <h1>PODSTRAN 2</h1> <select id="seznam"> {% for i in dict %} <option>{{ i }}</option> {% endfor %} </select> <button onclick="quoteGet()">Dobi Quote</button> <p id="quote"></p> <script> function quoteGet(){ let quote = document.getElementById("seznam").value; $.ajax({ url: '/quoteGet', data: { quote: quote }, success: function(result){ console.log("Dela") $("#quote").text(result.quote) } }) } </script> </body> </html> ``` * >podstran3.html ```html= <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script> <title>Document</title> </head> <body> <a href="/">nazaj</a> <h1>PODSTRAN 3</h1> <!--Vnos--> <input type="text" id="ime" placeholder="Ime"> <input type="text" id="vtis" placeholder="Sporočilo"> <input type="text" id="povezava" placeholder="Povezava"> <button onclick="getVse()">Shrani</button> <p id="izpis"></p> <script> function getVse() { let ime=document.getElementById("ime").value; let vtis=document.getElementById("vtis").value; let povezava=document.getElementById("povezava").value; $.ajax ({ url: "/get", data: { "ime" : ime, "vtis" : vtis, "povezava" : povezava }, success: function(result){ console.log("dela"); $("#izpis").text(result.izpis) } }) } </script> </body> </html> ``` * > Dobi spol in državo, iz kje ime izvira in spol glede na povprečen spol - main.py ```python= from flask import Flask, render_template, request, jsonify from tinydb import Query, TinyDB import requests import pprint #lepši print v consolu import random import math app = Flask('app') db = TinyDB('baza.json') #Imedict= @app.route('/') def index(): return render_template("index.html") @app.route('/podstran1') def podstran1(): return render_template("podstran1.html") #,dict=Imedict @app.route("/spol") def spol(): print("dobiSpol") email=request.args["email"] geslo=request.args["geslo"] razbito=email.split(".") ime=razbito[0] url= f'https://api.genderapi.io/api/?name={ime}&key=6659bf728afb35a712a720cc' zahteva=requests.get(url).json() url1= f'https://api.nationalize.io/?name={ime}' zahteva1=requests.get(url1).json() drzava=zahteva1["country"][0]["country_id"] moznost=round(zahteva1["country"][0]["probability"]*100) print(zahteva1["country"][0]) print(zahteva) tableOcene = db.table('baza') tableOcene.insert({"ime":ime, "geslo":geslo}) return f'Ime Elen je {zahteva["gender"]} iz države {drzava} {moznost}%' @app.route("/test") def test(): return "uspesno" @app.route('/podstran2') def podstran2(): return render_template("podstran2.html") app.run(host='0.0.0.0', port=8080, debug=True) ``` * > index.html ```html= <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <h1>INDEX</h1> <a href="/podstran1">podstran 1</a><br> <a href="/podstran2">podstran 2</a> </body> </html> ``` * > podstran1.html ```html= <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script> <title>Document</title> </head> <body> <a href="/">nazaj</a> <h1>PODSTRAN 1</h1> <!--Vnos--> <label name="email">Email</label> <input type="text" name="email" id="email"> <label name="geslo">Geslo</label> <input type="text" name="geslo" id="geslo"> <button onclick="pridobiSpol()">Pridobi spol</button> <h3 id="spolId"></h3> <script> function pridobiSpol() { console.log("dela") let email=document.getElementById("email").value; let geslo=document.getElementById("geslo").value; $.ajax ({ url: "/spol", data: { "email" : email, "geslo" : geslo }, success: function(result){ console.log("dela2"); let izpis=document.getElementById("spolId"); izpis.innerHTML = result; /*["#"]*/ } }) } </script> </body> </html> ``` * > Pokemon api - ```python= from flask import Flask, render_template, request, jsonify from tinydb import Query, TinyDB import requests import pprint #lepši print v consolu import random import math app = Flask('app') db = TinyDB('baza.json') @app.route('/') def index(): return render_template("index.html") @app.route('/podstran1') def podstran1(): return render_template("podstran1.html") #,dict=Imedict @app.route("/#") def karkoli(): klici=request.args["#1"] #url=f"api{ključ}" #zahteva=requests.get(url).json() #TinyDB vnos #tableOcene = db.table('baza') #tableOcene.insert({"primer":primer, "primer1":primer1, "primer2":primer2}) return "" @app.route('/podstran2') def podstran2(): return render_template("podstran2.html") @app.route("/pokeGet") def pokeGet(): ime = request.args.get('ime') url = f"https://pokeapi.co/api/v2/pokemon/{ime}" response = requests.get(url).json() abilities1 = response['abilities'][0]['ability']['name'] abilities2 = response['abilities'][1]['ability']['name'] abilities = f"{abilities1} and {abilities2}" return jsonify({'abilities': abilities}) app.run(host='0.0.0.0', port=8080, debug=True) ``` * > index.html ```html= <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <h1>INDEX</h1> <a href="/podstran1">podstran 1</a><br> <a href="/podstran2">podstran 2</a> </body> </html> ``` * > podstran 2 ```html= <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script> <title>Document</title> </head> <body> <a href="/">nazaj</a> <h1>POKEMON API</h1> Ime: <input type="text" id="ime" name="ime"/> <button onclick="pokeGet()">pokemon</button> <br> <p>Abilities:</p> <div id="abilities"></div> </body> <script> function pokeGet(){ let ime = document.getElementById("ime").value; $.ajax({ url: '/pokeGet', method: 'GET', data: { 'ime': ime }, success: function(result){ $("#abilities").text(result.abilities) } }) } </script> </html> ``` * > Pokemon api, kjer vpišemo ime sadja in dobimo ven okus ```python= from flask import Flask, render_template, request, jsonify from tinydb import Query, TinyDB import requests import pprint #lepši print v consolu import random import math app = Flask('app') db = TinyDB('baza.json') @app.route('/') def index(): return render_template("index.html") @app.route('/podstran1') def podstran1(): return render_template("podstran1.html") #,dict=Imedict @app.route("/getPoke") def getPoke(): okus = 0 name = "" ime =request.args["ime"] url = f'https://pokeapi.co/api/v2/berry/{ime}' zahteva=requests.get(url).json() hrana = zahteva['flavors'][0]['potency'] hrana2 = zahteva['flavors'][1]['potency'] hrana3 = zahteva['flavors'][2]['potency'] hrana4 = zahteva['flavors'][3]['potency'] hrana5 = zahteva['flavors'][4]['potency'] ime1=zahteva['flavors'][0]['flavor']['name'] ime2=zahteva['flavors'][1]['flavor']['name'] ime3=zahteva['flavors'][2]['flavor']['name'] ime4=zahteva['flavors'][3]['flavor']['name'] ime5=zahteva['flavors'][4]['flavor']['name'] if hrana > okus: okus = hrana name = ime1 if hrana2 > okus: okus = hrana2 name = ime2 if hrana3 > okus: okus = hrana3 name = ime3 if hrana4 > okus: okus = hrana4 name = ime4 if hrana5 > okus: okus = hrana5 name = ime5 pprint.pprint(okus) pprint.pprint(name) izpis = f"{ime} is {name} in flavor" return jsonify({"izpis":izpis}) @app.route('/podstran2') def podstran2(): return render_template("podstran2.html") @app.route("/pokeGet") def pokeGet(): ime = request.args.get('ime') url = f"https://pokeapi.co/api/v2/pokemon/{ime}" response = requests.get(url).json() abilities1 = response['abilities'][0]['ability']['name'] abilities2 = response['abilities'][1]['ability']['name'] abilities = f"{abilities1} and {abilities2}" return jsonify({'abilities': abilities}) app.run(host='0.0.0.0', port=8080, debug=True) ``` * > index.html ```html= <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <h1>INDEX</h1> <a href="/podstran1">podstran 1</a><br> <a href="/podstran2">podstran 2</a> </body> </html> ``` * > podstran1.html ```html= <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script> <title>Document</title> </head> <body> <a href="/">nazaj</a> <h1>PODSTRAN 1</h1> <!--Vnos--> <input type="text" id="ime" placeholder="ime"> <button onclick="getPoke()">Dobi okus</button> <p id="izpis"></p> <script> function getPoke() { let ime=document.getElementById("ime").value; $.ajax ({ url: "/getPoke", data: { "ime" : ime }, success: function(result){ console.log("dela"); $('#izpis').text(result.izpis); } }) } </script> </body> </html> ``` * > Jokes api- dobi šalo v dveh delih ```python= #Jokes api, vrže rasisticne sale from flask import Flask, render_template, request, jsonify from tinydb import Query, TinyDB import requests import pprint #lepši print v consolu import random import math app = Flask('app') db = TinyDB('baza.json') #Imedict= @app.route('/') def index(): return render_template("index.html") @app.route('/podstran1') def podstran1(): return render_template("podstran1.html") #,dict=Imedict @app.route('/quote1Get') def getJoke(): urlJoke = "https://v2.jokeapi.dev/joke/Any" klic = requests.get(urlJoke).json() if klic["type"] == "single": return jsonify({"joke": klic['joke']}) else: return jsonify({"setup": klic['setup'], "delivery": klic['delivery']}) @app.route('/podstran2') def podstran2(): return render_template("podstran2.html") app.run(host='0.0.0.0', port=8080, debug=True) ``` * > index.html ```html= <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <h1>INDEX</h1> <a href="/podstran1">podstran 1</a><br> <a href="/podstran2">podstran 2</a> </body> </html> ``` * > podstran1.html ```html= <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script> <title>Document</title> </head> <body> <a href="/">nazaj</a> <h1>Podstran 1</h1> <button onclick="quote1Get()">JOKE</button> <div id="rezultat3"></div> <div id="rezultat2"></div> <div id="rezultat1"></div> <script> function quote1Get(){ $.ajax({ url: '/quote1Get', data: {}, success: function(result){ $('#rezultat1').empty(); $('#rezultat2').empty(); $('#rezultat3').empty(); $("#rezultat1").text(result.delivery); $("#rezultat2").text(result.setup); $("#rezultat3").text(result.joke); } }) } </script> </body> </html> ``` * > Vsi podatki iz baza.json se izpisejo ```python= """Potrebuješ textarea, text input in gumb. Naredi aplikacijo v kateri lahko kdorkoli napiše sporočilo v text input. Ob kliku na gumb se sporočilo pošlje na strežnik. Ko se sporočilo pošlje na strežnik se le to shrani. Odgovor routa, ki sprejme sporočilo pa so vsa sporočila v bazi. Ta "vsa sporočila" izpiši v textboxu.""" from flask import Flask, render_template, request, jsonify from tinydb import Query, TinyDB import requests import pprint #lepši print v consolu import random import math app = Flask('app') db = TinyDB('baza.json') #Imedict= @app.route('/') def index(): return render_template("index.html") @app.route('/podstran1') def podstran1(): return render_template("podstran1.html") #,dict=Imedict @app.route("/getSpo") def getSpo(): niz = "" dobi=request.args["sporocilo"] tableOcene = db.table('baza') tableOcene.insert({"sporocilo":dobi}) dobi1 = tableOcene.all() for i in dobi1: baz = i['sporocilo'] niz += baz return jsonify({'dobi': niz}) @app.route('/podstran2') def podstran2(): return render_template("podstran2.html") app.run(host='0.0.0.0', port=8080, debug=True) ``` * > index.html ```html= <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <h1>INDEX</h1> <a href="/podstran1">podstran 1</a><br> <a href="/podstran2">podstran 2</a> </body> </html> ``` * > podstran1.html ```html= <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script> <title>Document</title> </head> <body> <a href="/">nazaj</a> <h1>PODSTRAN 1</h1> <!--Vnos--> <input type="text" id="sporocilo" placeholder="Sporočilo"> <button onclick="getSpo()">Dobi sporočila</button> <p id="dobi"></p> <script> function getSpo(){ var sporocilo = document.getElementById("sporocilo").value; $.ajax ({ url: "/getSpo", data: { "sporocilo" : sporocilo }, success: function(result){ console.log("dela"); $('#dobi').text(result.dobi); } }) } </script> </body> </html> ``` * > Izpisovanje baze na lepši/bolj drugačen način ```python= """Registracija/Prijava: Uporabnik se lahko registrira ali prijavi v aplikacijo. Pri registraciji zahtevaj uporabniško ime in geslo. Registracijo/prijavo lahko združiš (kot v chatu). Urejanje besedila: Po prijavi omogoči uporabniku urejanje besedila v textarea polju. Omogoči shranjevanje urejenega besedila. Shranjuješ lahko, ko uporabnik klikne na določen gumb. Ali pa kar na onchange() trigger textarea. Prikaz urejenega besedila: Ob naslednji prijavi uporabnika prikaži prejšnje urejeno besedilo v textarea polju.""" from flask import Flask, render_template, request, jsonify from tinydb import Query, TinyDB import requests import pprint #lepši print v consolu import random import math app = Flask('app') db = TinyDB('ocene.json') @app.route('/') def index(): return render_template("index.html") @app.route('/ocene') def ocene(): return render_template('ocene.html') @app.route('/shraniocene', methods=["POST"]) def oceneJson(): geslo = request.form["geslo"] ime = request.form["ime"] tableOcene = db.table('ocene') tableOcene.insert({"ime":ime, "geslo":geslo}) return vseOcene() @app.route('/seznamOcen') def seznamOcen(): return vseOcene() def vseOcene(): db = TinyDB('ocene.json') tableOcene = db.table('ocene') htmlTable = "<table>" htmlTable += "<tr><th>Ime</th><th>Geslo</th></tr>" for ocena in tableOcene.all(): htmlTable += f"<tr><td>{ocena['ime']}</td><td>{ocena['geslo']}</td></tr>" htmlTable += "</table>" return htmlTable @app.route('/podstran2') def podstran2(): return render_template("podstran2.html") app.run(host='0.0.0.0', port=8080, debug=True) ``` * > index.html ```html= <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <h1>INDEX</h1> <a href="/podstran2">podstran 2</a><br> <a href="/ocene"> Ocene</a> </body> </html> ``` * > ocene.html ```html= <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"> </script> <title>Ocene</title> </head> <a href="/"> DOMOV</a><br> <input type="text" id="ime" placeholder="Uporabniško ime"> <input type="text" id="geslo" placeholder="Geslo"> <body> <button onclick="shrani()"> Shrani v DB </button> <div id="prikaz"></div> <script> $( document ).ready(function() { seznamOcen(); }); function seznamOcen() { $.ajax({ url: "/seznamOcen", success: function(result){ document.getElementById("prikaz").innerHTML = result; } }) } function shrani() { var ime = document.getElementById("ime").value; var geslo = document.getElementById("geslo").value; $.ajax({ url: "/shraniocene", type: "POST", data: { "ime": ime, "geslo": geslo }, success: function(result){ document.getElementById("prikaz").innerHTML = result; } }) } </script> </body> </html> ``` * > Dobi sliko * > main.py ```python= """S pomočjo API-ja https://imgflip.com/api generiraj meme. Tvoja stran naj ima dropdown menu za izbiro "meme templata" in inpute za tekst. Meme template so različne slike ozadja meme-a. Iz routa "/get_memes" pridobi vse možne meme "template" in jih napolni v HTML dropdown ob naložitvi tvoje strani. Tu si pomagaj z Jinja for zanko. # recimo če Jinji pošljemo slovar iz /get_memes {% for item in options %} <option value={{ item.id }}>{{ item.name }}</option>""" from flask import Flask, render_template, request, jsonify from tinydb import Query, TinyDB import requests import pprint #lepši print v consolu import random import math app = Flask('app') db = TinyDB('baza.json') #Imedict= @app.route('/') def index(): return render_template("index.html") @app.route('/podstran1') def podstran1(): return render_template("podstran1.html") @app.route('/podstran2') def podstran2(): url = "https://api.imgflip.com/get_memes" klic = requests.get(url).json() values = klic['data']['memes'] return render_template("podstran2.html", values = values) @app.route('/meme') def meme(): lin = "" ime = "" id = request.args['id'] url = "https://api.imgflip.com/get_memes" klic = requests.get(url).json() for i in klic['data']['memes']: if i['id'] == id: lin = i['url'] ime = i['name'] img = f'<img src="{lin}" width="500" height="500" text-align="center">' return jsonify({'slika': img, 'name': ime}) app.run(host = '0.0.0.0', port = 8080, debug=True) app.run(host='0.0.0.0', port=8080, debug=True) ``` * > index.html ```html= <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <h1>INDEX</h1> <a href="/podstran1">podstran 1</a><br> <a href="/podstran2">podstran 2</a> </body> </html> ``` * > podstran1.html ```html= <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script> <title>Document</title> </head> <body> <a href="/">nazaj</a> <h1>PODSTRAN 2</h1> <select id="izbrano"> {% for i in values %} <option value="{{ i.id }}">{{ i.name }}</option> {% endfor %} </select> <button onclick="memeGet()">Dobi sliko</button> <h2 id="imeslike"></h2> <div id="slika"></div> <script> function memeGet() { let id = document.getElementById("izbrano").value; $.ajax({ url: "/meme", data: { id: id }, success: function(result) { $("#imeslike").text(result.name) console.log(result.slika) slika.innerHTML = result.slika } }) } </script> </body> </html> ``` * > Uporaba 3-eh apijev, genderize, agify in nationalize, obvesti nas, ko je ime že bilo zapisano oziroma shranjeno v bazi obvesti nas, ko je ime že bilo zapisano oziroma shranjeno v bazi ter iskanje okusa sadja, in uzitnost gob. Nato še razlika starosti za 15 let * > main.py ```python= from flask import Flask, render_template, request, jsonify from tinydb import Query, TinyDB import requests import pprint #lepši print v consolu import random import math app = Flask('app') db = TinyDB('baza.json') sadje = { "Jabolko": 1, "Banana": 2, "Češnja": 2, "Grozdje": 2, "Kivi": 3, "Limon": 4, "Jagoda": 2, "Pomaranča": 3, "Breskev": 2, "Sliva": 3 } kislost = { 1: "Rahlo kisel", 2: "Sladek", 3: "Rahlo sladek", 4: "Kisel" } gobe1 = { "Mušnica": "A", "Jurček": "B", "Šampinjon": "B", "Lisička": "B", "Golobica": "B", "Dežnik": "B", "Rdeča mušnica": "A", "Zelena mušnica": "A", "Blagva": "B", "Mlečnica": "C", "Poljska kukmaka": "B", "Krasnik": "C", "Gobasti muškatnik": "C", "Črni trobentač": "B", "Zimski trobentač": "B" } uzitnost1 = { "A": "STRUPENA", "B": "UŽITNA", "C": "POGOJNO UŽITNA" } @app.route('/') def index(): return render_template("index.html") """Ustvari spletno stran, ki od uporabnika sprejme izbrano sadje iz dropdown menija in ob kliku na gumb se mu na strani izpiše okus izbranega sadja. Za generiranje dropdowna s sadjem in za pridobivanje kislosti uporabi spodnja slovarja:""" @app.route('/uzitnost') def uzitnost(): return render_template("uzitnost.html", dict=sadje) @app.route("/getSadje") def getSadje(): sadje1=request.args["sadje1"] uzit = sadje[sadje1] uzitnost = kislost[uzit] pprint.pprint(uzitnost) izpis = f"{sadje1} je {uzitnost}" return jsonify({'izpis':izpis}) """Ustvari spletno stran, ki od uporabnika sprejme email in geslo. Predpostavljamo, da je email vedno v obliki ime.priimek@gmail.com. Ime pošlji preko API-ja genderize in shrani v bazo poleg imena in gesla tudi predviden spol glede na ime. Za bonus uporabi še API nationalize za pridobitev največje verjetnosti države glede na ime. Če uporabnik s tem imenom že obstaja, o tem kakorkoli obvesti uporabnika. Za nalogo je potrebna uporaba Ajax-a in TinyDB. PAZI, ker ima API 100 klicev na dan. Tako, da dokler ne implementiraš do konca, uporabi primer odgovora na stran""" @app.route('/narodnost') def narodnost(): return render_template("narodnost.html") @app.route('/dobi') def dobi(): email=request.args["email"] geslo=request.args["geslo"] split = email.split(".") ime = split[0] url=f"https://api.genderize.io?name={ime}" zahteva=requests.get(url).json() url1=f'https://api.nationalize.io/?name={ime}' zahteva1=requests.get(url1).json() url2=f'https://api.agify.io?name={ime}' zahteva2=requests.get(url2).json() starost = zahteva2['age'] spol = zahteva['gender'] moznost = zahteva['probability']*100 drzava = zahteva1['country'][0]['country_id'] moznost1 = round(zahteva1['country'][0]['probability']*100) izpis=f"{ime} je {spol} spola. Tega moznost je {moznost}%. To ime izhaja iz drzave {drzava} z {moznost1}% možnosti. Predvidevamo, da je oseba glede na ime stara {starost} let." tableBaza = db.table('baza') User = Query() existing_user = tableBaza.search(User.ime == ime) if existing_user: return jsonify({'izpis': f"Uporabnik z imenom {ime} že obstaja v bazi."}) tableBaza.insert({"ime":ime, "spol":spol, "moznost":moznost, 'drzava':drzava, 'moznost1':moznost1, 'starost':starost}) return jsonify({'izpis':izpis}) """Ustvari spletno stran, ki od uporabnika sprejme izbrano gobo iz dropdown menija in ob kliku na gumb , se mu na strani izpiše užitnost izbrane gobe. Za generiranje dropdowna gob in za pridobivanje vrednosti uporabi spodnja slovarja:""" @app.route('/gobe') def gobe(): return render_template("gobe.html",dict=gobe1) @app.route('/getGobe') def getGobe(): ime = request.args['get'] uzit = gobe1[ime] uzitnost = uzitnost1[uzit] izpis = f"Goba {ime} je {uzitnost}" return jsonify({'izpis':izpis}) """Ustvari spletno stran, ki od uporabnika zahteva vnos emaila, starosti, imena in gesla preko tekstovnega polja. Ob kliku na gumb Flask v ozadju preveri starost uporabnika z uporabo Agify API na podlagi imena. Če se povprečna starost za dano ime razlikuje za manj kot 15 let od vnesene starosti, se podatki shranijo v TinyDB. Uporabniku napiši, če je uspešno ali neuspešno vpisan.""" @app.route('/starost') def starost(): return render_template("starost.html") @app.route('/getRazlika') def getRazlika(): ime = request.args['ime'] email = request.args['email'] starost = request.args['starost'] geslo = request.args['geslo'] url=f"https://api.agify.io?name={ime}" odgovor=requests.get(url).json() star_razlika = abs(int(starost) - int(odgovor['age'])) if star_razlika < 15: db1 = TinyDB('baza1.json') tableBaza = db1.table('baza1') tableBaza.insert({"email":email,"ime":ime, "geslo":geslo, "starost":starost}) return "Uspešno shranjeno." else: return f"Starostna razlika je prevelika. Povprečna starost za ime je: {odgovor['age']}" """Ustvari spletno stran, ki od uporabnika sprejme seznam hrane, ločen z vejicami, preko text input-a. Flask bo te podatke sprejel in preveril kalorično vrednost vsake hrane v slovarju. Na strani se prikaže kalorična vrednost vsake hrane. Zaradi enostavnosti, naloga ne upošteva teže hrane. Recimo, če nekdo vpiše: “krompir, mleko, jajca”; Aplikacija odgovori - “Vnešena hrana ima 274 kalorij”""" @app.route('/kalorije1') def kalorije1(): return render_template('kalorije1.html') @app.route("/kalorije", methods=["POST"]) def kalorije(): kalorije = { "jabolko": 52, "banana": 89, "pomaranča": 47, "jagoda": 32, "limona": 29, "kruh": 265, "riž": 130, "piščanec": 239, "govedina": 250, "korenje": 41, "mleko": 42, "jajca": 155, "sir": 402, "paradižnik": 18, "krompir": 77 } hrana=request.form["hrana"] hrane=hrana.split(",") vsota = 0 for h in hrane: vsota += kalorije[h] return f"Vnešena hrana ima {str(vsota)} kalorij" app.run(host='0.0.0.0', port=8080, debug=True) ``` * >index.html ```html= <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <h1>INDEX</h1> <a href="/narodnost">Narodnost in Gender</a><br> <a href="/uzitnost">uzitnost</a><br> <a href="/gobe">gobe</a><br> <a href="/starost">Starost</a><br> <a href="/kalorije1">Kalorije</a> </body> </html> ``` * > narodnost.html ```html= <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script> <title>Document</title> </head> <body> <a href="/">nazaj</a> <h1>Narodnost</h1> <!--Vnos--> <input type="text" id="email" placeholder="e-mail"> <input type="text" id="geslo" placeholder=Geslo> <button onclick="dobi()">Dobi Spol</button> <p id="izpis"></p> <script> function dobi() { let email=document.getElementById("email").value; let geslo=document.getElementById("geslo").value; $.ajax ({ url: "/dobi", data: { "email":email, "geslo":geslo }, success: function(result){ console.log("dela"); $('#izpis').text(result.izpis); } }) } </script> </body> </html> ``` * > uzitnost.html ```html= <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script> <title>Document</title> </head> <body> <a href="/">nazaj</a> <h1>Uzitnost</h1> <select id="sadje1" placeholder="Dobi sadje"> {% for i in dict %} <option>{{ i }}</option> {% endfor %} </select> <button onclick="getSadje()">Dobi kislost</button> <p id="izpis"></p> <script> function getSadje(){ let sadje1 = document.getElementById('sadje1').value; $.ajax({ url: '/getSadje', data: { "sadje1": sadje1 }, success: function (result) { console.log("dela"); $("#izpis").text(result.izpis); } }) } </script> </body> </html> ``` * > gobe.html ```html= <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script> <title>Document</title> </head> <body> <a href="/">nazaj</a> <h1>Gobe</h1> <select id="get" placeholder="ime"> {% for i in dict %} <option>{{ i }}</option> {% endfor %} </select> <button onclick="getGobe()">Dobi</button> <p id="izpis"></p> <script> function getGobe(){ let get = document.getElementById('get').value; $.ajax({ url: '/getGobe', data: { "get":get }, success: function (result) { console.log("dela"); $("#izpis").text(result.izpis); } }) } </script> </body> </html> ``` * > starost.html ```html= <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script> <title>Document</title> </head> <body> <a href="/">nazaj</a> <h1>PODSTRAN 1</h1> <!--Vnos--> <input type="text" id="ime" placeholder="Ime"> <input type="text" id="email" placeholder="E-mail"> <input type="text" id="starost" placeholder="starost"> <input type="text" id="geslo" placeholder="Geslo"> <button onclick="getRazlika()">Dobi starost</button> <p id="odgovor"></p> <script> function getRazlika() { let ime=document.getElementById("ime").value; let email=document.getElementById("email").value; let starost=document.getElementById("starost").value; let geslo=document.getElementById("geslo").value; $.ajax ({ url: "/getRazlika", data: { "ime" : ime, "email":email, "starost":starost, "geslo":geslo }, success: function(result){ console.log("dela"); const odg=document.getElementById("odgovor"); odg.innerHTML=result; } }) } </script> </body> </html> ``` * > kalorije1.html ```html= <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script> <title>Document</title> </head> <body> <a href="/">nazaj</a> <h1>Kalorije</h1> <input type="text" id="hrana" placeholder="Hrana"> <button onclick="pridobiKalorije()">Pridobi kalorije</button> <p id="kalorije_odg"></p> <script> function pridobiKalorije(){ var hrana=document.getElementById("hrana").value $.ajax ({ url: "/kalorije", type: "POST", data: { "hrana": hrana }, success: function(result){ var odg=document.getElementById("kalorije_odg") odg.innerHTML=result } }) } </script> </body> </html> ``` * > Primerjava nacionalnosti * > main.py ```python= """Ustvari spletno stran, ki od uporabnika zahteva vnos emaila, narodnosti, imena in gesla preko tekstovnega polja. Po kliku na gumb Flask v ozadju preveri narodnost uporabnika z uporabo Nationalize API na podlagi imena. Če se nacionalnost za dano ime pojavi med nacionalnostnmi iz API-ja, se podatki shranijo v TinyDB. Uporabniku napiši, če je uspešno ali neuspešno vpisan. Za nacionalnost uporabnik vpiše kratico države, kot je to na Nationalize API.""" """Ustvari spletno stran, ki od uporabnika zahteva vnos emaila, narodnosti, imena in gesla preko tekstovnega polja. Po kliku na gumb Flask v ozadju preveri narodnost uporabnika z uporabo Nationalize API na podlagi imena. Če se nacionalnost za dano ime pojavi med nacionalnostnmi iz API-ja, se podatki shranijo v TinyDB. Uporabniku napiši, če je uspešno ali neuspešno vpisan. Za nacionalnost uporabnik vpiše kratico države, kot je to na Nationalize API.""" from flask import Flask, render_template, request, jsonify from tinydb import Query, TinyDB import requests import pprint #lepši print v consolu import random import math app = Flask('app') db = TinyDB('baza.json') emisije = { "avto": 120, "motor": 90, "kolo": 0, "vlak": 50, "letalo": 250, "ladja": 170, "avtobus": 80 } @app.route('/') def index(): return render_template("index.html") @app.route('/podstran1') def podstran1(): return render_template("podstran1.html") #,dict=Imedict @app.route('/nation') def nation(): m = False tableBaza = db.table('baza') ime = request.args['ime'] email = request.args['email'] narodnost = request.args['narodnost'] geslo = request.args['geslo'] url=f'https://api.nationalize.io/?name={ime}' odgovor=requests.get(url).json() odgovor1 = odgovor['country'] for i in odgovor1: odgovor2 = i['country_id'] pprint.pprint(odgovor2) if narodnost == odgovor2 : tableBaza.insert({"email":email,"ime":ime, "geslo":geslo, "narodnost":narodnost}) m = True if m: return "Uspešno shranjeno" else: return "Država, ki ste jo vpisali ne ustreza nobenem zapisu iz apija." """Ustvari spletno stran, ki od uporabnika sprejme seznam transportnih vozil, ločenih z vejicami, preko text input-a. Flask bo te podatke sprejel preko Ajax-a in preveril emisije CO2 za vsako sredstvo v slovarju. Na strani se prikaže skupna količina emisij CO2. Recimo, če nekdo vpiše: “avto, vlak, letalo”; Aplikacija odgovori - “Vnešena transportna sredstva povzročajo skupno 420 g CO2""" @app.route('/podstran2') def podstran2(): return render_template("podstran2.html") @app.route('/avti') def avti(): vsota = 0 ime = request.args['ime'] split = ime.split(",") for i in split: vsota += emisije[i] pprint.pprint(vsota) izpis = f"Vnešena transportna sredstva povzročajo skupno {vsota} g CO2" return jsonify({'izpis':izpis}) app.run(host='0.0.0.0', port=8080, debug=True) ``` * > index.html ```html= <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <h1>INDEX</h1> <a href="/podstran1">podstran 1</a><br> <a href="/podstran2">podstran 2</a> </body> </html> ``` * > podstran1.html ```html= <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script> <title>Document</title> </head> <body> <a href="/">nazaj</a> <h1>PODSTRAN 1</h1> <!--Vnos--> <input type="text" id="ime" placeholder="Ime"> <input type="text" id="email" placeholder="E-mail"> <input type="text" id="narodnost" placeholder="narodnost"> <input type="text" id="geslo" placeholder="Geslo"> <button onclick="nation()">Dobi nacionalnost</button> <p id="odgovor"></p> <script> function nation() { let ime=document.getElementById("ime").value; let email=document.getElementById("email").value; let narodnost=document.getElementById("narodnost").value; let geslo=document.getElementById("geslo").value; $.ajax ({ url: "/nation", data: { "ime" : ime, "email":email, "narodnost":narodnost, "geslo":geslo }, success: function(result){ console.log("dela"); const odg=document.getElementById("odgovor"); odg.innerHTML=result; } }) } </script> </body> </html> ``` * > podstran2.html ```html= <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script> <title>Document</title> </head> <body> <a href="/">nazaj</a> <h1>PODSTRAN 2</h1> <input type="text" id="ime" placeholder="ime"> <button onclick="avti()">Pretvori</button> <p id="izpis"></p> <script> function avti(){ let ime = document.getElementById('ime').value; $.ajax({ url: '/avti', data: { "ime": ime }, success: function (result) { console.log("dela"); $("#izpis").text(result.izpis); } }) } </script> </body> </html> ``` * > Chuck Norris Api, Holiday Api, Cards Api, Bored Api * > main.py ```python= from flask import Flask, render_template, request, jsonify from tinydb import Query, TinyDB import requests import pprint #lepši print v consolu import random import math app = Flask('app') db = TinyDB('baza.json') #Imedict= @app.route('/') def index(): return render_template("index.html") @app.route('/holiday') def holiday(): return render_template("holiday.html") #,dict=Imedict @app.route("/holidayGet") def holidayGet(): leto = request.args.get('leto') drzava = request.args.get('drzava') url = f"https://date.nager.at/api/v3/PublicHolidays/{leto}/{drzava}" response = requests.get(url).json() # Extracting names from the holidays #holiday_names = [holiday['name'] for holiday in holidays if 'name' in holiday] holiday_names = [{ 'name': holiday['name'], 'date': holiday['date'] } for holiday in response if 'name' in holiday and 'date' in holiday] return jsonify({'holiday_names': holiday_names}) @app.route('/karte') def karte(): return render_template("karte.html") @app.route("/cardGet") def cardGet(): tableKarte = db.table('karte') url = "https://www.deckofcardsapi.com/api/deck/new/shuffle/?deck_count=1" response = requests.get(url).json() id = response['deck_id'] url2 = f"https://www.deckofcardsapi.com/api/deck/{id}/draw/?count=1" response2 = requests.get(url2).json() vrednost = response2['cards'][0]['value'] vrsta = response2['cards'][0]['suit'] tableKarte.insert({'vrsta': vrsta, 'vrednost': vrednost}) vseKarte = db.table('karte').all() print(vseKarte) karta = f'{vrednost} of {vrsta}' return jsonify({'karta': karta}) @app.route("/chucknorris") def podstran2(): return render_template("chucknorris.html") @app.route("/quoteGet") def quoteGet(): url = "https://api.chucknorris.io/jokes/random" klic = requests.get(url).json() quote = klic['value'] return jsonify({'quote': quote}) @app.route("/bored") def podstran6(): return render_template("bored.html") @app.route("/activityGet") def activityGet(): url = "http://www.boredapi.com/api/activity/" klic = requests.get(url).json() activity = klic['activity'] pprint.pprint(activity) return jsonify({'activity': activity}) app.run(host='0.0.0.0', port=8080, debug=True) ``` * > index.html ```html= <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <h1>INDEX</h1> <a href="/holiday">Prazniki</a><br> <a href="/karte">Karte</a><br> <a href="/chucknorris">CHUCK NORRIS</a><br> <a href="/bored">Bored api</a> </body> </html> ``` * > chucknorris.html ```html= <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script> <title>Document</title> </head> <body> <a href="/">nazaj</a> <h1>CHUCK NORRIS API</h1> <button onclick="quoteGet()">Dobi Quote</button> <div id="quote"></div> <script> function quoteGet(){ $.ajax({ url: '/quoteGet', data: {}, success: function(result){ $("#quote").text(result.quote) } }) } </script> </body> </html> ``` * > holiday.html ```html= <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script> <title>Document</title> </head> <body> <a href="/">nazaj</a> <h1>HOLIDAY API</h1> <form> Leto: <input type="text" id="leto" name="leto"/><br> Drzava: <input type="text" id="drzava" name="drzava" maxlength="2"/><br> </form><br> <button onclick="holidayGet()">Dobi praznike</button> <div id="holidayList"> </div> <script> function holidayGet(){ var leto = document.getElementById("leto").value; var drzava = document.getElementById("drzava").value; $.ajax({ url: '/holidayGet', method: 'GET', data: { leto: leto, drzava: drzava }, success: function(response) { $('#holidayList').empty(); // Clear any existing list items if (response.holiday_names && response.holiday_names.length > 0) { response.holiday_names.forEach(function(holiday) { $('#holidayList').append('<p>' + holiday.name + ' (' + holiday.date + ')</p>')/*('<p>' + name + '</p>')*/; }); } } }) } </script> </body> </html> ``` * > karte.html ```html= <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script> <title>Document</title> </head> <body> <a href="/">nazaj</a> <h1>CARDS API</h1> <button onclick="cardGet()">Dobi karto</button> <div id="karta"></div> <script> function cardGet(){ $.ajax({ url: '/cardGet', data: {}, success: function(result){ $("#karta").text(result.karta) } }) } </script> </body> </html> ``` * > bored.html ```html= <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script> <title>Document</title> </head> <body> <a href="/">nazaj</a> <h1>BORED API</h1> <button onclick="activityGet()">Activity</button> <div id="activity"></div> <script> function activityGet(){ $.ajax({ url: '/activityGet', data: {}, success: function(result){ $("#activity").text(result.activity) } }) } </script> </body> </html> ``` * > Koliko čebel je na travniku * > main.py ```python= from flask import Flask, render_template, request, jsonify from tinydb import Query, TinyDB import requests import pprint #lepši print v consolu import random import math app = Flask('app') db = TinyDB('baza.json') #Imedict= @app.route('/') def index(): return render_template("index.html") @app.route('/podstran1') def podstran1(): return render_template("podstran1.html") #,dict=Imedict """Naloga 1: Število rastlin na travniku [3 točke] Uporabnika prosimo, da vnese površino travnika v kvadratnih metrih. Na podlagi tega izračunamo število rastlin na travniku (predpostavljamo, da na kvadratnem metru raste 50 rastlin) in izpišemo rezultat. Primer izpisa za vnos kvadratnihMetrov = 10: "Na travniku s površino 10 m^2 imamo približno 500 rastlin." Naloga 2: Število čebelic na travniku [3 točke] Nadaljujemo prejšnjo nalogo, vendar tokrat želimo izračunati tudi število čebelic na travniku. Predpostavljamo, da na vsaki rastlini živi približno 15 čebelic. Uporabnik vnese površino travnika, mi pa izračunamo število rastlin in čebelic ter izpišemo rezultat. Primer izpisa za vnos kvadratnihMetrov = 10:""" @app.route("/povrsina") def povrsina(): vnos=request.args["vnos"] st = int(vnos) #Spremeni str v int st_rastlin = st * 50 st_cebel = st_rastlin * 15 izpis = f"Na travniku s površino {vnos} m^2 imamo približno {st_rastlin} rastlin. Na travniku je tudi {st_cebel} čebel" return jsonify({'izpis':izpis}) @app.route('/podstran2') def podstran2(): return render_template("podstran2.html") app.run(host='0.0.0.0', port=8080, debug=True) ``` * > index.html ```html= <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <h1>INDEX</h1> <a href="/podstran1">podstran 1</a><br> </body> </html> ``` * > podstran1.html ```html= <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script> <title>Document</title> </head> <body> <a href="/">nazaj</a> <h1>PODSTRAN 1</h1> <!--Vnos--> <input type="text" id="vnos" placeholder="Vnesi površino"> <button onclick="povrsina()">Dobi število rastlin</button> <p id="izpis"></p> <script> function povrsina() { var vnos=document.getElementById("vnos").value; $.ajax ({ url: "/povrsina", data: { "vnos" : vnos }, success: function(result){ console.log("dela"); $('#izpis').text(result.izpis); } }) } </script> </body> </html> ``` * > vstavi recept, samo jinja brez ajaxa! * > main.py ```python= from flask import Flask, render_template, request, jsonify from tinydb import Query, TinyDB import requests import pprint #lepši print v consolu import random import math app = Flask('app') db = TinyDB('baza.json') #Imedict= @app.route('/') def index(): return render_template("index.html") @app.route('/podstran1') def podstran1(): url = "https://www.themealdb.com/api/json/v1/1/random.php" zahteva = requests.get(url).json() odprto = zahteva["meals"][0] ime = odprto["strMeal"] opis = odprto["strInstructions"] slika = odprto["strMealThumb"] sestavine = [] for i in range(1, 21): if odprto[f"strIngredient{i}"]: tmpI = odprto[f"strIngredient{i}"] tmpM = odprto[f"strMeasure{i}"] sestavine.append([tmpI, tmpM]) return render_template("podstran1.html", ime=ime, opis=opis, slika=slika, sestavine=sestavine) @app.route('/podstran2') def podstran2(): return render_template("podstran2.html") app.run(host='0.0.0.0', port=8080, debug=True) ``` * > index.html ```html= <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <h1>INDEX</h1> <a href="/podstran1">podstran 1</a><br> <a href="/podstran2">podstran 2</a> </body> </html> ``` * > podstran1.html ```html= <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script> <title>Document</title> </head> <body> <a href="/">nazaj</a> <h1>PODSTRAN 1</h1> <div> {{ ime }} </div> <div> {{ opis }} </div> <img src="{{ slika }}" width="500" height="600"> {% for s in sestavine %} <li> {{ s[0] }} | {{ s[1] }} </li> {% endfor %} </body> </html> ``` * > Coin flip in random quotes * > main.py ```python= """V index.html, ki smo ga delali nazadnje dodaj še povezavo za vsako od svoji routov iz prejšne vaje: /coinFlip - naredi kovanec.html, se ob kliku na gumb izpiše naključna stran in slika kovanca. /randomQuote- na qoute.html se ob osvežitvi strani pokaže nov random quote. /randomNum/ - na rndnum.html naredi 2 inputa za min in max vrednost. Ob pritisku na gumb se na strani pokaže naključne številka med min in max. /randPassword/ - na password.html 1 input za dolžino gesla in en gumb, ki na strani izpiše novo generirano geslo. /randDice/ - 2 inputa, 1 gumb. Ob pritisku na gumb izpiši podatke, ki jih vrača zgorni route.""" from flask import Flask, render_template, request, jsonify from tinydb import Query, TinyDB import requests import pprint #lepši print v consolu import random import math import os, string app = Flask('app') db = TinyDB('baza.json') @app.route('/') def index(): return render_template("index.html") @app.route('/coinFlip1') def coinFlip1(): return render_template("coinFlip1.html") #,dict=Imedict kovanecGlava = "https://upload.wikimedia.org/wikipedia/en/1/10/Common_face_of_one_euro_coin.png" kovanecGrb = "https://www.pngfind.com/pngs/m/17-174860_standing-liberty-quarter-type2m-1926-reverse-tails-of.png" kovanec = [kovanecGlava, kovanecGrb] status = ["head", "tails"] @app.route('/coinFlip') def coinFlip(): tmpFlip = random.choice(kovanec) if tmpFlip == kovanecGlava: tmpStatus = "head" else: tmpStatus = "tails" dict = {"img": tmpFlip, "status": tmpStatus} return jsonify(dict) tai_lung_quotes = { 1: "I have come home, Master.", 2: "Your real strength comes from being the Dragon Warrior.", 3: "I am the Dragon Warrior!", 4: "Finally, a worthy opponent. Our battle will be legendary!", 5: "You are not the Dragon Warrior. You will never be the Dragon Warrior until you have the secret of the Dragon Scroll.", 6: "I rotted in jail for 20 years because of your weakness!", 7: "Everything I did, I did to make you proud! Tell me how proud you are, Shifu! Tell me!", 8: "I have come to claim what is rightfully mine.", 9: "I was the best. I was... The Dragon Warrior.", 10: "There is no charge for awesomeness... or attractiveness.", 11: "You knew I was the Dragon Warrior. You always knew. But when Oogway said otherwise, what did you do? What did you do?!", 12: "It is said that the Dragon Warrior can survive for months at a time on nothing but the dew of a single ginkgo leaf and the energy of the universe.", 13: "No one can resist the power of Tai Lung!", 14: "I fought for honor and my family. But you, you fight for nothing.", 15: "How could a fool like you unlock that secret?", 16: "You think I'm a fool. You think I don't know who can and can't help me?", 17: "The scroll has given him power. No one can stand against him now.", 18: "I see you have found the Sacred Peach Tree of Heavenly Wisdom!", 19: "It was never enough for Shifu to train me. He had to control me. He had to control everything!", 20: "When will you realize, the more you take, the less you have?", 21: "I don't want to talk about it. I want to fight about it!", 22: "Your Kung Fu is strong, but my will is stronger!", 23: "You think knowing a little Kung Fu will help you? You think it will make you a warrior?", 24: "I have spent my life waiting for this moment!", 25: "The mark of a true hero is humility." } @app.route('/quote') def quote(): random_quote = random.choice(list(tai_lung_quotes.values())) return render_template("quote.html", quote=random_quote) @app.route('/minInMax') def minInMax(): return render_template("minInMax.html") @app.route('/dobiSt', methods=['POST']) def dobiSt(): min = request.form['min'] max = request.form['max'] min1 = int(min) max1 = int(max) if min1 < max1: nakljucno = random.randint(min1, max1) pprint.pprint(nakljucno) izpis = f"Naključno število med {min} in {max} je {nakljucno}" return jsonify({'izpis':izpis}) @app.route('/randPassword') def randPassword(): return render_template("randPassword.html") @app.route('/dobiGeslo') def dobiGeslo(): geslo = request.args['geslo'] length = 13 chars = string.ascii_letters + string.digits + '!@#$%^&*()' random.seed = (os.urandom(1024)) #izpis = random.randint(male,velike) izpis=f"Novo generirano naključno geslo je: {''.join(random.choice(chars) for i in range(length))}" return jsonify({'izpis':izpis}) @app.route('/metKocke') def metKocke(): return render_template("metKocke.html") @app.route('/dobiMet') def dobiMet(): meti = [random.randint(1, 7) for _ in range(5)] vsota = sum(meti) izpis = f"Število metov je: {meti} in pa vsota vseh metov je: {vsota}" return jsonify({'izpis':izpis}) app.run(host='0.0.0.0', port=8080, debug=True) ``` * > index.html ```html= <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <h1>INDEX</h1> <a href="/coinFlip1">Coin Flip</a><br> <a href="/quote">Quote</a><br> <a href="/minInMax">Min in Max</a><br> <a href="/randPassword">Naključno geslo</a><br> <a href="/metKocke">Met kocke</a><br> </body> </html> ``` * > coinFlip1.html ```html= <!DOCTYPE html> <html lang="en"> <head> <title>Index</title> <style type="text/css"> body { font-family: Arial, sans-serif; margin: 0; padding: 0; background-color: #f2f2f2; } h1 { color: #333; text-align: center; } button { background-color: #007bff; color: white; border: none; padding: 10px 20px; cursor: pointer; } #output { margin-top: 20px; padding: 10px; background-color: #fff; text-align: center; } #myDiv { margin-top: 20px; text-align: center; } img { border-radius: 5px; } </style> </head> <body> <h1>Met kovanca</h1> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js" integrity="sha512-v2CJ7UaYy4JwqLDIrZUI/4hqeoQieOmAZNXBeQyjo21dadnwR+8ZaIJVT8EE2iyI61OV8e6M8PP2/4hpQINQ/g==" crossorigin="anonymous" referrerpolicy="no-referrer"></script> <button onclick="refreshData()" type="coinflip">MET</button> <div id="output"></div> <div id="myDiv"></div> <script> function refreshData() { let output = document.getElementById("output") var myDiv = document.getElementById('myDiv') var slika = document.createElement('img'); $.ajax({ url: "/coinFlip", success: function(result) { output.innerHTML = result.status slika.src = result.img; slika.alt = "My Image"; slika.width = 200; slika.height = 200; myDiv.innerHTML = ''; myDiv.appendChild(slika); } }); } </script> </body> </html> ``` * > quote.html ```html= <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script> <title>Document</title> </head> <body> <a href="/">nazaj</a> <h1>Quote</h1> <p>{{ quote }}</p> </body> </html> ``` * > minInMax.html ```html= <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script> <title>Document</title> </head> <body> <a href="/">nazaj</a> <h1>Min in Max </h1> <!--Vnos--> <input type="text" id="min" placeholder="Vnesi minimalno številko"> <input type="text" id="max" placeholder="Vnesi maksimalno številko"> <button onclick="dobiSt()">Dobi random številko</button> <p id="izpis"></p> <script> function dobiSt() { var min=document.getElementById("min").value; var max=document.getElementById("max").value; $.ajax ({ url: "/dobiSt", type: 'POST', data: { "min" : min, "max" : max }, success: function(result){ console.log("dela"); $('#izpis').text(result.izpis); } }) } </script> </body> </html> ``` * > randPassword.html ```html= <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script> <title>Document</title> </head> <body> <a href="/">nazaj</a> <h1>Naključno geslo</h1> <!--Vnos--> <input type="text" id="geslo" placeholder="poljubno"> <button onclick="dobiGeslo()">Dobi naključno geslo</button> <p id="izpis"></p> <script> function dobiGeslo() { let geslo=document.getElementById("geslo").value; $.ajax ({ url: "/dobiGeslo", data: { "geslo" : geslo }, success: function(result){ console.log("dela"); $('#izpis').text(result.izpis); } }) } </script> </body> </html> ``` * > metKocke.html ```html= <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script> <title>Document</title> </head> <body> <a href="/">nazaj</a> <h1>Naključno geslo</h1> <!--Vnos--> <button onclick="dobiMet()">Dobi met</button> <p id="izpis"></p> <script> function dobiMet() { $.ajax ({ url: "/dobiMet", data: { }, success: function(result){ console.log("dela"); $('#izpis').text(result.izpis); } }) } </script> </body> </html> ``` * > Lastna vaja: Quiz * > main.py ```python= from flask import Flask, render_template, request, jsonify from tinydb import Query, TinyDB import requests import pprint #lepši print v consolu import random import math app = Flask('app') db = TinyDB('baza.json') questions_dict = { "questions": [ {"question1": "Which planet is the largest?"}, {"question2": "How big is this planet?"}, {"question3": "Which planet is the smallest?"}, {"question4": "How big is this planet?"}, {"question5": "On which planet are we currently?"}, {"question6": "How big is this planet?"} ] } @app.route('/') def index(): return render_template("index.html") @app.route('/podstran1') def podstran1(): sez = [] vprasanja = questions_dict['questions'] for i in range(1, 7): m = f'question{i}' for vprasanjaa in vprasanja: if m in vprasanjaa: vprasanje = vprasanjaa[m] sez.append(vprasanje) return render_template("podstran1.html",sez=sez) @app.route('/pravilni') def pravilni(): vsota = 0 odgovor1 = request.args['odgovor1'] odgovor2 = request.args['odgovor2'] odgovor3 = request.args['odgovor3'] odgovor4 = request.args['odgovor4'] odgovor5 = request.args['odgovor5'] odgovor6 = request.args['odgovor6'] if odgovor1 == 'Jupiter': vsota += 1 if odgovor2 == '139820': vsota += 1 if odgovor3 == 'Mercury': vsota += 1 if odgovor4 == '4880': vsota += 1 if odgovor5 == 'Earth': vsota += 1 if odgovor6 == '12742': vsota += 1 pprint.pprint(vsota) izpis = f"Correct answers: {vsota}. The biggest planet is Jupiter. Its diameter is 139.820 km. The smallest planet is Mercury. Its diameter is 4880 km. We are currently on the planet Earth. Its diameter is 12.742 km." return jsonify({'izpis':izpis}) app.run(host='0.0.0.0', port=8080, debug=True) ``` * > index.html ```html= <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <h1>INDEX</h1> <a href="/podstran1">podstran 1</a><br> </body> </html> ``` * > podstran1.html ```html= <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script> <title>Document</title> </head> <body> <a href="/">nazaj</a> <h1>PODSTRAN 1</h1> <!--Vnos--> {% for s in sez %} <li>{{ s }} <br> <!--<input type="text" id="odgovor1" placeholder="Odgovor"> --> </li> {% endfor %} 1:<input type="text" id="odgovor1" placeholder="Odgovor1"> 2:<input type="text" id="odgovor2" placeholder="Odgovor2"><br> 3:<input type="text" id="odgovor3" placeholder="Odgovor3"> 4:<input type="text" id="odgovor4" placeholder="Odgovor4"><br> 5:<input type="text" id="odgovor5" placeholder="Odgovor5"> 6:<input type="text" id="odgovor6" placeholder="Odgovor6"> <button onclick="pravilni()">Dobi pravilne odgovore in število pravilno odgovorjenih</button> <p id="izpis"></p> <script> function pravilni() { let odgovor1=document.getElementById("odgovor1").value; let odgovor2=document.getElementById("odgovor2").value; let odgovor3=document.getElementById("odgovor3").value; let odgovor4=document.getElementById("odgovor4").value; let odgovor5=document.getElementById("odgovor5").value; let odgovor6=document.getElementById("odgovor6").value; $.ajax ({ url: "/pravilni", data: { "odgovor1" : odgovor1, "odgovor2" : odgovor2, "odgovor3" : odgovor3, "odgovor4" : odgovor4, "odgovor5" : odgovor5, "odgovor6" : odgovor6 }, success: function(result){ console.log("dela"); $('#izpis').text(result.izpis); } }) } </script> </body> </html> ``` * > Iskanje jedi, izračunavanje povprečne ocene, pretvorba v različne merske enote * > main.py ```python= from flask import Flask, render_template, request, jsonify from tinydb import Query, TinyDB import requests import math app = Flask('app') db = TinyDB('ocene.json') db.truncate() exchange_rates = conversion_factors = { 'inches': 39.37, # 1 meter = 39.37 inches 'feet': 3.281, # 1 meter = 3.281 feet 'yards': 1.094, # 1 meter = 1.094 yards 'miles': 0.000621371, # 1 meter = 0.000621371 miles } @app.route('/') def index(): return render_template('index.html') @app.route('/Meritve') def meritve(): return render_template('Meritve.html', dict = exchange_rates) @app.route('/Pretvorba', methods=['GET']) def Pretvorba(): number = request.args['number'] meritev = request.args['meritev'] for mera in exchange_rates: if meritev == mera: result = exchange_rates[mera] * int(number) print(result) return jsonify({'number': result, 'meritev': meritev}) @app.route('/jedi') def jedi(): return render_template('jedi.html') @app.route('/dobiJedi') def dobiJedi(): iskanaJed = request.args["iskanaJed"] url = f'https://www.themealdb.com/api/json/v1/1/search.php?s={iskanaJed}' klic = requests.get(url).json() result = [] for jed in klic['meals']: if jed['strArea'] == 'Italian': result.append(jed['strMeal']) ime = 'Nobene jedi najde' if not result else result[0] return f'Ime jedi je: {ime}' @app.route('/ocene') def ocene(): return render_template('ocene.html') @app.route('/shraniocene', methods=["POST"]) def oceneJson(): ocena = request.form["ocena"] ime = request.form["ime"] url = request.form['url'] tableOcene = db.table('ocene') tableOcene.insert({"ime":ime, "ocena":ocena, "url":url}) return vseOcene() @app.route('/seznamOcen') def seznamOcen(): return vseOcene() def vseOcene(): db = TinyDB('ocene.json') tableOcene = db.table('ocene') htmlTable = "<table>" htmlTable += "<tr><th>Predmet</th><th>Ocena</th><th>Emoji</th></tr>" for ocena in tableOcene.all(): htmlTable += f"<tr><td>{ocena['ime']}</td><td>{ocena['ocena']}</td><td>{ocena['url']}</td></tr>" htmlTable += "</table>" return htmlTable students_names = { 'Alice', 'Bob', 'Charlie', 'David', 'Eve', 'Frank', 'Grace', 'Jure' } @app.route('/ucenci') def ucenci(): return render_template("ucenci.html", data=students_names) @app.route('/koncnaOcena') def koncnaOcena(): ucenec = request.args.get('ucenec') ocena = request.args.get('ocena') db.insert({"ucenec": ucenec, "ocene": ocena}) ocena_list = list(map(int, ocena.split(","))) print(ocena_list) avg_ocena = average(ocena_list) return jsonify({"ucenec": ucenec, "ocena": avg_ocena}) def average(ocena): if not ocena: return 0 return sum(ocena) / len(ocena) app.run(host='0.0.0.0', port=8080, debug=True) ``` * > index.html ```html= <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <h1>NALOGE</h1> <a href="/Meritve"> Meritve</a><br> <a href="/jedi"> Jedi</a><br> <a href="/ocene"> Poti</a><br> <a href="/ucenci"> Ucenci</a> </body> </html> ``` * > jedi.html ```html= <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script> <title>Document</title> </head> <body> <a href="/"> DOMOV</a> <br> <div>Poisci jed</div> <div><input type="text" id="iskanaJed" placeholder="Poisci jed"></div> <button onClick="dobiJed()">Poisci</button> <div id="najdenaJed"></div> <script> function dobiJed() { var iskanaJed = document.getElementById("iskanaJed").value; $.ajax({ url: "/dobiJedi", data: { "iskanaJed": iskanaJed }, success: function(result) { document.getElementById("najdenaJed").innerHTML = result; }, error: function(error) { document.getElementById("najdenaJed").innerHTML = "Jed ni bila najdena v seznamu."; } }); } </script> </body> </html> ``` * > meritve.html ```html= <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script> </head> <body> <a href="/"> DOMOV</a> <br> <input type="text" id="number" placeholder="vnesi mera"> <select id="meritev" placeholder="izberi pretvorbo"> {% for i in dict %} <option>{{ i }}</option> {% endfor %} </select> <div id="rezultat"></div> <button onclick="pretvori()">Pretvori</button> <script> function pretvori(){ var number = document.getElementById('number').value; var meritev = document.getElementById('meritev').value; $.ajax({ url: '/Pretvorba', data: { number: number, meritev: meritev }, success: function (result) { $("#rezultat").text(result.number) } }) } </script> </body> </html> ``` * > ocene.html #Shrani v db ```html= <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"> </script> <title>Ocene</title> </head> <input type="text" id="ime" placeholder="vnesi pot"><br> <input type="text" id="ocena" placeholder="vnesi razdaljo"><br> <input type="text" id="url" placeholder="vnesi url slike"><br> <body> <a href="/"> DOMOV</a> <br> <button onclick="shrani()"> Shrani v DB </button><br> <div id="prikaz"></div> <script> $( document ).ready(function() { seznamOcen(); }); function seznamOcen() { $.ajax({ url: "/seznamOcen", success: function(result){ document.getElementById("prikaz").innerHTML = result; } }) } function shrani() { var ime = document.getElementById("ime").value; var ocena = document.getElementById("ocena").value; var url = document.getElementById("url").value; $.ajax({ url: "/shraniocene", type: "POST", data: { "ime": ime, "ocena": ocena, "url": url }, success: function(result){ document.getElementById("prikaz").innerHTML = result; } }) } </script> </body> </html> ``` * > ucenci.html ```html= <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Ucenci</title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script> </head> <body> <select id="ucenec"> {% for item in data%} <option>{{ item }}</option> {% endfor %} </select> <input type="text" name="ocena" id="ocena" placeholder="Jure smrdi"> <button type="button" onclick="getData()">GET</button><br> <div id="ucenc"></div> <div id="koncOcene"></div> <script> function getData(){ var ucenec = document.getElementById('ucenec').value; var ocena = document.getElementById('ocena').value; $.ajax({ url: '/koncnaOcena', data: { ucenec: ucenec, ocena: ocena, }, success: function(result){ $("#ucenc").text(result.ucenec); $("#koncOcene").text(result.ocena); }, error: function(){ console.log("ne dela"); } }) } </script> </body> </html> ``` * > Dobi avte, vseee * > main.py ```python= from flask import Flask, render_template, request, jsonify from tinydb import Query, TinyDB import requests import pprint #lepši print v consolu import random import math app = Flask('app') db = TinyDB('baza.json') avti = { "golf": { "znamka": "Volkswagen", "tip": "O", "drzavaProizvodnje": "DE" }, "clio": { "znamka": "Renault", "tip": "O", "drzavaProizvodnje": "SI" }, "vitara": { "znamka": "Suzuki", "tip": "O", "drzavaProizvodnje": "JP" }, "eVito": { "znamka": "Mercedes-Benz", "tip": "L", "drzavaProizvodnje": "DE" }, "Volvo FH": { "znamka": "Volvo", "tip": "T", "drzavaProizvodnje": "SE" }, "Boxer": { "znamka": "PEUGEOT", "tip": "L", "drzavaProizvodnje": "FR" }, "Lion coach": { "znamka": "MAN", "tip": "P", "drzavaProizvodnje": "PL" } } seznam_tipov = { "O": "Osebni", "T": "Tovorni", "L": "Lahki dostavnik", "P": "Prevoz oseb" } seznam_drzav = { "DE": "Nemčija", "SI": "Slovenija", "JP": "Japonska", "SE": "Švedska", "PL": "Poljska", "FR": "Francija" } @app.route('/') def index(): return render_template("index.html") @app.route('/podstran1') def podstran1(): return render_template("podstran1.html", dict=avti) """Naloga 1 Naredi aplikacijo, ki bo za izbrani avto iz seznama izpisala podatke o avtu. Program naj izpiše znamke in države v obliki koda – naziv. Primer izpisa za izbrani avto Vitara Avto: Vitara Tip: O – Osebni Država proizvodnje: JP - Japonska""" @app.route("/dobiAvto") def dobiAvto(): avto=request.args['avto'] inf = avti[avto] inf1 = inf['znamka'] drzava = inf['drzavaProizvodnje'] tip = inf['tip'] sez = seznam_drzav[drzava] sez1 = seznam_tipov[tip] pprint.pprint(inf) pprint.pprint(sez) pprint.pprint(sez1) izpis = f"Avto: {avto}, Znamka: {inf1}, Tip: {sez1}, Država: {sez}" return jsonify({'izpis':izpis}) app.run(host='0.0.0.0', port=8080, debug=True) ``` * > index.html ```html= <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <h1>INDEX</h1> <a href="/podstran1">podstran 1</a><br> </body> </html> ``` * > podstran1.html ```html= <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script> <title>Document</title> </head> <body> <a href="/">nazaj</a> <h1>PODSTRAN 1</h1> <select id="avto" placeholder="Avto"> {% for i in dict %} <option>{{ i }}</option> {% endfor %} </select> <button onclick="dobiAvto()">Dobi info</button> <p id="izpis"></p> <script> function dobiAvto(){ let avto = document.getElementById('avto').value; $.ajax({ url: '/dobiAvto', data: { "avto": avto }, success: function (result) { console.log("dela"); $("#izpis").text(result.izpis); } }) } </script> </body> </html> ```