# UPN -Primeri iz predavanj
[Wokwi main page](https://wokwi.com/)
[New ESP32 MicroPy project](https://wokwi.com/projects/new/micropython-esp32)
## 2 LED blink

```python
from machine import Pin
from utime import sleep
p18 = Pin(18, Pin.OUT)
p5 = Pin(5, Pin.OUT)
d = 0.1
while True:
#prva ledica
p18.value(1)
sleep(d)
p18.value(0)
sleep(d)
#druga ledica
p5.value(1)
sleep(d)
p5.value(0)
sleep(d)
# naj LEDice izmenično utripajo.
```
## 2 LEDici blink list var
```python
from machine import Pin
from utime import sleep
pList = [5, 18]
pins = []
d = 0.2
for p in pList:
pins.append(Pin(p, Pin.OUT))
while True:
for p in pins:
p.value(1)
sleep(d)
p.value(0)
sleep(d)
# naj LEDice utripajo sinhrono (obe naenkrat).
```
## NeoPixel(WS2812) ring - intro
```python
import neopixel
from machine import Pin
from time import sleep
NUM_LED = 24
leds = neopixel.NeoPixel(Pin(5), NUM_LED)
while True:
for l in range(NUM_LED):
leds[l] = [200, 100, 10]
leds.write()
sleep(0.2)
for l in range(NUM_LED):
leds[l] = (0, 0, 0)
leds.write()
sleep(0.2)
```
# Moje vaje
```python=
#Moje vaje UPNja
from neopixel import NeoPixel
from utime import sleep
from machine import Pin, ADC
import random
NUM_LED = 16
leds = NeoPixel(Pin(18), NUM_LED)
while True:
a = random.randint(0, NUM_LED - 1)
leds[a] = (255, 0, 0)
leds.write()
cycles = random.randint(1, 5)
b = random.randint(0, 1)
for _ in range(cycles):
for i in range(NUM_LED):
if leds[i] == leds[a] and b != 1:
leds[i] = (255, 0, 0)
else:
leds[i] = (0, 0, 255)
leds.write()
sleep(0.4)
leds[i] = (0, 0, 0)
leds.write()
if b == 1 and leds[a] != (0, 0, 0):
leds[a] = (0, 0, 0)
leds.write()
sleep(1)
```
## Vaja12.py
```python=
from neopixel import NeoPixel
from utime import sleep
from machine import Pin, ADC
import random
num_led = 16
leds = NeoPixel(Pin(18), num_led)
a = random.randint(0, 255)
b = random.randint(0, 255)
c = random.randint(0, 255)
while True:
d = a//16
e = b//16
f = c//16
for i in range(num_led):
leds[i] = (a, b, c)
leds.write()
sleep(0.5)
a -= d
b -= e
c -= f
for i in reversed(range(num_led)):
leds[i] = (0, 0, 0)
leds.write()
sleep(0.5)
a = random.randint(0, 255)
b = random.randint(0, 255)
c = random.randint(0, 255)
```
## Vaja11.py
```python=
from machine import Pin
button1 = Pin(18, Pin.IN, Pin.PULL_UP)
button2 = Pin(19, Pin.IN, Pin.PULL_UP)
ledO = Pin(2, Pin.OUT)
ledP = Pin(4, Pin.OUT)
while True:
if not button1.value():
ledO.value(1)
elif not button2.value():
ledO.value(1)
ledP.value(1)
else:
ledO.value(0)
ledP.value(0)
```
## Vaja10.py
```python=
from machine import Pin, ADC
from utime import sleep
from neopixel import NeoPixel
num_led = 16
leds = NeoPixel(Pin(18), num_led)
pot1 = ADC(Pin(15))
pot2 = ADC(Pin(2))
pot3 = ADC(Pin(4))
while True:
leds.fill([pot1.read()//16,pot2.read()//16,pot3.read()//16])
leds.write()
```
## Vaja9.py
```python=
from neopixel import NeoPixel
from machine import Pin
from utime import sleep
import time
led_num = 60
leds = NeoPixel(Pin(18), led_num)
while True:
current_time = time.localtime()
minutes, seconds = current_time[4:6]
minutes_pixel = int((minutes % 60) * (led_num / 60))
seconds_pixel = int((seconds % 60) * (led_num / 60))
leds.fill((0, 0, 0))
leds[minutes_pixel] = (0, 255, 0)
leds[seconds_pixel] = (255, 0, 0)
leds.write()
sleep(1)
```
## Vaja8.py
```python=
from neopixel import NeoPixel
from machine import Pin
from utime import sleep
import random
led = 16
st = 0
st2 = 0
leds = NeoPixel(Pin(18), led)
while True:
a = random.randint(100, 256)
for i in range(led):
if st > a:
st = 0
leds[st2%led] = (25, 100, 250)
leds.write()
sleep(4)
if st2 == led:
st2 = 0
leds[i] = (25, 100, 250)
leds.write()
sleep(0.1)
leds[i] = (0, 0, 0)
leds.write()
st2 += 1
st += random.randint(0, 16)
```
## Vaja7.py
```python=
from neopixel import NeoPixel
from utime import sleep
from machine import Pin
led = 24
st = led//3
leds = NeoPixel(Pin(18), led)
while True:
for i in range(st):
leds[i] = (113, 50, 200)
leds.write()
sleep(1)
for i in range(st):
leds[i] = (0, 0, 0)
leds.write()
for i in range(st, (2*st)):
leds[i] = (113, 50, 200)
leds.write()
sleep(1)
for i in range(2*st):
leds[i] = (0, 0, 0)
leds.write()
for i in range((2*st), led):
leds[i] = (113, 50, 200)
leds.write()
sleep(1)
for i in range((2*st), led):
leds[i] = (0, 0, 0)
leds.write()
```
## Vaja6.py
```python=
from neopixel import NeoPixel
from utime import sleep
from machine import Pin
led = 16
st = 0
leds = NeoPixel(Pin(18), led)
while True:
for i in range(led):
if st == led:
st = 0
leds[i] = (255, 0, 0)
leds[st] = (0, 0, 255)
st+=2
leds.write()
sleep(1)
for i in range(led):
if st == led:
st = 0
leds[i] = (0, 0, 255)
leds[st] = (255, 0, 0)
st+=2
leds.write()
sleep(1)
```
## Vaja5.py
```python
from neopixel import NeoPixel
from utime import sleep
from machine import Pin
import random
NUM_LED = 160
count = 0
st = NUM_LED//4
leds = NeoPixel(Pin(18), NUM_LED)
while True:
leds[count] = (random.randint(0, 255), random.randint(0, 255),random.randint(0, 255))
leds[count + 40] = (random.randint(0, 255), random.randint(0, 255),random.randint(0, 255))
leds[count + 80] = (random.randint(0, 255), random.randint(0, 255),random.randint(0, 255))
leds[count + 120] = (random.randint(0, 255), random.randint(0, 255),random.randint(0, 255))
leds.write()
sleep(0.0000000000000000000000000000000000000001)
count+=1
for i in range(NUM_LED):
leds[i] = (0, 0, 0)
leds.write()
if count == NUM_LED//4:
count = 0
```
## Vaja4.py
```python=
"""import neopixel
from machine import Pin
from utime import sleep
NUM_LED = 16
i = 0
sez = ""
led = neopixel.NeoPixel(Pin(18), NUM_LED)
while True:
sez = str(bin(i))
print(sez)
for index in sez:
if index == "1":
led[index] = (255, 0, 0)
led.write()
else:
led[index] = (102, 3, 5)
led.write()
i += 1"""
import neopixel
from machine import Pin
from utime import sleep
NUM_LED = 16
i = 0
led = neopixel.NeoPixel(Pin(18), NUM_LED)
while True:
sez = bin(i)[2:]
sez = '5' * (NUM_LED - len(sez)) + sez
print(sez)
for index, value in enumerate(sez):
if value == "1":
led[index] = (25, 60, 120)
elif value == "0":
led[index] = (102, 23, 45)
led.write()
i += 1
sleep(1)
```
## Vaja3.py
```python=
import neopixel
from machine import Pin
from utime import sleep
NUM_LED = 16
leds = neopixel.NeoPixel(Pin(18), NUM_LED)
while True:
for l in range(NUM_LED):
leds[l] = (204, 102, 143)
leds.write()
sleep(0.2)
for l in range(NUM_LED):
leds[l] = (0, 0, 0)
leds.write()
sleep(0.2)
```
## Vaja2.py
```python=
import neopixel
from machine import Pin
from utime import sleep
NUM_LED = 16
leds = neopixel.NeoPixel(Pin(18), NUM_LED)
while True:
for l in range(NUM_LED):
leds[l] = (204, 102, 143)
leds.write()
sleep(0.2)
for l in range(NUM_LED):
leds[l] = (0, 0, 0)
leds.write()
sleep(0.2)
```
## Moj projekt
### Vremenska postaja
# Načrtovanje Domače Vremenske Postaje s Flaskom
### Uvod
Projekt bo zdaj nadgrajen z vključitvijo Flask strežnika, ki bo omogočal zajem, shranjevanje ter prikazovanje meteoroloških podatkov v spletnem vmesniku. Poleg tega bomo dodali možnost procesiranja povprečnih, maksimalnih in minimalnih vrednosti vremenskih podatkov za določeno obdobje.
### Cilji in Izzivi
Poleg prvotnih ciljev, kot so sestava postaje in programiranje mikrokrmilnika, bodo zdaj vključeni tudi naslednji izzivi:
- **Ustvarjanje Flask Aplikacije:** Spoznati Flask okolje in vzpostaviti povezavo med vremensko postajo in spletnim vmesnikom.
- **Izbira Komponent:** Izbrati najustreznejše senzorje in mikrokrmilnik za zanesljivo delovanje.
- **Sestava Delov:** Sestaviti komponente in jih pravilno povezati, da bodo delovale kot dobro uigrana ekipa.
- **Programiranje Mikrokrmilnika:** Razviti program za zajem in posredovanje podatkov.
- **Implementacija Podatkovne Baze:** Ustvariti podatkovno bazo za shranjevanje meteoroloških podatkov.
- **Oblikovanje Frontenda:** Ustvariti pregledno spletno stran za prikazovanje meteoroloških podatkov v realnem času.
- **Povezovanje Backend-Frontend:**
- Zagotoviti, da se podatki pravilno prenašajo iz Flask strežnika v spletni vmesnik.
- Dodati možnost prikaza povprečnih, maksimalnih in minimalnih vrednosti vremenskih podatkov za določeno obdobje.
## Komponente in Oprema
Oprema za ta projekt bo enako uporabna kot žlica za juho - neizogibna! Vključuje:
- **Senzor Temperature:** Za natančno merjenje temperature zraka v okolici.
- **Vlažnostni Senzor:** Meri količino vlage v zraku, brez pretiravanja.
- **Mikrokrmilnik:** Glavni možgani operacije, ki bodo skrbeli za obdelavo in posredovanje podatkov.
- **Zaslon ali Povezava z Računalnikom:** Za prikaz rezultatov meritev, da bodo jasni kot sončen dan.
- **Podatkovna Baza:** Za shranjevanje meteoroloških podatkov za kasnejšo analizo.
**Nasvet:** Ne pozabi na čarobno zaklinjanje "Hokus Pokus - Delaj!". Nekateri komponenti se obnašajo kot pubertetniki, ki potrebujejo malo dodatne vzpodbude.
## Načrt Dela
1. **Izdelava Flask Aplikacije:**
- bolje spoznati Flask okolje.
- Ustvariti Flask aplikacijo za sprejemanje in obdelavo podatkov od vremenske postaje.
2. **Pisanje API Endpointov:**
- Določiti ustrezne API endpointe, preko katerih bo vremenska postaja pošiljala podatke na Flask strežnik.
3. **Implementacija Podatkovne Baze:**
- Ustvariti podatkovno bazo za shranjevanje meteoroloških podatkov.
4. **Oblikovanje Frontenda:**
- Ustvariti pregledno spletno stran za prikazovanje meteoroloških podatkov v realnem času.
5. **Povezovanje Backend-Frontend:**
- Zagotoviti, da se podatki pravilno prenašajo iz Flask strežnika v spletni vmesnik.
- Dodati možnost prikaza povprečnih, maksimalnih in minimalnih vrednosti vremenskih podatkov za določeno obdobje.
6. **Testiranje Delovanja Spletne Aplikacije:**
- Preveriti, ali spletni vmesnik pravilno prikazuje in ažurira meteorološke podatke.
7. **Optimizacija in Izboljšave:**
- Po potrebi izboljšati delovanje spletne aplikacije in uporabniške izkušnje.
## Zaključek
S tem projektom bomo pridobili dragocene izkušnje na področju elektronike, programiranja, razvoja spletnih aplikacij in uporabe podatkovnih baz. Z veseljem pričakujem rezultate in upam, da bomo ustvarili zanesljivo vremensko postajo z odličnim spletnim vmesnikom, ki bo omogočal analizo povprečnih, maksimalnih in minimalnih vrednosti vremenskih podatkov za določeno obdobje! 🌦️🔧📊
| Del postaje | Cena (v EUR) | URL |
| ----------------- |:------------ |:------------:|
| Senzor temp/vlage | 1 | alilink.com |
| ESP32 | 3 | alilink2.com |
| Sončni panel | 30 | alilink3.com |
# Wokwi - Neopixel LED ring
Navodila vaj kopiraj k sebi in zraven dopiši kodo rešitev. Dodaj še screenshot za boljšo preglednost.
Nov projekt.
[Wokwi mPy ESP32](https://wokwi.com/projects/new/micropython-esp32)
## 1. **Naloga: Alternirajče utripanje vsake druge LED diode:**
- Napiši program, ki naj prižge vsako prvo in drugo LED diodo v različni barvi. Barvi naj se izmenjujeta na eno sekundo.
Primer 4 Ledic. (R - rdeča, M - modra)
1. LED R, 2. LED M, 3. LED R, 4. LED M
2. LED M, 2. LED R, 3. LED M, 4. LED R
3. LED R, 2. LED M, 3. LED R, 4. LED M
4. LED M, 2. LED R, 3. LED M, 4. LED R
## 2. **Naloga: Vklop in izklop LED diod v tretjinah obroča:**
- Razdeli Neopixel obroč na tri dele in napiši program, ki vklopi in izklopi LED diode v vsaki tretjini zaporedoma.
- **BONUS**: funkcijo pripravi, da krog razdeli na poljubno delov.
## 3. **Naloga: LED ruleta:**
- Ustvari program, ki naključno izbere eno LED diodo in jo prižge. Pred tem naj se lučka vrti po krogu kot pri ruleti, nato pa se ustavi na naključno izbrani LED diodi. Po kratkem časovnem zamiku jo ugasne, nato pa izbere novo LED diodo.
## 4. **Naloga: Gibanje kazalca za sekunde na uri:**
- Simuliraj gibanje sekundnega kazalca ure tako, da prižgeš LED diodo, ki predstavlja sekunde. Posodobi jo vsako sekundo.
**Uporabi 60 LED krog.**
- **BONUS**: implementiraj še minutni kazalec.
```python=
#uporabi kar
import time
sec = time.time()
```
# API naloge
**Velik del vaje je učenje branja dokumentacije**
**Dokumentacija Requests knjižnice:** [Docs](https://requests.readthedocs.io/en/latest/)
## Osnoven API klic
```python=
response = requests.get("https://example.com/api")
```
## Parametri klica (ponavadi, ko delamo GET klic)
```python=
params = {"param1": "value1", "param2": "value2"}
response = requests.get("https://example.com/api", params= params)
```
## Body klica (ponavadi, ko delamo POST klic)
```python=
headers = {
"User-Agent": "my-app/1.0",
"Authorization": "Bearer token123",
"Accept": "application/json" # zahteva JSON podatkov
}
response = requests.get("https://example.com/api", headers=headers)
```
Seveda lahko kombiniramo headers in params.
## Primerjava GET in POST (za spodnje vaje bomo večino uporabljali GET)
| Lastnost | GET | POST |
|--------------------------|------------------------------------|-----------------------------------|
| **Podatki v URL-ju** | Podatki so priloženi v URL-ju. | Podatki niso v URL-ju. |
| **Omejitev dolžine** | Omejitev dolžine URL-ja (običajno omejeno na približno 2.000 znakov). | Ni omejitve dolžine podatkov v telesu zahteve. |
| **Varnost** | Manj varno, ker so podatki vidni v URL-ju in jih je mogoče videti v zgodovini brskalnika ali dnevnikih strežnika. | Bolj varno, ker se podatki prenašajo v telesu zahteve in niso vidni v URL-ju. |
| **Podatki v telesu** | Podatki se ne prenašajo v telesu zahteve, zato so primerni za zahteve, ki ne spreminjajo stanja na strežniku (samo read). | Podatki se prenašajo v telesu zahteve, zato so primerni za zahteve, ki spreminjajo stanje na strežniku (npr. dodajanje ali urejanje podatkov). |
| **Uporaba v obrazcih HTML** | Primeren za branje podatkov iz strežnika, na primer iskanje rezultatov iskanja. | Primeren za pošiljanje obrazcev s podatki na strežnik, na primer prijavo ali oddajo obrazca. |
[Za radovedne](https://www.guru99.com/difference-get-post-http.html)
## Naloge
1. Seznam vseh sposobnosti poljubnega Pokémona (Uporaba Pokémon API)
2. Iskanje aktivnosti glede na kriterije (Uporaba Bored API)
3. Odkrivanje dejstev o sadju (Uporaba Trefle API)
4. Sledenje Mednarodni vesoljski postaji
├── 4.1 Sledenje lokaciji MVP
└── 4.2 Kako daleč je MVP od mene zdaj? (Zahteva vnos vaše lokacije)
└── Vnesite vašo lokacijo (Zemljepisna širina, Zemljepisna dolžina): [Vnos uporabnika]
5. Prevedite slovensko besedo skozi N prevodov in nazaj v slovenščino
## Navodila
**za prijavo na APIje, ki potrebujejo login (za dostop do API ključa) uporabi kar "temp mail"**
1. **Seznam vseh sposobnosti izbranega Pokemona (Pokémon API):**
Pridobi vse sposobnosti izbranega Pokemona iz Pokémon API-ja. Uporabite API: https://pokeapi.co.
Skripta naj nato izvleče in prikaže seznam sposobnosti, ki jih Pikachu poseduje.
```python=
import requests
import json
choice = input("Izberi pokemona: ").lower()
url = "https://pokeapi.co/api/v2/pokemon/" + choice
response = requests.get(url)
data = response.json()
for ability in data['abilities']:
print(ability['ability']['name'])
```
2. **Iskanje aktivnosti glede na kriterije (Bored API):**
Ustvarite funkcijo, ki bo sprejela parametre, kot so cena, število ljudi in število aktivnosti, ter uporabila Bored API za iskanje primernih aktivnosti. Uporabite naslovno točko: http://www.boredapi.com. Skripta naj pošlje zahteve na Bored API s podanimi parametri in vrne seznam predlaganih aktivnosti.
3. **Odkrivanje dejstev o sadju (Trefle API):**
Napišite skripto, ki omogoča vnos imena sadja in izvedbo iskanja petih zanimivih dejstev o njem prek Trefle API-ja. Uporabite naslovno točko: https://trefle.io. Skripta naj razčleni odgovor API-ja in izvleče informacije, kot so znanstveno ime, družina, rod in druge zanimive podrobnosti. Nato izpiši še 5 poljubnih dejstev o sadju.
4. **Sledenje MVP (Mednarodna vesoljska postaja):**
1. Sledenje lokaciji MVP:
Izpiši trenutno lokacijo MVP.
1. Razdalja do MVP:
Vnesite svojo trenutno lokacijo (zemljepisno širino in dolžino) in izračunajte razdaljo med vašo lokacijo in trenutno lokacijo MVP.
**po spletu poišči kako izračunamo razdaljo med dvema koordinatama**
5. **Prevedite slovensko besedo skozi N prevodov in nazaj v slovenščino:**
Ta naloga vključuje večkratno prevajanje slovenske besede in nato povratno prevajanje v slovenščino. Omogočite uporabniku, da določi število prevodov (N) in vpiše besedo za prevajanje. Skripta naj prevede besedo skozi N prevodov (naključnih jezikov) in jo nato ponovno prevede v slovenščino za končni rezultat. Uporabi poljuen API
**implementacija čez katere jezike gre prevod je poljubna.**
6. **implementriaj poljubno uporabnost nekega APIja**
### Oblika izbirnika
1. Poglej sposobnosti Pokémona
└── Vnesi ime Pokémona (npr. Pikachu):
2. Išči aktivnosti
└── Vnesi ceno, število ljudi in število aktivnosti (npr. 10, 5, 3):
3. Odkrij dejstva o sadju
└── Vnesi ime sadja (npr. apple):
4. Sledenje MVP
1. Sledi lokaciji MVP
2. Izračunaj razdaljo do MVP
5. Prevajanje besed skozi N prevodov
└── Vnesi število prevodov (npr. 3) in besedo za prevajanje (npr. hiša):
Recimo slovensko -> angleško -> italjankso -> nemško -> slovensko
# Povezava z WiFi na ESP32
import network
import time
import urequests
print("Connecting to WiFi", end="")
sta_if = network.WLAN(network.STA_IF)
sta_if.active(True)
sta_if.connect('Wokwi-GUEST', '')
while not sta_if.isconnected():
print(".", end="")
time.sleep(0.1)
print(" Connected!")
# requests/urequests delujeta enako
klic = urequests.get("https://api.chucknorris.io/jokes/random")
print(klic.json())
## Pomoč pri oblikovanju menija:
```python=
import requests
def main():
while True:
print("Izberite nalogo:")
print("1. Poglej sposobnosti Pokémona")
print("2. Iskanje aktivnosti")
print("3. Informacije o sadju")
print("4. Sledenje MVP")
print("5. Verižno prevajanje")
choice = input("Izberi možnost: ")
if choice == "1":
pokemon_name = input("Vnesite ime Pokémona: ")
# koda za izbiro 1
elif choice == "2":
# Koda za izbiro 2
pass
elif choice == "3":
# Koda za izbiro 3
pass
elif choice == "4":
print("1. Sledi lokaciji MVP")
print("2. Izračunaj razdaljo do MVP")
mvp_choice = input("Izberite podnalogo: ")
if mvp_choice == "1":
pass # koda za izbiro 4.1
elif mvp_choice == "2":
pass # koda za izbiro 4.2
elif choice == "5":
# Koda za izbiro 5
pass
main()
```
# vaja 2
Neopixel krog, potenciometer in gumb.
## 1. Hitrost animacije
Naredi preprosto animacijo na Neopixel krogu, kjer se ena LEDica vrti okoli kroga. S potenciometrom kontroliramo hitrost vrtenja.
```python=
from machine import Pin, ADC
from utime import sleep
from neopixel import NeoPixel
import random
num_led = 16
leds = NeoPixel(Pin(18), num_led)
pot1 = ADC(Pin(2))
while True:
for i in range(num_led):
a = pot1.read()
leds[i] = (random.randint(0, 255), random.randint(0, 255), random.randint(0, 255))
leds.write()
sleep(a/10000)
leds[i] = (0, 0, 0)
leds.write()
sleep(a/10000)
```
## 2. Moč mutacije
Naredi animacijo na NeoPixel krogu, kjer se za prvo LEDico izbere naključna barva.
Vse nadaljne barve naj bodo naključna mutacija prve barve (torej naključno spremenimo RGB vrednosti prve barve). **Ko se krog konča, naj bodo vse LEDice prižgane.**
```python=
from neopixel import NeoPixel
from machine import Pin, ADC
from urandom import randint
NUM_LEDS = 16
leds = NeoPixel(Pin(18), NUM_LEDS)
potentiometer = ADC(Pin(4))
while True:
barva = [randint(0, 255) for _ in range(3)]
for i in range(NUM_LEDS):
mocMutacije = potentiometer.read_u16() / 65535.0
rand_min = int(-mocMutacije * 255)
rand_max = int(mocMutacije * 255)
rand_r = randint(rand_min, rand_max)
mutated_color = [(int(barva[j] + rand_r) % 256) for j in range(3)]
leds[i] = tuple(mutated_color)
leds.write()
```
Ko se krog obrne, naj se izbere novo prvo barvo in se animacija nadaljuje v neskončno.
S potenciometrom kontroliraj moč mutacije (torej za koliko se prva barva spremenija).
* v konzolo tudi izpiši moč mutacije
## 3. Refleks igra
Napiši refleks igrico, kjer se na začetku igre vse LEDice v krogu pobarvajo na zeleno.
Po naključno dolgem času pobarvaj vse LEDice na rdečo.
Po prehodu na rdečo, čakaj, da uporabnik klikne gumb.
Izpiši v konzolo, kako dolgo je uporabnik potreboval, da je odreagiral na spremembo barve.
* opozori uporabnika, če goljufa (klika pred rdečo)
```mermaid
flowchart TD
A[ZELENA] -->|random delay 1-4s| B[RDEČA]
B -->|čakaj na klik gumba| C[Izpiši čas]
C -->|delay 2s| A
```
## vaja7
Pripomočki:
2 NeoPixel kroga
3 potenciometri
1 gumb
Navodila:
Zagon igre:
Ko se igra prižge, 1. NeoPixel krog zažari v naključno izbrani barvi.
Ugibanje barve:
Igralec z uporabo treh potenciometrov (vsak za eno izmed RGB komponent) prilagaja barvo 2. NeoPixel kroga.
Cilj je, da se izbrana barva čim bolj približa barvi, ki sveti na 1. krogu.
Ocenjevanje:
Ko je igralec zadovoljen s svojo izbiro barve, pritisne gumb.
Igra nato prikaže razliko med izbrano in ciljno barvo za vsako RGB komponento posebej ter skupno napako, ki je vsota vseh treh napak.
Nova igra:
Po končani igri se igralni proces začne znova z novo, naključno izbrano barvo na 1. NeoPixel krogu.
```python=
from neopixel import NeoPixel
from utime import sleep
from machine import Pin, ADC
import random
num_led = 16
st1 = []
st2 = []
prime = 765
leds1 = NeoPixel(Pin(18), num_led)
leds2 = NeoPixel(Pin(19), num_led)
pot1 = ADC(Pin(15))
pot2 = ADC(Pin(2))
pot3 = ADC(Pin(4))
button = Pin(17, Pin.IN, Pin.PULL_UP)
while True:
a = random.randint(0, 255)
b = random.randint(0, 255)
c = random.randint(0, 255)
leds1.fill([a, b, c])
leds1.write()
st1 = [a, b, c]
print("1. krog:", st1)
d, e, f = 0, 0, 0
while button.value() == 1:
d = pot1.read()//16
e = pot2.read()//16
f = pot3.read()//16
leds2.fill([d, e, f])
leds2.write()
st2 = [d, e, f]
print("2. krog:", st2)
raz1 = [abs(x - y) for x, y in zip(st1, st2)]
raz2 = sum(raz1)
proce = round((raz2 / prime) * 100)
print(raz1)
print(raz2)
print(proce, "%")
break
from neopixel import NeoPixel
from machine import Pin, ADC
from utime import sleep
import random
num_led = 16
ld = NeoPixel(Pin(19), num_led)
gld = NeoPixel(Pin(18), num_led)
bttn = Pin(5, Pin.IN, Pin.PULL_UP)
pot1 = ADC(Pin(15))
pot2 = ADC(Pin(2))
pot3 = ADC(Pin(0))
while True:
a = random.randint(0, 255)
b = random.randint(0, 255)
c = random.randint(0, 255)
for i in range(num_led):
ld[i] = (a, b, c)
ld.write()
print(a, b, c)
while bttn.value() == 1:
e = pot1.read()//16
d = pot2.read()//16
f = pot3.read()//16
gld.fill([e, d, f])
gld.write()
print(e, d, f)
print(abs(a-e), abs(b-d), abs(c-f))
rez2 = abs(a - e) + abs(b - d) + abs(c - f)
proce = round((rez2 / 765) * 100)
print(proce,"%")
break
```
## Vaja 6
Za vajo potrebuješ NeoPixel krog in gumb.
Prva lučka se prižge samodejno na zeleno barvo.
Program čaka, da uporabnik pritisne gumb.
Ko uporabnik pritisne gumb, se naslednja ledica v zaporedju pobarva na eno od naslednjih barv.
Če je bil gumb kliknjen po manj kot 1s po prejšne prižgani ledici - ZELENA
Če je bil pritisnjen po 1s in pred 2s - MODRA
po 2s - RDEČA
```python=
from neopixel import NeoPixel
from utime import sleep
from machine import Pin
import time
num_led = 18
button = Pin(19, Pin.IN, Pin.PULL_UP)
leds = NeoPixel(Pin(18), num_led)
zacetek = time.time()
led = 0
while True:
if led == num_led:
break
cas = time.time() - zacetek
if button.value() == 0:
if cas < 1:
leds[led] = (0, 255, 0)
elif 1 <= cas < 2:
leds[led] = (0, 0, 255)
else:
leds[led] = (255, 0, 0)
leds.write()
sleep(0.1)
led = (led + 1) % num_led
zacetek = time.time()
```
## Vaja 5
Cilj te vaje je programirati ESP mikrokrmilnik za simulacijo metanja kocke. Ko uporabnik pritisne gumb, se bo naključno izpisalo število od 1 do 6 predstavljeno na LED diodah.
BONUS:
Naredi, da preden se izpiše met kocke simuliraš animacijo metanja kocke.
Torej se naključno preklaplja med različnimi vrednostmi, dokler ne pristane na končni izbiri.
Poskusi implementirati zvok s pomočjo Piezo zvočnika.
from machine import Pin , PWM
import utime
```python=
from neopixel import NeoPixel
from utime import sleep
from machine import Pin, PWM
import random
num_led = 6
leds = NeoPixel(Pin(18), num_led)
while True:
b = random.randint(1, num_led)
vnos = input("Za zacetek pritisni q: ")
print(f"vasa kocka je: {b}")
while vnos == "q":
a = random.randint(1, num_led)
for i in range(a):
leds[i] = (255, 0, 0)
leds.write()
sleep(1)
for i in range(a):
leds[i] = (0, 0, 0)
leds.write()
sleep(0.1)
if a == b:
vnos = input("ce zelite nadaljevati kliknite e: ")
if vnos == "e":
break
```
## vaja4
Cilj naloge je ustvariti igrico, kjer se na 50 LEDičnem krogu naključno prižgejo pet LEDic. Igralec bo upravljal potenciometer, s katerim bo poskušal doseči želeno LEDico. Nato pa se bo prižgala naslednja. Igralec bo moral doseči vseh pet LEDic in program bo izpisal čas, ki ga je igralec porabil za dokončanje igre.
Bonus:
LEDice se naj razmaknejo vsaj 20 narazen za vsako naključno prižigajočo se LEDico.
Igralec bo moral ostati vsaj 0.5 sekunde na pravilni LEDici.
```python=
from neopixel import NeoPixel
from utime import sleep
from machine import Pin, ADC
import random, time
num_led = 50
rez = 0
leds = NeoPixel(Pin(18), num_led)
pot = ADC(Pin(4))
st = pot.read()
value = round(st/4096*50)
cas1 = time.time()
while rez != 5:
a = random.randint(0, num_led)
leds[a] = (255, 0, 255)
leds.write()
while value != a:
st = pot.read()
value = round(st/4096*50)
print(value)
if value == a:
rez += 1
leds[a] = (0, 0, 0)
leds.write()
cas2 = time.time()
cas = cas2 - cas1
print(f"Uganil si vse točke v {cas} sekundah")
```
## UPN - Wokwi primeri
Wokwi main page
New ESP32 MicroPy project
2 LED blink
prva
from machine import Pin
from utime import sleep
## Vaja 3 - nalaganje barv
V Wokwiju izdelaj naslednjo animacijo.
naloga naj deluje na poljubne velikem krogu
```python=
from neopixel import NeoPixel
from utime import sleep
from machine import Pin
import random
num_led = 18
st = 0
leds = NeoPixel(Pin(18), num_led)
while True:
for i in range(num_led):
leds[i] = (random.randint(0, 255), random.randint(0, 255),random.randint(0, 255))
leds.write()
sleep(0.1)
leds[i] = (0, 0, 0)
leds.write()
sleep(0.1)
st += 1
if num_led== st:
leds[i] = (random.randint(0, 255), random.randint(0, 255),random.randint(0, 255))
leds.write()
num_led -= 1
st = 0
```
barva = [rand(255), rand(255), rand(255)]
```python=
from neopixel import NeoPixel
from machine import Pin
import utime
import urandom
NUM_LEDS = 16
leds = NeoPixel(Pin(18), NUM_LEDS)
button = Pin(2, Pin.IN)
def set_led_color(color):
for i in range(NUM_LEDS):
leds[i] = color
leds.write()
def wait_for_button_press():
while button.value() == 0:
pass
def wait_for_button_release():
while button.value() == 1:
pass
while True:
set_led_color((0, 255, 0))
utime.sleep(urandom.randint(5, 15))
set_led_color((255, 0, 0))
start_time = utime.ticks_ms()
wait_for_button_press()
wait_for_button_release()
end_time = utime.ticks_ms()
reaction_time = utime.ticks_diff(end_time, start_time)
if leds[0] == (0, 255, 0):
print("Don't cheat!")
break
else:
print("Reaction Time: {} ms".format(reaction_time))
break
```
## Lastne vaje
```python=
from neopixel import NeoPixel
from machine import Pin
from utime import sleep
import random
num_led = 16
leds = NeoPixel(Pin(18), num_led)
button = Pin(5, Pin.IN, Pin.PULL_UP)
while True:
if button.value() == 0:
for i in range(num_led):
leds[i] = (random.randint(0, 125), random.randint(0, 125), random.randint(0, 125))
leds.write()
else:
for i in range(num_led):
leds[i] = (125, 0, 255)
leds.write()
from machine import Pin, ADC
from utime import sleep
from neopixel import NeoPixel
import random
num_led = 16
leds = NeoPixel(Pin(18), num_led)
time = 30
while True:
if time >= 20:
leds.fill([0, 255, 0])
leds.write()
sleep(1)
elif time < 20 and time >= 10:
leds.fill([255, 255, 0])
leds.write()
sleep(1)
else:
leds.fill([255, 0, 0])
leds.write()
sleep(1)
if time <= 0:
print("Konec odstevanja")
break
time -= 1
```
# Jinja
Jinja cheatsheet
ads via CarbonYour new development career awaits. Check out the latest listings.
ads via Carbon
Basic usage
- variable x has content: {{ x }}
- expression: {{ x + 1 }}
- escaped for HTML: {{ x | e }}
Control structures
{% for x in range(5) %}
{% if x % 2 == 0 %}
{{ x }} is even!
{% else %}
{{ x }} is odd!
{% endif %}
{% endfor %}
Whitespace trimming
these are
{{ "three" }}
lines.
this is conc
{{- "at" -}}
enated.
Special blocks
{% filter e %}
{% raw %}
This is a raw block where {{nothing is evaluated}}
{% not even this %}
and <html is escaped> too with "e" filter
{% endraw %}
{% endfilter %}
{% macro myfunc(x) %}
this is a reusable macro, with arguments: {{x}}
{% endmacro %}
{{ myfunc(42) }}
{#
this is a comment
#}
Inheritance
shared.html
<html>
<head>
<title>{%block title %}{% endblock %}</title>
</head>
<body>
<header><h1>{% block title %}{% endblock %}</h1></header>
<main>{% block content %}{% endblock %}</main>
</body>
</html>
home.html
{% extends "shared.html" %}
{% block title %}Welcome to my site{% endblock %}
{% block content %}
This is the body
{% endblock %}
When generating HTML from templates, there’s always a risk that a variable will include characters that affect the resulting HTML. There are two approaches:
manually escaping each variable; or
automatically escaping everything by default.
Jinja supports both. What is used depends on the application configuration. The default configuration is no automatic escaping; for various reasons:
Escaping everything except for safe values will also mean that Jinja is escaping variables known to not include HTML (e.g. numbers, booleans) which can be a huge performance hit.
The information about the safety of a variable is very fragile. It could happen that by coercing safe and unsafe values, the return value is double-escaped HTML.
Working with Manual Escaping
If manual escaping is enabled, it’s your responsibility to escape variables if needed. What to escape? If you have a variable that may include any of the following chars (>, <, &, or ") you SHOULD escape it unless the variable contains well-formed and trusted HTML. Escaping works by piping the variable through the |e filter:
{{ user.username|e }}
Working with Automatic Escaping
When automatic escaping is enabled, everything is escaped by default except for values explicitly marked as safe. Variables and expressions can be marked as safe either in:
The context dictionary by the application with markupsafe.Markup
The template, with the |safe filter.
If a string that you marked safe is passed through other Python code that doesn’t understand that mark, it may get lost. Be aware of when your data is marked safe and how it is processed before arriving at the template.
If a value has been escaped but is not marked safe, auto-escaping will still take place and result in double-escaped characters. If you know you have data that is already safe but not marked, be sure to wrap it in Markup or use the |safe filter.
Jinja functions (macros, super, self.BLOCKNAME) always return template data that is marked as safe.
String literals in templates with automatic escaping are considered unsafe because native Python strings are not safe.
List of Control Structures
A control structure refers to all those things that control the flow of a program - conditionals (i.e. if/elif/else), for-loops, as well as things like macros and blocks. With the default syntax, control structures appear inside {% ... %} blocks.
For
Loop over each item in a sequence. For example, to display a list of users provided in a variable called users:
<h1>Members</h1>
<ul>
{% for user in users %}
<li>{{ user.username|e }}</li>
{% endfor %}
</ul>
As variables in templates retain their object properties, it is possible to iterate over containers like dict:
<dl>
{% for key, value in my_dict.items() %}
<dt>{{ key|e }}</dt>
<dd>{{ value|e }}</dd>
{% endfor %}
</dl>
Python dicts may not be in the order you want to display them in. If order matters, use the |dictsort filter.
<dl>
{% for key, value in my_dict | dictsort %}
<dt>{{ key|e }}</dt>
<dd>{{ value|e }}</dd>
{% endfor %}
</dl>
Inside of a for-loop block, you can access some special variables:
Variable
Description
loop.index
The current iteration of the loop. (1 indexed)
loop.index0
The current iteration of the loop. (0 indexed)
loop.revindex
The number of iterations from the end of the loop (1 indexed)
loop.revindex0
The number of iterations from the end of the loop (0 indexed)
loop.first
True if first iteration.
loop.last
True if last iteration.
loop.length
The number of items in the sequence.
loop.cycle
A helper function to cycle between a list of sequences. See the explanation below.
loop.depth
Indicates how deep in a recursive loop the rendering currently is. Starts at level 1
loop.depth0
Indicates how deep in a recursive loop the rendering currently is. Starts at level 0
loop.previtem
The item from the previous iteration of the loop. Undefined during the first iteration.
loop.nextitem
The item from the following iteration of the loop. Undefined during the last iteration.
loop.changed(*val)
True if previously called with a different value (or not called at all).
Within a for-loop, it’s possible to cycle among a list of strings/variables each time through the loop by using the special loop.cycle helper:
{% for row in rows %}
<li class="{{ loop.cycle('odd', 'even') }}">{{ row }}</li>
{% endfor %}
Since Jinja 2.1, an extra cycle helper exists that allows loop-unbound cycling. For more information, have a look at the List of Global Functions.
Unlike in Python, it’s not possible to break or continue in a loop. You can, however, filter the sequence during iteration, which allows you to skip items. The following example skips all the users which are hidden:
{% for user in users if not user.hidden %}
<li>{{ user.username|e }}</li>
{% endfor %}
The advantage is that the special loop variable will count correctly; thus not counting the users not iterated over.
If no iteration took place because the sequence was empty or the filtering removed all the items from the sequence, you can render a default block by using else:
<ul>
{% for user in users %}
<li>{{ user.username|e }}</li>
{% else %}
<li><em>no users found</em></li>
{% endfor %}
</ul>
Note that, in Python, else blocks are executed whenever the corresponding loop did not break. Since Jinja loops cannot break anyway, a slightly different behavior of the else keyword was chosen.
It is also possible to use loops recursively. This is useful if you are dealing with recursive data such as sitemaps or RDFa. To use loops recursively, you basically have to add the recursive modifier to the loop definition and call the loop variable with the new iterable where you want to recurse.
The following example implements a sitemap with recursive loops:
<ul class="sitemap">
{%- for item in sitemap recursive %}
<li><a href="{{ item.href|e }}">{{ item.title }}</a>
{%- if item.children -%}
<ul class="submenu">{{ loop(item.children) }}</ul>
{%- endif %}</li>
{%- endfor %}
</ul>
The loop variable always refers to the closest (innermost) loop. If we have more than one level of loops, we can rebind the variable loop by writing {% set outer_loop = loop %} after the loop that we want to use recursively. Then, we can call it using {{ outer_loop(…) }}
Please note that assignments in loops will be cleared at the end of the iteration and cannot outlive the loop scope. Older versions of Jinja had a bug where in some circumstances it appeared that assignments would work. This is not supported. See Assignments for more information about how to deal with this.
If all you want to do is check whether some value has changed since the last iteration or will change in the next iteration, you can use previtem and nextitem:
{% for value in values %}
{% if loop.previtem is defined and value > loop.previtem %}
The value just increased!
{% endif %}
{{ value }}
{% if loop.nextitem is defined and loop.nextitem > value %}
The value will increase even more!
{% endif %}
{% endfor %}
If you only care whether the value changed at all, using changed is even easier:
{% for entry in entries %}
{% if loop.changed(entry.category) %}
<h2>{{ entry.category }}</h2>
{% endif %}
<p>{{ entry.message }}</p>
{% endfor %}
If
The if statement in Jinja is comparable with the Python if statement. In the simplest form, you can use it to test if a variable is defined, not empty and not false:
{% if users %}
<ul>
{% for user in users %}
<li>{{ user.username|e }}</li>
{% endfor %}
</ul>
{% endif %}
For multiple branches, elif and else can be used like in Python. You can use more complex Expressions there, too:
{% if kenny.sick %}
Kenny is sick.
{% elif kenny.dead %}
You killed Kenny! You bastard!!!
{% else %}
Kenny looks okay --- so far
{% endif %}
If can also be used as an inline expression and for loop filtering.
Macros
Macros are comparable with functions in regular programming languages. They are useful to put often used idioms into reusable functions to not repeat yourself (“DRY”).
Here’s a small example of a macro that renders a form element:
{% macro input(name, value='', type='text', size=20) -%}
<input type="{{ type }}" name="{{ name }}" value="{{
value|e }}" size="{{ size }}">
{%- endmacro %}
The macro can then be called like a function in the namespace:
<p>{{ input('username') }}</p>
<p>{{ input('password', type='password') }}</p>
## Flask, API in Ajax vaje(pyton del)
```python
#1.vaja
import requests
import random
for i in range(1, 100):
url = "http://numbersapi.com/"
list = ["trivia", "math", "year"]
category = random.choice(list)
response = requests.get(url + str(i) + "/" + category)
print(response.text, category)
import requests
#2. vaja
apiKey = "894face34d965f1d5d7ca04e919831f6"
mesta = [
["Tokyo", 35.6895, 139.6917],
["New York City", 40.7128, -74.0060],
["Shanghai", 31.2304, 121.4737],
["Sao Paulo", -23.5505, -46.6333],
["Mumbai", 19.0760, 72.8777],
["Delhi", 28.7041, 77.1025],
["Istanbul", 41.0082, 28.9784],
["Lahore", 31.5497, 74.3436],
["Kinshasa", -4.4419, 15.2663],
["Lima", -12.0464, -77.0428],
["London", 51.5099, -0.1180]
]
#3.vaja
def getCityTemp(lat, lon):
payload = {
"lat": lat,
"lon": lon,
"units": "metric",
"appid": apiKey
}
baseUrl = "https://api.openweathermap.org/data/2.5/weather"
response = requests.get(baseUrl, params=payload)
return response.json()
city_info = mesta[0] #
temperature_data = getCityTemp(city_info[1], city_info[2])
print("Temperature in", city_info[0], "is", temperature_data, "°C")
#4.vaja
url = f"https://api.openweathermap.org/data/2.5/weather?lat=44.34&lon=10.99&appid={apiKey}"
podatk = requests.get(url).json()
print(podatk)
#5.vaja
import requests
import json
url1 = "https://api.sunrise-sunset.org/json"
apiKey = "a4c5034cab2c57ee47bc26b0015e312b4d6fe3639f"
payload = {
"lat": 46.2767,
"lng": 13.8846
}
da = requests.get(url1, params=payload).json()
print(da["results"]["sunrise"], da["results"]["sunset"])
url2 = 'https://www.smsapi.si/poslji-sms'
data = {
'un': 'jdjajda_kajkdja',
'ps': apiKey,
'from': '031480333',
'to': '070137300',
'm': "Kys Samo Meze vemo kje zivis - LP Jure ta mau Mencinger",
'cc': '386'
}
response = requests.post(url2, data=data)
print(response.text)
#6.vaja
import requests
import json
url = "https://pokeapi.co/api/v2/pokemon/"
pokemon = input("Vnesi ime pokemona: ")
response = requests.get(url + pokemon)
pokemonData = response.json()
print(pokemonData["name"])
print(pokemonData["id"])
print(pokemonData["height"])
print(pokemonData["weight"])
print(pokemonData["types"][0]["type"]["name"])
#7.vaja
import requests
url = "https://www.boredapi.com/api/activity/"
response = requests.get(url)
activityData = response.json()
print(activityData["activity"],"\n",activityData["type"],"\n",activityData["participants"])
#8.vaja
import requests
import json
url = "https://trefle.io/api/v1/species/search?q=random&limit=3"
apiKey = "ege-92ukLlKssCHpfMZE4bKS0IYgr3HE9jmmkjLBzso"
response = requests.get(url, headers={"Authorization": apiKey})
data = response.json()
for item in data["data"]:
print(item["common_name"])
print(item["slug"])
print(item["scientific_name"])
#9.vaja
import requests
from geopy.distance import geodesic
# Get the real-time location of the ISS
iss_response = requests.get("http://api.open-notify.org/iss-now.json")
iss_data = iss_response.json()
iss_location = (iss_data['iss_position']['latitude'], iss_data['iss_position']['longitude'])
print("Current ISS Location: Latitude {}, Longitude {}".format(iss_location[0], iss_location[1]))
# Input your current location (latitude and longitude)
your_location = (40.7128, -74.0060) # Example coordinates for New York City
# Calculate the distance between your location and the ISS location
distance = geodesic(your_location, (float(iss_location[0]), float(iss_location[1]))).kilometers
print("Distance between your location and ISS: {:.2f} kilometers".format(distance))
#10.vaja
from flask import Flask, render_template
from dominantcolors import get_image_dominant_colors
import urllib.request
import requests
app = Flask(__name__)
url = "https://www.themealdb.com/api/json/v1/1/random.php"
@app.route('/')
def index():
data = requests.get(url).json()
instr = data["meals"][0]["strInstructions"]
name = data["meals"][0]["strMeal"]
img = data["meals"][0]["strMealThumb"]
urllib.request.urlretrieve(img, "slike/slika.jpg")
dominant = get_image_dominant_colors(image_path="slike/slika.jpg", num_colors=2)
dominant_rgb = ["rgb({},{},{})".format(*color) for color in dominant]
return render_template('index.html', instructions=instr, food=name, img=img, dominant_colors=dominant_rgb)
if __name__ == '__main__':
app.run(host='0.0.0.0', port=8080, debug=True)
#11.vaja
from flask import Flask, render_template, request
import requests
app = Flask(__name__)
apiKey = "ced5379744b7b05a15095129ec656de4"
url1 = "https://api.agify.io?name="
url2 = "https://api.genderize.io?name="
url3 = "https://api.nationalize.io?name="
@app.route('/')
def main():
return render_template('names.html')
@app.route('/names', methods=['GET'])
def getData():
name = request.args.get('name')
age = requests.get(url1 + name).json()["age"]
gender = requests.get(url2 + name).json()["gender"]
nationality = requests.get(url3 + name).json()["country"][0]["country_id"]
return render_template('namesdata.html', age = age, gender = gender, nationality = nationality, name = name)
app.run(host='0.0.0.0', port=8080, debug=True)
#12.vaja
from flask import Flask, render_template, request
import requests
app = Flask(__name__)
apiKey = "420418a53eddccdb12a5e8ddc6405dfc"
geoUrl = "http://ipwho.is/"
@app.route('/')
def index():
user_ip = request.remote_addr
user_ip = "185.60.216.35" #Samo zato ker je moj IP address private
lat = requests.get(geoUrl + user_ip).json()['latitude']
lon = requests.get(geoUrl + user_ip).json()['longitude']
Weather = requests.get(f"https://api.openweathermap.org/data/2.5/weather?lat={lat}&lon={lon}&appid={apiKey}").json()['weather'][0]['main']
return render_template("Ip_Address.html", IP = user_ip, lat = lat, lon = lon, Weather = Weather)
app.run(host='0.0.0.0', port=8080, debug=True)
#13.vaja
from flask import Flask, request
from flask.json import jsonify
import requests
import random
app = Flask(__name__)
@app.route('/coinFlip')
def coinFlip():
list = ["Heads", "Tails"]
coin = random.choice(list)
if coin == "Tails":
img = "https://i.postimg.cc/zysdXN8w/tail.png"
return jsonify({"status" : coin, "img": img})
else:
img = "https://i.postimg.cc/CBNJNfDJ/head.png"
return jsonify({"status" : coin, "img": img})
@app.route('/randomQuote')
def randomQuote():
url = "https://api.quotable.io/random"
quote = requests.get(url).json()["content"]
author = requests.get(url).json()["author"]
return jsonify({"author": author, "quote" : quote})
@app.route("/minMax/<int:min>/<int:max>")
def min_max(min, max):
return jsonify({"min": min, "max": max, "random num": random.randint(min, max)})
@app.route('/password/<int:length>')
def generatePassword(length):
password = ""
for i in range(length):
password += random.choice("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890!@#$%^&*()")
return jsonify({"password": password, "num of chars": length})
@app.route('/randDice/<int:strani>/<int:meti>')
def randomDice(strani, meti):
list = []
for i in range(meti):
list.append(random.randint(1, strani))
return jsonify({"throws": list, "sum": sum(list)})
app.run(host='0.0.0.0', port=8080, debug=True)
#14.vaja
from flask import Flask, request, render_template
from flask.json import jsonify
import requests
import random
app = Flask(__name__)
@app.route('/')
def main():
return render_template("vaje.html")
@app.route('/coinFlip')
def coinFlip():
list = ["Heads", "Tails"]
coin = random.choice(list)
if coin == "Tails":
img = "https://i.postimg.cc/zysdXN8w/tail.png"
return render_template("coinFlip.html", coin = coin, img = img)
else:
img = "https://i.postimg.cc/CBNJNfDJ/head.png"
return render_template("coinFlip.html", coin = coin, img = img)
@app.route('/randomQuote')
def randomQuote():
url = "https://api.quotable.io/random"
quote = requests.get(url).json()["content"]
author = requests.get(url).json()["author"]
return render_template("randomQuote.html", author = author, quote = quote)
@app.route("/minMax", methods=['GET'])
def min_max():
min = int(request.args.get('minNum'))
max = int(request.args.get('maxNum'))
return render_template(
"minMax.html", min = min, max = max, randNum= random.randint(min, max))
@app.route('/password', methods=['GET'])
def generatePassword():
length = int(request.args.get('length'))
password = ""
for i in range(length):
password += random.choice("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890!@#$%^&*()")
return render_template(
"password.html", password = password, length = length)
@app.route('/randDice', methods=['GET'])
def randomDice():
strani = int(request.args.get('sides'))
meti = int(request.args.get('throws'))
list = []
for i in range(meti):
list.append(random.randint(1, strani))
return render_template(
"randDice.html", meti = list, stevilo = sum(list))
app.run(host='0.0.0.0', port=8080, debug=True)
#15.vaja
from flask import Flask, render_template, request
import requests
app = Flask(__name__)
url = "https://api.imgflip.com/get_memes"
@app.route('/')
def main():
memes = []
for i in range(1, 100):
meme_name = requests.get(url).json()["data"]["memes"][i]["name"]
memes.append(meme_name)
return render_template('meme.html', meme = memes)
@app.route('/meme', methods=['GET'])
def getMeme():
ime = request.form.get('meme')
template = request.args.get('meme')
return template, ime
app.run(host='0.0.0.0', port=8080, debug=True)
#16.vaja
from flask import Flask, render_template, request, jsonify
import requests
app = Flask(__name__)
api_key = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpYXQiOjE3MTE0NDcxMTYsInVzZXJfaWQiOiI2NjAyOWM0OWI2ZDJjN2E0NDZiMDBjZWEifQ.KoyPXXXGfD201kDr8WWQvse3ZWOtOIThh11fiUUOUAY" # Replace 'YOUR_API_KEY' with your actual API key
@app.route('/')
def main():
return render_template('stable.html')
@app.route('/generate_image', methods=['POST'])
def generate_image():
text = request.form['text']
headers = {'Authorization': f'Bearer {api_key}'}
payload = {'text': text}
response = requests.post('https://api.wizmodel.com/text-to-image', json=payload, headers=headers)
if response.status_code == 200:
image_url = response.json()['url']
return jsonify({'image_url': image_url})
if __name__ == '__main__':
app.run(host='0.0.0.0', port=8080, debug=True)
#17.vaja
from flask import Flask, render_template, request, jsonify
import requests
from tinydb import TinyDB, Query
db = TinyDB('db.json')
app = Flask(__name__)
@app.route('/')
def main():
shrani = db.all()
return render_template('chat.html', shrani = shrani)
@app.route('/chat', methods=['POST'])
def chat():
text = request.form['text']
db.insert({'text': text})
return text
app.run(host='0.0.0.0', port=8080, debug=True)
#18.vaja
from flask import Flask, render_template, request, jsonify
import requests
import random
url = "http://www.randomnumberapi.com/api/v1.0/random?min=100&max=1000&count=1"
app = Flask(__name__)
@app.route('/')
def main():
return render_template('randomNum.html')
@app.route('/randomNum')
def randNum():
num = requests.get(url).json()[0]
return jsonify(num)
app.run(host='0.0.0.0', port=8080, debug=True)
#19.vaja
from flask import Flask, render_template, request, jsonify
import requests
import random
apiKey = "420418a53eddccdb12a5e8ddc6405dfc"
geoKey = "8293e44bf6d345e1b650444ba1a0f18f"
app = Flask(__name__)
@app.route('/')
def main():
return render_template('weatheCity.html')
@app.route('/weather', methods=['POST'])
def weather():
city = request.args.get('text')
url2 = f"https://api.opencagedata.com/geocode/v1/json?q={city}&key={geoKey}"
lat = requests.get(url2).json()['results'][0]['geometry']['lat']
lon = requests.get(url2).json()['results'][0]['geometry']['lng']
Weather = requests.get(f"https://api.openweathermap.org/data/2.5/weather?lat={lat}&lon={lon}&appid={apiKey}").json()['weather'][0]['main']
return Weather
app.run(host='0.0.0.0', port=8080, debug=True)
#20.vaja
from flask import Flask, render_template, request, jsonify
import requests
import random
app = Flask(
__name__)
@app.route('/')
def main():
return render_template('hello.html')
@app.route('/helloWorld', methods=['GET'])
def hello():
izpis = "Hello World"
return izpis
app.run(host='0.0.0.0', port=8080, debug=True)
#21.vaja
from flask import Flask, render_template, request, jsonify
import requests
apiKey = "420418a53eddccdb12a5e8ddc6405dfc"
app = Flask(
__name__)
@app.route('/')
def main():
return render_template('weather.html')
@app.route('/getWeather', methods=['GET'])
def getWeather():
lat = request.args.get('lat')
lon = request.args.get('lon')
url = requests.get(f"https://api.openweathermap.org/data/2.5/weather?lat={lat}&lon={lon}&appid={apiKey}").json()['weather'][0]['description']
return jsonify({'samo': url})
app.run(host='0.0.0.0', port=8080, debug=True)
#22.vaja
from flask import Flask, render_template, request, jsonify
import requests
max, min, middle = 0, 0, 0
app = Flask(
__name__)
@app.route('/')
def main():
return render_template('stevec.html')
@app.route('/stevec', methods=['GET'])
def stevec():
stev1 = int(request.args.get('st1'))
stev2 = int(request.args.get('st2'))
stev3 = int(request.args.get('st3'))
if(stev1 > stev2 and stev1 > stev3):
max = stev1
if(stev2 > stev1 and stev2 > stev3):
max = stev2
if(stev3 > stev1 and stev3 > stev2):
max = stev3
if(stev1 < stev2 and stev1 < stev3):
min = stev1
if(stev2 < stev1 and stev2 < stev3):
min = stev2
if(stev3 < stev1 and stev3 < stev2):
min = stev3
if(stev1 > stev2 and stev1 < stev3 or stev1 > stev3 and stev1 < stev2):
middle = stev1
if(stev2 > stev1 and stev2 < stev3 or stev2 < stev1 and stev2 > stev3):
middle = stev2
if(stev3 > stev1 and stev3 < stev2 or stev3 < stev1 and stev3 > stev2):
middle = stev3
return jsonify(
{'max': max, 'min': min, 'middle': middle})
app.run(host='0.0.0.0', port=8080, debug=True)
#23.vaja
from flask import Flask, render_template, request, jsonify
conversion_rates = {
'USD': 1.18, # 1 Euro = 1.18 US Dollar
'GBP': 0.86, # 1 Euro = 0.86 British Pound Sterling
'JPY': 130.68, # 1 Euro = 130.68 Japanese Yen
'AUD': 1.56, # 1 Euro = 1.56 Australian Dollar
'CAD': 1.48 # 1 Euro = 1.48 Canadian Dollar
}
app = Flask(__name__)
@app.route('/')
def main():
return render_template('currency.html', currencies=conversion_rates.keys())
@app.route('/conversion', methods=['POST'])
def conversion():
currency = request.form.get('currency')
amount = float(request.form.get('amount'))
converted_amount = amount * conversion_rates[currency]
return jsonify({'converted_amount': converted_amount})
if __name__ == '__main__':
app.run(host='0.0.0.0', port=8080, debug=True)
#24.vaja
from flask import Flask, render_template, request, jsonify
from tinydb import TinyDB
db = TinyDB('db.json')
db.truncate()
app = Flask(__name__)
@app.route('/')
def main():
return render_template('primerjevalc.html')
@app.route('/primerjeval', methods=['GET'])
def primerjeval():
db.insert({'number': request.args.get('stev')})
print(db.all())
return ""
@app.route('/posiljatelj', methods=['POST'])
def poslji():
numbers = [int(entry['number']) for entry in db.all()]
if len(numbers) >= 3:
max_number = max(numbers)
min_number = min(numbers)
sorted_numbers = sorted(numbers)
middle_number = sorted_numbers[1]
return jsonify({
'max': max_number,
'min': min_number,
'middle': middle_number
})
if __name__ == '__main__':
app.run(host='0.0.0.0', port=8080, debug=True)
```
## Flask, API in Ajax vaje(html del)
```html
#10.vaja
index.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>Recipe</title>
<style type="text/css">
body{
background-color: {{ dominant_colors[0] }};
margin: 0 auto;
}
h1 {
font-family: sans-serif;
font-size: 2em;
color: Rgb(200, 100 , 50);
}
</style>
</head>
<body>
<h1>{{ food }}</h1>
<ul>
<li>{{ instructions }}</li>
<li><img src="{{ img }}" alt="Slika"></li>
</ul>
</body>
</html>
#11.vaja
names.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>names</title>
</head>
<body>
<form action="/names" method="GET">
<input type="text" name='name'>
<input type="submit" value="Submit">
</form>
</body>
</html>
namesdata.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>Podatki o imenu</title>
</head>
<body>
<h1>Welcome {{ name }}</h1>
<p>age is: {{ age }} </p>
<p>gender is : {{ gender }}</p>
<p>nationality is : {{ nationality }}</p>
</body>
</html>
#12.vaja
Ip_Address.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>Ip</title>
</head>
<body>
<h1>Your IP address is {{ IP }}</h1>
Your latitude is {{ lat }}<br>
Your longitude is {{ lon }}<br>
The Weather in your region is {{ Weather }}
</body>
</html>
#14.vaja
vaja.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>Vaje</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
<h1>Skupek vseh vaj</h1>
<h2>Coin Flip</h2>
<form action="/coinFlip" method="GET">
<input type="submit" value="Flip Coins">
</form>
<h2>Random quote</h2>
<form action="/randomQuote" method="GET">
<input type="submit" value="Get a Quote">
</form>
<h2>Min Max</h2>
<form id="MinMax" action="/minMax">
<label for="minNum">Min number:</label>
<input type="number" id="minNum" name="minNum" min="1" value="0">
<br>
<label for="maxNum">Max number:</label>
<input type="number" id="maxNum" name="maxNum" min="1" value="0">
<br><br>
<input type="submit" value="Get a random number">
</form>
<h2>Generate Password</h2>
<form id="Password" action="/password">
<label for="password">type length of password:</label>
<input type="number" id="length" name="length" min="1" value="0"><br><br>
<input type="submit" value="Generate a password">
</form>
<h2>Random Dice</h2>
<form id="randDice" action="/randDice">
<label for="sides">Number of sides:</label>
<input type="number" id="sides" name="sides" min="1" value="0">
<br>
<label for="throws">Number of throws:</label>
<input type="number" id="throws" name="throws" min="1" value="0">
<br><br>
<input type="submit" value="Throw Dice">
</form>
<script><script>
$(document).ready(function() {
$('#MinMax').submit(function(event) {
event.preventDefault();
var formData = $(this).serialize();
$.ajax({
type: 'GET',
url: '/minMax',
data: formData,
success: function(response) {
console.log(response);
},
error: function(xhr, status, error) {
console.error(error);
}
});
});
});
$(document).ready(function() {
$('#Password').submit(function(event) {
event.preventDefault();
var formData = $(this).serialize();
$.ajax({
type: 'GET',
url: '/password',
data: formData,
success: function(response) {
console.log(response);
},
error: function(xhr, status, error) {
console.error(error);
}
});
});
});
$(document).ready(function() {
$('#randDice').submit(function(event) {
event.preventDefault();
var formData = $(this).serialize();
$.ajax({
type: 'GET',
url: '/randDice',
data: formData,
success: function(response) {
console.log(response);
},
error: function(xhr, status, error) {
console.error(error);
}
});
});
});
</script>
</script>
</body>
</html>
coinFlip.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>Your coin is {{ coin }}</h1><br>
<img src="{{img}}" alt="slika"><br>
<form action="/" method="GET">
<input type="submit" value="Return">
</form>
</body>
</html>
randomQoute.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>Random Quote</title>
</head>
<body>
<h1>Random Quote</h1>
<p>{{ author }}</p>
<p>{{ quote }}</p>
<form action="/" method="GET">
<input type="submit" value="Return">
</form>
</body>
</html>
minMax.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>Min and Max</title>
</head>
<body>
<h1>Min is {{min}} and Max is {{ max }}</h1>
<p>Random number in between is {{ randNum }}</p>
<form action="/" method="GET">
<input type="submit" value="Return">
</form>
</body>
</html>
password.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>Password</title>
</head>
<body>
<h1>Generated password</h1>
<p>Length of password is {{length}}</p>
<p>Password is {{password}}</p>
<form action="/" method="GET">
<input type="submit" value="Return">
</form>
</body>
</html>
randDice.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>RandDice</title>
</head>
<body>
<h1>Random Dice</h1>
<p>Throws are {{meti}}</p>
<p>sum is {{stevilo}}</p>
</body>
</html>
#15.vaja
meme.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>Meme Vaja</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<body>
{{ ime }}
<form id="getMeme" type="GET">
<input name="meme" id="meme" type="text">
</form>
<select id="memeList">
{% for item in meme %}
<option value={{ item }}>{{ item }}</option>
{% endfor %}
</select>
<button id="button" type="button" onclick="refreshData()">Refresh</button>
<script>
function refreshData() {
location.reload();
}
$(document).ready(function() {
$('#getMeme').submit(function(event) {
event.preventDefault();
var memeValue = $('#meme').val();
$.ajax({
type: 'GET',
url: '/meme',
data: { meme: memeValue },
success: function(response) {
console.log(response);
$('#memeList').html(response);
},
error: function(xhr, status, error) {
console.error(xhr, status, error);
}
});
});
});
</script>
</body>
</html>
#16.vaja
stable.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>Stable</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<body>
<h1>Stable</h1>
<form id="inputForm">
<label for="textInput">Enter Text:</label>
<input type="text" id="textInput" name="text">
<input type="submit" value="Submit">
</form>
<div id="result"></div>
<script>
$(document).ready(function() {
$('#inputForm').submit(function(event) {
event.preventDefault();
var text = $('#textInput').val();
$.ajax({
type: 'POST',
url: '/generate_image',
data: { text: text },
success: function(response) {
$('#result').html(`<img src="${response.image_url}" alt="Generated Image">`);
},
error: function(xhr, status, error) {
console.error(error);
$('#result').html('<p>Error occurred while generating image</p>');
}
});
});
});
</script>
</body>
</html>
#17.vaja
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Textarea Example</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<body>
<h1>Textarea Example</h1>
<form id="textForm" action="/chat" method="POST">
<label for="textInput">Enter Text:</label><br>
<textarea id="textInput" name="textarea" rows="4" cols="50">{%for i in shrani%}{{ i }}{%endfor%}</textarea><br><br>
<input type="text" id="text" name="text">
<button type="submit">Submit</button>
</form>
<script>
$(document).ready(function() {
$('#textForm').submit(function(event) {
event.preventDefault();
var formData = $(this).serialize();
$.ajax({
type: 'POST',
url: '/chat',
data: formData,
success: function(response) {
$('#textInput').val(response.updatedText);
},
error: function(xhr, status, error) {
console.error(error);
}
});
});
});
</script>
</body>
</html>
#18.vaja
randomNum.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>RandomNum generator</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<body>
<p>Random number is <span id="randomNum"></span></p>
<button type="button" id="button">Get random Number</button>
<script>
$(document).ready(function() {
$('#button').click(function() {
$.ajax({
type: 'GET',
url: '/randomNum',
success: function(response) {
$('#randomNum').text(response);
},
}
});
});
});
</script>
</body>
</html>
#19.vaja
weatheCity.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Weather App</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="script.js"></script>
</head>
<body>
<span id="weather"></span>
<h1>Weather App</h1>
<form id="weatherForm">
<label for="cityInput">Enter City:</label>
<input type="text" id="cityInput" name="city">
<button id="button" type="button">Get Weather</button>
</form>
<div id="weatherInfo"></div>
<script>
$(document).ready(function() {
$('#button').click(function() { // Change to click event handler for the button
$.ajax({
type: 'POST',
url: '/weather',
data: { city: $('#cityInput').val() },
success: function(response) {
$('#weatherInfo').text('Weather: ' + response);
},
error: function(xhr, status, error) {
console.error('Error fetching weather data:', error);
$('#weatherInfo').text('Error fetching weather data');
}
});
});
});
</script>
</body>
</html>
#20.vaja
hello.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>Hello world</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="script.js"></script>
</head>
<body>
<span id="helloWorld"></span><br>
<button type="button" id="button" onclick="helloWorld()">Press ME!!!!</button>
<script>
function helloWorld() {
}
$(document).ready(function() {
$('#button').click(function() {
$.ajax({
type: 'GET',
url: '/helloWorld',
success: function(response) {
$('#helloWorld').text(response);
}
})
});
});
</script>
</body>
</html>
#21.vaja
<!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>Weather</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
<div id="weather"></div>
<form type="POST" id="weatherForm">
<input type="text" name="lon" id="lon" placeholder="Longitude">
<input type="text" name="lat" id="lat" placeholder="Latitude">
<input type="submit" value="send">
</form>
<script>
$(document).ready(function() {
$('#weatherForm').submit(function(event) {
event.preventDefault();
var formData = $(this).serialize();
$.ajax({
type: 'GET',
url: '/getWeather',
data: formData,
success: function(response) {
$('#weather').html(response.samo);
}
});
});
});
</script>
</body>
</html>
#22.vaja
stevec.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>Stevec</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
<div id="numbers"></div>
<form id="stevec" method="POST">
<input type="text" name="st1" id="st1" placeholder="Vnesi stevilo">
<input type="text" name="st2" id="st2" placeholder="Vnesi stevilo">
<input type="text" name="st3" id="st3" placeholder="Vnesi stevilo">
<input type="submit" value="Stevec">
</form>
<script>
$(document).ready(function() {
$('#stevec').submit(function(event) {
event.preventDefault();
let formData = $(this).serialize();
$.ajax({
type: 'GET',
url: '/stevec',
data: formData,
success: function(response) {
$('#numbers').html('Min: ' + response.min + ', ' + 'Middle: ' + response.middle + ', ' + 'Max: ' + response.max);
}
});
});
});
</script>
</body>
</html>
#23.vaja
curreny.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>Currency Converter</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
<form id="currencyForm">
<input type="number" name="amount" id="amount" placeholder="Enter amount">
<select id="currencySelect">
{% for currency in currencies %}
<option>{{ currency }}</option>
{% endfor %}
</select>
<input type="submit" value="Convert">
</form>
<div id="result"></div>
<script>
$(document).ready(function() {
$('#currencyForm').submit(function(event) {
event.preventDefault();
var amount = $('#amount').val();
var currency = $('#currencySelect').val();
$.ajax({
type: 'POST',
url: '/conversion',
data: {
amount: amount,
currency: currency
},
success: function(response) {
$('#result').text('Converted amount: ' + response.converted_amount);
}
});
});
});
</script>
</body>
</html>
#24.vaja
primerjevalc.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>Primerjevalc</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
<form id="stevila" method="GET">
<input type="text" name="stev" id="stev" placeholder="Vnesi stevilo">
<input type="submit" value="submit">
</form>
<button type="button" id="button" onclick="dobiStevila()">Dobi stevila</button>
<div id="enteredValues"></div>
<script>
function dobiStevila() {
$.ajax({
type: 'POST',
url: '/poslji',
success: function(response) {
console.log(response);
if (response.hasOwnProperty('error')) {
console.log(response.error);
} else {
console.log('Max: ' + response.max);
console.log('Min: ' + response.min);
console.log('Middle: ' + response.middle);
}
}
});
}
$(document).ready(function() {
$('#stevila').submit(function(event) {
event.preventDefault();
let formData = $(this).serialize();
$.ajax({
type: 'GET',
url: '/primerjeval',
data: formData,
success: function(response) {
console.log('Vneseno stevilo: ' + response);
$('#enteredValues').text('Vneseno stevilo: ' + response);
}
});
});
});
</script>
</body>
</html>
```
# TINY DB INFO
TinyDB is a lightweight, document-oriented database written in Python. It's easy to set up and use, making it suitable for small projects and prototypes. Below are the steps to install and use TinyDB, along with some basic functions:
Installation: You can install TinyDB using pip, Python's package manager.
bash
Copy code
pip install tinydb
Importing TinyDB: Once installed, you can import TinyDB into your Python code.
python
Copy code
from tinydb import TinyDB, Query
Creating a Database: You can create a TinyDB database by providing a file path. If the file doesn't exist, TinyDB will create it for you.
python
Copy code
db = TinyDB('db.json')
Inserting Data: You can insert data into the database using the insert method.
python
Copy code
db.insert({'name': 'John', 'age': 30})
db.insert({'name': 'Alice', 'age': 25})
Querying Data: You can query data from the database using TinyDB's querying syntax.
python
Copy code
User = Query()
result = db.search(User.name == 'John')
print(result)
Updating Data: You can update data in the database using the update method.
python
Copy code
db.update({'age': 35}, User.name == 'John')
Removing Data: You can remove data from the database using the remove method.
python
Copy code
db.remove(User.name == 'Alice')
Closing the Database: It's good practice to close the database when you're done using it.
python
Copy code
db.close()
Here's a simple example of using TinyDB:
python
Copy code
from tinydb import TinyDB, Query
# Creating a database
db = TinyDB('db.json')
# Inserting data
db.insert({'name': 'John', 'age': 30})
db.insert({'name': 'Alice', 'age': 25})
# Querying data
User = Query()
result = db.search(User.name == 'John')
print(result)
# Updating data
db.update({'age': 35}, User.name == 'John')
# Removing data
db.remove(User.name == 'Alice')
# Closing the database
db.close()
This is just a basic overview of TinyDB. It's a versatile library, and you can explore more advanced features like table operations, atomic updates, and transactions in the TinyDB documentation.
User
give me everything there is to know about tiny db
ChatGPT
TinyDB is a lightweight, document-oriented database written in Python. It provides a simple and easy-to-use interface for storing and querying JSON-like documents. Here's everything you need to know about TinyDB:
1. Features:
Lightweight: TinyDB is designed to be lightweight and easy to use.
No external dependencies: It doesn't rely on any external database engines or libraries.
Document-oriented: Data is stored as JSON documents, making it easy to work with semi-structured data.
Querying: Provides a simple querying syntax for retrieving data from the database.
Modular: Allows you to extend its functionality through plugins.
Transactions: Supports transactions to ensure data integrity.
Thread-safe: Provides thread-safe access to the database.
2. Installation:
You can install TinyDB using pip, Python's package manager:
bash
Copy code
pip install tinydb
3. Basic Usage:
3.1. Creating a Database:
You can create a TinyDB database by providing a file path. If the file doesn't exist, TinyDB will create it for you.
python
Copy code
from tinydb import TinyDB
db = TinyDB('db.json')
3.2. Inserting Data:
You can insert data into the database using the insert method.
python
Copy code
db.insert({'name': 'John', 'age': 30})
db.insert({'name': 'Alice', 'age': 25})
3.3. Querying Data:
You can query data from the database using TinyDB's querying syntax.
python
Copy code
from tinydb import Query
User = Query()
result = db.search(User.name == 'John')
print(result)
3.4. Updating Data:
You can update data in the database using the update method.
python
Copy code
db.update({'age': 35}, User.name == 'John')
3.5. Removing Data:
You can remove data from the database using the remove method.
python
Copy code
db.remove(User.name == 'Alice')
3.6. Closing the Database:
It's good practice to close the database when you're done using it.
python
Copy code
db.close()
4. Advanced Usage:
4.1. Table Operations:
TinyDB supports table operations like creating, dropping, and renaming tables.
4.2. Atomic Updates:
TinyDB provides atomic updates, ensuring that data modifications are consistent and isolated.
4.3. Transactions:
Transactions allow you to perform multiple operations on the database as a single unit of work, ensuring data integrity.
4.4. Plugins:
TinyDB is extensible through plugins, allowing you to add custom functionality to the database.
5. Documentation:
You can find more information and detailed documentation on TinyDB's official website: TinyDB Documentation
TinyDB is a great choice for small to medium-sized projects where simplicity and ease of use are priorities. It's particularly well-suited for prototyping, testing, and projects with lightweight data storage requirements.
User
you gave less informatino than before
ChatGPT
Apologies for the oversight. Let's delve deeper into TinyDB:
1. Introduction:
TinyDB is a lightweight, file-based database written in pure Python. It is designed for simplicity and ease of use, making it an excellent choice for small to medium-sized projects where you need a quick and efficient way to store and query data.
2. Features:
Document-Oriented: TinyDB stores data in JSON-like documents, making it easy to work with semi-structured data.
No Dependencies: TinyDB does not rely on any external dependencies, making it easy to install and use in any Python environment.
Simple API: TinyDB provides a simple and intuitive API for interacting with the database, including inserting, querying, updating, and deleting data.
Querying: It supports querying data using a simple syntax similar to that of MongoDB.
Transactions: TinyDB supports transactions to ensure data integrity, allowing you to perform multiple operations as a single atomic unit of work.
Modular and Extensible: TinyDB is designed to be modular and extensible, allowing you to add custom functionality through plugins.
Thread-Safe: TinyDB provides thread-safe access to the database, allowing multiple threads to interact with the database simultaneously without the risk of data corruption.
3. Installation:
You can install TinyDB using pip, Python's package manager:
bash
Copy code
pip install tinydb
4. Basic Usage:
4.1. Creating a Database:
You can create a TinyDB database by providing a file path. If the file doesn't exist, TinyDB will create it for you.
python
Copy code
from tinydb import TinyDB
db = TinyDB('db.json')
4.2. Inserting Data:
You can insert data into the database using the insert method.
python
Copy code
db.insert({'name': 'John', 'age': 30})
db.insert({'name': 'Alice', 'age': 25})
4.3. Querying Data:
You can query data from the database using TinyDB's querying syntax.
python
Copy code
from tinydb import Query
User = Query()
result = db.search(User.name == 'John')
print(result)
4.4. Updating Data:
You can update data in the database using the update method.
python
Copy code
db.update({'age': 35}, User.name == 'John')
4.5. Removing Data:
You can remove data from the database using the remove method.
python
Copy code
db.remove(User.name == 'Alice')
4.6. Closing the Database:
It's good practice to close the database when you're done using it.
python
Copy code
db.close()
5. Advanced Usage:
TinyDB also supports advanced features such as table operations, transactions, atomic updates, and plugins for extending its functionality.
6. Documentation:
You can find more detailed information and examples in the official TinyDB documentation: TinyDB Documentation
TinyDB is a versatile and easy-to-use database solution for Python developers, suitable for a wide range of applications, from small scripts to larger projects. Its simplicity, flexibility, and performance make it a popular choice among developers.
User
truncate, delete
ChatGPT
In TinyDB, there are methods to remove data from the database, including truncating the entire database or deleting specific records.
1. Truncating the Entire Database:
Truncating the database means removing all the data from it, essentially starting with a clean slate.
python
Copy code
from tinydb import TinyDB
# Create or open the database
db = TinyDB('db.json')
# Truncate the entire database
db.truncate()
# Close the database
db.close()
2. Deleting Specific Records:
If you want to delete specific records from the database based on certain criteria, you can use the remove method along with a query.
python
Copy code
from tinydb import TinyDB, Query
# Create or open the database
db = TinyDB('db.json')
# Define a query for the records you want to delete
User = Query()
query = User.name == 'John' # For example, delete records where the name is 'John'
# Delete records matching the query
db.remove(query)
# Close the database
db.close()
3. Note:
Truncating the database removes all records, effectively resetting the database to an empty state.
Deleting specific records allows you to remove only the records that match certain criteria, leaving other records intact.
Ensure that you use these methods carefully, as they will permanently remove data from the database. Always make sure to have proper backups or confirmations before executing these operations, especially in production environments.