---
# System prepended metadata

title: Spletna stran - ZAPISKI
tags: [UPN, srednja sola]

---

# IMPORTI
```python=
from flask import Flask, request, render_template
from tinydb import TinyDB, Query
import requests, string
```

# DICTIONARY
## delovanje
```python=
import requests
import pprint #pretty print - naredi lepši print dictionaryjev

#dictionary
dict = {"Ime" : "Maša",
       "Starost" : 17,
       "Zaposlen" : False,
       "Siblings" : ["Ančka", "Teja"]
       }

print(dict["Ime"], dict["Siblings"][1], dict["Zaposlen"])
print(dict.get("Ime2", 0)) #če tega imena v dict ni, izpiše dano vrednost(0)
```
![image](https://hackmd.io/_uploads/H1ip-H746.png)

--- 
# API
Validator: https://jsonformatter.curiousconcept.com

## brez parametrov(payload)
```python=
import requests
import pprint

#api key ni nujen
api_key = "api_key"

#namesto api key lahko dodamo katerekoli parametre
base_url = f"base_url?/{api_key}"
call = requests.get(base_url).json()
print(call["name"])
```
---

## z parametri(payload) v seznamu
```python=
import requests
import pprint

api_key = "api_key"

# parametri apija
payload = {"vrednost1" : 13,
           "vrednost2" : "Hello",
           "vrednost3" : ["Jaka", "Janez"],
           "vrednost4" : {ime: "Jaka", "starost": 13}
           "apiKey_name": api_key,
         }

base_url = "base_url"
call = requests.get(base_url, params = payload).json()
print(call["name"])
```
---

## Ustvaritev lastnega apija:
PYTHON:
```python=
from flask import Flask, jsonify
import random

app = Flask('app')

imena = ['Ana', 'Borut', 'Cilka', 'Darko', 'Eva']
priimek = ['Novak', 'Kovač', 'Horvat', 'Krajnc', 'Golob']

@app.route('/randomOseba')
def random_oseba():
  temp_ime = random.choice(imena)
  temp_priimek = random.choice(priimek)
  dict = {"Ime"    : temp_ime,
          "Priimek": temp_priimek,
          "Email"  : f"{temp_ime}.{temp_priimek}@gmail.com".lower()
  }
  
  return jsonify(dict)

app.run(host='0.0.0.0', port=8080,debug=True)
```

---

# Flask
```python=
from flask import Flask, render_template, request

app = Flask('app')

@app.route('/')
def hello_world():
  return render_temlate('index.html')

app.run(host='0.0.0.0', port=8080, debug=True)
```
---

# Ajax
## head html dokumenta z ajaxom
```python
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
```
---

## ajax
```htmlmixed=
<script>
    $.ajax({
          url: "/api",
          data: {
            spremenljivka_ki_jo_pošljemo_python_funkciji: spremenljivka_iz_jave
          },

          success: function( result ) {
            html_id_za_izpis.innerHTML = result.result_api_spremenljivka
          }
    });
</script>
```
---

## ajax s funkcijo
HTML:
```htmlmixed=
<input type="text" id="spremenljivka">
<button onclick="funkcija_ime()">Click</button>
<div id="html_id_za_izpis"></div>

<script>
    console.log("Pozdrav iz skripte") // javascript print
      
    function funkcija_ime() { // refresh funkcija
      var spremenljivka = document.getElementById("spremenljivka").value
      
      $.ajax({
          url: "/api",
          data: {
            spremenljivka_ki_jo_pošljemo_python_funkciji: spremenljivka_iz_html
          },

          success: function( result ) {
            html_id_za_izpis.innerHTML = result.result_api_spremenljivka
          }
    });
    }

    setInterval(refresh, 1000) // osveževanje
  </script>
```
---

### vzemanje spremenljivk iz ajaxa
PYTHON:
```python=
from flask import Flask, render_template, request

app = Flask('app')

@app.route('/api')
def hello_world():
    #naredi nekaj s python spremenljivko
    python_spremenljivka = request.args.get("spremenljivka_ki_jo_pošljemo_python_funkciji", -1)
    return render_temlate('index.html', result_api_spremenljivka = python_spremenljivka)

app.run(host='0.0.0.0', port=8080, debug=True)
```

---

# HTML
## obrazci
```python=
<input type="number" id="number">
<input type="text" id="text">
<input type="textarea" id="text">

<select id="izbira">
    <option value="izbira1">izbira1</option>
    <option value="izbira2">izbira1</option>
    <option value="izbira3">izbira1</option>
</select>
```
---

## jinja for loop
### seznam
```htmlmixed=
{% for s in sez %}
      <li> {{s}} </li>
{% endfor %}
```
---

### primer z oštevilčenim seznamom
```htmlmixed=
<ol>
    {% for p in psi %}
      <tr>
        <li>{{p}}</li>
      </tr>
    {% endfor %}
</ol>
```
---

### select
```htmlmixed=
<select id="izbira">
      {% for st in range(dolzina) %}
           <option value="{{ izbira[st] }}">{{ izbira[st] }}</option>
      {% endfor %}
</select>
```

#### select z dictionaryjem
```htmlmixed=
<select id="izbira">
        {% for posta in postne_st %}
             <option value="{{ postna_st }}">{{ postna_st }}</option>
        {% endfor %}
  </select>
```

#### iz selecta direkno izpiše rez(ne potrebuješ gumba)
```htmlmixed=
<body>
  <select onchange="prikaz()" id="izbira">
        {% for postna_st in postne_st %}
             <option value="{{ postna_st }}">{{ postna_st }}</option>
        {% endfor %}
  </select>

  <div id="izpis"></div>
  <script>
    function prikaz() { // refresh funkcija
      var izbira = document.getElementById("izbira").value

      $.ajax({
          url: "/get_posta",
          data: {
            izbira: izbira
          },

          success: function( result ) {
              izpis.innerHTML = result
          }
    });
    }

  </script>
</body>
```
---

# tinyDB

![image](https://hackmd.io/_uploads/S1QlTxEbR.png)

## osnovno
```python=
from tinydb import TinyDB, Query
db = TinyDB('db.json')
```

---
## dodajanje v db
```python=
db.insert({'type': 'apple', 'count': 7})
```
---

## izpis celotne baze
```python=
db.all()
```

---

## iskanje specifičnih stvari v bazi
```python=
Fruit = Query()
db.search(Fruit.type == 'peach')

#rezultat
[{'count': 3, 'type': 'peach'}]
```
---

## splosno
```python=
from tinydb import TinyDB, Query

# To ustvari (ali odpre, če že obstaja) datoteko db.json, ki služi kot naša baza podatkov.
db = TinyDB('db.json')


# To doda nov zapis v našo bazo. Vsak zapis ima ključe 'username', 'password' in 'note' - v note si shranimo vsebino beležke.
db.insert({'username': 'uporabnik', 'password': 'geslo123', 'note': 'Začetna vrednost beležke? Mogoče pozdravimo uporabnika.. Hey uporabnik!'})


# To poišče vse zapise, kjer je vrednost ključa 'username' enaka 'uporabnik'.
# Lahko bi rekli tudi Query().username == 'uporabnik'.
# Ponavadi si jo poimenujemo zaradi preglednosti, lahko pa jo tudi v napreprej filtriramo
User = Query()  
search_result = db.search(User.username == 'uporabnik')


# To posodobi zapis, ki ustreza pogoju (kjer je 'username' enak 'uporabnik'), in nastavi vrednost 'note' na novo vsebino.
db.update({'note': 'Posodobljena vsebina'}, User.username == 'uporabnik')


# To najde prvi zapis, ki ustreza pogoju, in izpiše vrednost njegove beležke.
user_note = db.search(User.username == 'uporabnik')[0]['note']
```
---

# ROUTI
## pošiljanje na route brez ajaxa
HTML:
```htmlmixed=
<form action="/route_na_katerega_zelimo">
      <label>First name:</label><br>
      <input type="text" name="first_name"><br>
      
      <label>Last name:</label><br>
      <input type="text" name="second_name"><br><br>
      
      <input type="submit" value="Submit">
</form> 
```
---

## vzemanje podatkov:
PYTHON:
```python=
ime = request.args.get("first_name")
```
---

## izbris nečesa iz baze
```python=
db.remove(Username.username == 'a')
```
---

## uporaba/route_ime/< spremenljivka > routov
PYTHON:
Ustvaritev leaderboarda
```python=
@app.route('/save_score/<tocke>/<ime>')
def save_score(tocke, ime):
    
  #doda točke in ime v seznam
  leaderboard.append([int(tocke), ime])
  
  return leaderboard
```
---

# VAJA
### python main.py
```python=
from flask import Flask, render_template, request
from tinydb import TinyDB, Query
import requests

app = Flask('app')

#database
db = TinyDB('db.json')
Username = Query()

@app.route('/')
def index():
  return render_template('index.html')

#SHRANJEVANJE NAJLJUBŠEGA ŠT
@app.route('/shrani_najljubse_stevilo')
def shrani_naj_st():
  username = request.args.get("username", -1)
  naj_st = request.args.get("najljubse_st", 0)
  db.insert({'name': username, 'naj_st': naj_st})
  return render_template('index.html')


#route za pridobivanje dejstva/stevila
@app.route('/stevilo')
def stevilo():
  izbira = ["math", "trivia", "year"]
  dolzina = len(izbira)
  return render_template('stevilo.html', izbira = izbira, dolzina = dolzina)


#PRIDOBIVANJE DEJSTVA
@app.route('/pridobi_dejstvo')
def pridobi_dejstvo():
  username = request.args.get("username", -1)
  info_username = db.search(Username.name == username)
  izbira = request.args.get("izbira", "trivia")
  naj_st = 0
  
  if len(info_username) != 0:
    naj_st = info_username[0]['naj_st']


  base_url = f"http://numbersapi.com/{naj_st}/{izbira}"
  fact = requests.get(base_url).text
  
  return fact


app.run(host='0.0.0.0', port=8080, debug=True)
```

---

### stevilo.html
```htmlmixed=
<!DOCTYPE html>
  <html lang="en">
  <head>
    <meta charset="UTF-8">
    <title>Welcome</title>

    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script> 

  </head>
  <body>
    <h1> Pridobi fact o stevilu najljubšem stevilu </h1>
    Username: <input type="text" id="username"> <br>
    Izberi: 
    <select id="izbira">
      {% for st in range(dolzina) %}
       <option value={{ izbira[st] }}>{{ izbira[st] }}</option>
      {% endfor %}
    </select>
    <br>
    
    <button onclick="prikaz()">Pridobi</button>

    <div id="izpis"></div>

    
    <script>
      function prikaz() {
        console.log("prikaz")
        var username = document.getElementById("username").value;
        var izbira = document.getElementById("izbira").value;

        $.ajax({
          url: "/pridobi_dejstvo",
          data: {
            username : username,
            izbira   : izbira
          },
  
          success: function( result ) {
            izpis.innerHTML = result;
          }
        });
      }
    </script>
  </body>
  </html>
```

---

### index.html
```python=
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Welcome</title>

  <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script> 

</head>
<body>
  <h1> Shrani najljubše število </h1>
  Username: <input type="text" id="username">
  <br>
  Shrani najljubše št: <input type="number" id="najljubse_stevilo">
  <button onclick="shrani()">Shrani</button>
  <br>

  <a href="/stevilo">Želim pridobiti dejstvo o številu</a>

    
  <script>
    function shrani() {
      var username = document.getElementById("username").value;
      let naj_st = document.getElementById("najljubse_stevilo").value;

      $.ajax({
        url: "/shrani_najljubse_stevilo",
        data: {
          username     : username,
          najljubse_st : naj_st
        }
      });
    }
  </script>

</body>
</html>
```

# PRIPRAVLJENA KODA
## index.html
```python=
<!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> Izberi:</H1>
    <a href="/pot_do_routa1">Ime1</a><br>
    <a href="/pot_do_routa2">Ime2</a><br>
    <a href="/pot_do_routa3">Ime3</a>
</body>
</html>
```

---

## izvzem ključev iz dict in dodajanje v spustni seznam
mapa: templates, datoteka: koda.html
```htmlmixed=
<select id="izbira">
    {% for posta in postne_st %}
        <option value="{{ postna_st }}">{{ postna_st }}</option>
    {% endfor %}
</select>
```
---

# API ZA TEST
## Chuck Norris API: https://api.chucknorris.io/
base url = "https://api.chucknorris.io/jokes/random"

### iskanje random
```python=
base_url = "https://api.chucknorris.io/jokes/random"
call = requests.get(base_url).json()
print(call)
```
![image](https://hackmd.io/_uploads/ByLByiVmC.png)

---

### iskanje po kategorijah
**Kategorije:**["animal","career","celebrity","dev","explicit","fashion","food","history","money","movie","music","political","religion","science","sport","travel"]
```python=
category = ["animal","career","celebrity","dev","explicit","fashion","food","history","money","movie","music","political","religion","science","sport","travel"]
  
#category = celebrety
base_url = f"https://api.chucknorris.io/jokes/random?category={category[2]}"
call = requests.get(base_url).json()
print(call)
```
![image](https://hackmd.io/_uploads/SJ4IAc47A.png)

---

### iskanje vicov z besedami
```python=
#glede na besedo najde chuck norris vice
words = "hello"
base_url = f"https://api.chucknorris.io/jokes/search?query={words}"
call = requests.get(base_url).json()
print(call)
```
![image](https://hackmd.io/_uploads/Hk3wei4Q0.png)

---


## Holidy API: https://date.nager.at/Api
base_url = "https://date.nager.at/api/v3"

### iskanje podatkov države iz 2 črk
```python=
contryCode = "SI"
base_url = f"https://date.nager.at/api/v3/CountryInfo/{contryCode}"
call = requests.get(base_url).json()
pprint.pprint(call)
```
![image](https://hackmd.io/_uploads/BJfnT04m0.png)

---



## Nationalize: https://nationalize.io
base_url = "https://api.nationalize.io"

### pridobi nationalitys iz imena
```python=
name = "johnson"
base_url = f"https://api.nationalize.io?name={name.lower()}"
call = requests.get(base_url).json()
pprint.pprint(call)
```

![image](https://hackmd.io/_uploads/r1pkarD7R.png)

---

## Genderize: https://genderize.io/
base_url = "https://api.genderize.io"

### pridobi podatke za specifično ime
```python=
name = "johnson"
base_url = f"https://api.genderize.io?name={name.lower()}"
call = requests.get(base_url).json()
pprint.pprint(call)
```
![image](https://hackmd.io/_uploads/HkV96Bwm0.png)

---

### pridobi podatke za specifično ime v določeni državi
```python=
name = "johnson"
base_url = f"https://api.genderize.io?name={name.lower()}"
call = requests.get(base_url).json()
pprint.pprint(call)
```

![image](https://hackmd.io/_uploads/S19oCHPXR.png)

---

## Agify: https://agify.io/
base_url = "https://api.agify.io"

### pridobi podatke za specifično ime
```python=
name = "johnson"
base_url = f"https://api.agify.io?name={name.lower()}"
call = requests.get(base_url).json()
pprint.pprint(call)
```
![image](https://hackmd.io/_uploads/r1jmyIPQR.png)


---

### pridobi podatke za specifično ime v določeni državi
```python=
name = "michael"
country_id = "US"
base_url = f"https://api.agify.io?name={name.lower()}&country_id={country_id.upper()}"
call = requests.get(base_url).json()
pprint.pprint(call)
```

![image](https://hackmd.io/_uploads/B1PPy8w7R.png)


---

## Vreme: https://openweathermap.org/
api_key = "5f5c8f523ca2bf8d20d9babb8676c5f4"

### iskanje podatkov za kraj z lat in lon
```python=
api_key = "5f5c8f523ca2bf8d20d9babb8676c5f4"

payload = {
    "lat"    : 46.24315712153155,
    "lon"    : 14.35470591783279,
    "appid": api_key
}
  
base_url = "https://api.openweathermap.org/data/2.5/weather"
call = requests.get(base_url, params = payload).json()
pprint.pprint(call)
```
![image](https://hackmd.io/_uploads/S1CtPntXR.png)

---

### iskanje podatkov za kraj iz imena
```python=
api_key = "5f5c8f523ca2bf8d20d9babb8676c5f4"
city_name = "London"

base_url = f"https://api.openweathermap.org/data/2.5/weather?q={city_name}&appid={api_key}"
call = requests.get(base_url).json()
pprint.pprint(call)
```
![image](https://hackmd.io/_uploads/rJ_eOntXR.png)

---

## Bored API: https://www.boredapi.com/
base_url = "http://www.boredapi.com/api/activity"

Parametri:
![image](https://hackmd.io/_uploads/S1k7eUwQ0.png)

### pridobi naključno aktivnost
```python=
base_url = "http://www.boredapi.com/api/activity"
call = requests.get(base_url, params = payload).json()
pprint.pprint(call)
```

![image](https://hackmd.io/_uploads/H1V0bLPQA.png)

---

### pridobi podatke za določeno dejavnost
(vrednosti nastavi v payload)
```python=
payload = {
    "type"         : "education",
    "participants" : 1
}

base_url = "http://www.boredapi.com/api/activity"
call = requests.get(base_url, params = payload).json()
pprint.pprint(call)
```

![image](https://hackmd.io/_uploads/H1u6lUPQA.png)

---

## Jokes: https://sv443.net/jokeapi/v2/
base_url = "https://sv443.net/jokeapi/v2"

### 
```python=

```

## PokeAPI: https://pokeapi.co/
base_url = "https://pokeapi.co/api/v2"

### 
```python=

```

## Cards: https://www.deckofcardsapi.com/

### premešaj karte
```python=
deck_count = 1
base_url = f"https://www.deckofcardsapi.com/api/deck/new/shuffle/?deck_count={deck_count}"
call = requests.get(base_url).json()
pprint.pprint(call)
```

![image](https://hackmd.io/_uploads/ByaQC0OQA.png)

---

### vzemi 2 karti iz kupa
```python=
deck_id = "sz4kt8mewbwd"
deck_draw = 2 #vzem kart
base_url = f"https://www.deckofcardsapi.com/api/deck/{deck_id}/draw/?count={deck_draw}"
call = requests.get(base_url).json()
pprint.pprint(call)
```

![image](https://hackmd.io/_uploads/HkK7yJYXR.png)

---

### premešaj VSE karte
```python=
deck_id = "sz4kt8mewbwd"
deck_draw = 2 #vzem kart
base_url = f"https://www.deckofcardsapi.com/api/deck/{deck_id}/draw/?count={deck_draw}"
call = requests.get(base_url).json()
pprint.pprint(call)
```

![image](https://hackmd.io/_uploads/H1zxl1t70.png)

---

### premešaj karte v GLAVNEM kupu
```python=
deck_id = "sz4kt8mewbwd"
base_url = f"https://www.deckofcardsapi.com/api/deck/{deck_id}/shuffle/?remaining=true"
call = requests.get(base_url).json()
pprint.pprint(call)
```

![image](https://hackmd.io/_uploads/SJTExJt7R.png)

---

### dodaj nov kup kart
```python=
deck_id = "sz4kt8mewbwd"
base_url = f"https://www.deckofcardsapi.com/api/deck/{deck_id}/shuffle/?remaining=true"
call = requests.get(base_url).json()
pprint.pprint(call)
```

![image](https://hackmd.io/_uploads/SJTExJt7R.png)

---


### dodaj nov costum  kup kart
```python=
cards = "AS,2S,KS,AD,2D,KD,AC,2C,KC,AH,2H,KH"
base_url = f"https://www.deckofcardsapi.com/api/deck/new/shuffle/?cards={cards}"
call = requests.get(base_url).json()
pprint.pprint(call)
```

![image](https://hackmd.io/_uploads/HkRu-kYXC.png)

---

### dodaj nov costum  kup kart iz seznama
```python=
  cards_sez = ["AS", "2S", "KS", "AD", "2D", "KD", "AC", "2C", "KC", "AH", "2H", "KH"]
  cards = ""
  
  for card in cards_sez:
    cards += card + ","

  print(cards)
  
  base_url = f"https://www.deckofcardsapi.com/api/deck/new/shuffle/?cards={cards}"
  call = requests.get(base_url).json()
  pprint.pprint(call)
```

![image](https://hackmd.io/_uploads/B1YsfJtXR.png)

---

### dodajanje kart na svoj kup
```python=
cards = "AS,2S"
deck_id = "sz4kt8mewbwd"
username = "masa"
  
base_url = f"https://www.deckofcardsapi.com/api/deck/{deck_id}/pile/{username}/add/?cards={cards}"
call = requests.get(base_url).json()
pprint.pprint(call)
```

![image](https://hackmd.io/_uploads/H1iTEyF70.png)

---

### pogled v kupček
```python=
deck_id = "sz4kt8mewbwd"
username = "masa"
  
base_url = f"https://www.deckofcardsapi.com/api/deck/{deck_id}/pile/{username}/list/"
call = requests.get(base_url).json()
pprint.pprint(call)
```

![image](https://hackmd.io/_uploads/BkhMHJYmR.png)

---

### vrnitev kart na glavni kup

https://www.deckofcardsapi.com/api/deck/<<deck_id>>/return/
https://www.deckofcardsapi.com/api/deck/<<deck_id>>/pile/<<pile_name>>/return/
https://www.deckofcardsapi.com/api/deck/<<deck_id>>/return/?cards=AS,2S
https://www.deckofcardsapi.com/api/deck/<<deck_id>>/pile/<<pile_name>>/return/?cards=AS,2S


# FUNKCIJE
## .split()
text ali seznam
### razdeli vse
```python=
x = txt.split("znak")
```

### razdeli določeno št
```python=
x = txt.split("znak", st_splitov)
```

## random
**random.randrange(start, stop, step)** - stop se ne upošteva(če izbiramo 1 in 2, bo izbral 1, 2 se ne upošteva)

**random.randint(start, stop)** - obe števili se upoštevata


## dobivanje max vrednosti v dict
```python=
# Creating a dictionary
dictt = {'1': 100, '2': 1292, 'Hi': 6543}

# Getting the key with maximum value
Key_max = max(zip(dictt.values(), dictt.keys()))[1]
print("The key with the maximum value is: ", Key_max)
```
![image](https://hackmd.io/_uploads/rk3KE2tXR.png)
