---
# System prepended metadata

title: flask

---

#1
### PYTHON
```python=
import requests
from pprint import pprint

dict = {"Ime" : "David",
   "Starost" : "17",
   "Zaposlen" : False,
   "Siblings" : ["Matej"]}
url = "https://api.chucknorris.io/jokes/random"
call = requests.get(url)
pprint(dict["Ime"])
pprint(dict["Zaposlen"])
pprint(dict["Siblings"][0])

pprint(dict.get("Ime", -1))
```


### PYTHON
```python=
import requests

for i in range(101):
  url = f"http://numbersapi.com/{i}/trivia"
  print(url)
  k = requests.get(url)
  print(k.text)
```

### PYTHON
```python=
import requests
from flask import Flask, render_template
import random
app = Flask("app")
@app.route('/')
def index():
  k = requests.get("https://zenquotes.io/api/quotes/author/babe-ruth/").json()
  temp = k[0]['q']
  return render_template("index.html",quote=temp)
  
app.run(host='0.0.0.0', port=8080, debug=True)
```
# flask
### PYTHON
```python=
import requests
from flask import Flask, render_template

app = Flask("app")
d = requests.get("https://dog.ceo/api/breeds/list/all").json()
sez = list(d["message"].keys())
print(sez)
@app.route('/')
def index():
  d = requests.get("https://dog.ceo/api/breeds/list/all").json()
  sez = list(d["message"].keys())

  return render_template("index.html",sez=sez)
app.run(host='0.0.0.0', port=8080, debug=True)
```

### HTML
```htmlembedded=
<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Hello Bulma!</title>
  </head>
  <body>
    Pasme:
    {%for s in sez%}
     <ul><li>{{ s }}</li></ul>
    {% endfor %}
    </table>
  </body>
</html>
```
-----------------------------------------------------------------------------------------------
### PYTHON
```python=
from flask import Flask, render_template, request
import requests
from pprint import pprint


app = Flask("app")
@app.route('/')
def index():
  API_KEY = "420c89673fa140bf927be5752ab5c9c5"
  APIkey = "c7244d9045470736bf3e1e55e2f57235"
  x = dict(request.headers)
  x = x["X-Forwarded-For"].split(",")[0]

  url = f"https://api.ipgeolocation.io/ipgeo?apiKey={API_KEY}&ip={x}"
  q = requests.get(url).json()
  lat = q["latitude"]
  lon = q["longitude"]
  Ł =q["country_name"]
  urlmk2 = f"https://api.openweathermap.org/data/2.5/weather?lat={lat}&lon={lon}&appid={APIkey}"
  đ = requests.get(urlmk2).json()
  ł = đ["weather"][0]["main"]
  ß = đ["sys"]["country"]
  š = đ["weather"][0]["icon"]
  pprint(đ)

  return render_template("index.html",lat = lat, lon = lon,ip = x, Ł = Ł, ł=ł,ß=ß,š=š)

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

### HTML
```htmlembedded=
<!DOCTYPE html>
<html lang="en-US">
<head>
  <title>Doc</title>
  <style>
    body{
      margin:20px;
      background-color:#537d99;
    }
    h1{
      font-family: "Times New Roman", Times, serif;
      color:#d69074;
      text-align:center;
    }
    p{
      font-family: "Times New Roman", Times, serif;
      color:#edc593;
      font-size:1.2em;
      padding:5px;
    }
  </style>
</head>
<body>
  <h1>Deus dê</h1>
  <p>IP: 
    {{ ip }}
  </p>
  <p>Lan: 
    {{ lat }}
  </p>
  <p>Lon:
    {{lon}}
  </p>
  <p>
    Country: {{ ß }}, {{ Ł }}
  </p>
  <p>
   Weather: {{ ł }}
  </p>
    <img src="https://openweathermap.org/img/wn/{{ š }}.png" alt ='sljejka' height='170' width='200'>
  </body>
</html>
```

# AJAX vzhod/zahod
### PYTHON
```python=
from flask import Flask, render_template, request
from flask.json import jsonify
import requests
import pprint

app = Flask('app')

@app.route('/')
def hello_world1():
  return render_template("index1.html")

@app.route('/sonce')
def hello_world():
  id = request.args
  lat = id["lat"]
  lon = id["lon"]
  url = f"https://api.sunrise-sunset.org/json?lat={lat}&lng={lon}&date=2024-04-22"
  klic = requests.get(url).json()
  vzhod = klic["results"]["sunrise"]
  zahod = klic["results"]["sunset"]
  return jsonify({'vzhod': vzhod, 'zahod': zahod})
app.run(host='0.0.0.0', port=8080, debug=True)
```
### HTML
```htmlembedded=
<!DOCTYPE html>
<html>
  <head>
    <title>My Page</title>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
  </head>
  <body>
    <h1>Welcome to My Page</h1>
    <form id="sonck">
      <input type="text" id="lat" name="lat" placeholder="latitude"> <!-- Added id="lat" -->
      <input type="text" id="lon" name="lon" placeholder="longitude"> <!-- Added id="lon" -->
    </form>
    <button onclick="sonckGet()">dobi sonce</button>
    <p>vzhod: <span id="vzhod"></span></p> <!-- Added span with id="vzhod" -->
    <p>zahod: <span id="zahod"></span></p> <!-- Added span with id="zahod" -->
    <script>
      function sonckGet(){
        let lat = document.getElementById("lat").value;
        let lon = document.getElementById("lon").value;
        $.ajax({
          url:"/sonce",
          data: {
            lat: lat,
            lon: lon
          },
          success: function(result) {
            $("#vzhod").text(result.vzhod)
            $("#zahod").text(result.zahod)
          }
        });
      }
    </script>
  </body>
</html>
```

# AJAX numbersQuote
### PYTHON
```python=
from flask import Flask, request, jsonify, render_template
import pprint
import requests

app = Flask('app')

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

@app.route('/quote')
def get_quote():
  id = request.args
  num = id["num"]
  url = f"http://numbersapi.com/{num}"
  quote = requests.get(url)
  
  return jsonify({'quote': quote.text})

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

```
### HTML
```htmlmixed=
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>New HTML Page</title>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
</head>
<body>
    <h1>Welcome to this website</h1>
    <form>
      <input type="text" id="num" name="num" placeholder="number">
    </form>
    <button onclick="quoteGet()">quote</button>
    <p>quote: <span id="quote"></span></p>  
  <script>
    function quoteGet() {
      let num = document.getElementById("num").value;
      $.ajax({
        url: "/quote",
        data: {
          num: num
        },
      success: function(result) {
        $("#quote").text(result.quote)
      }
      })
    }
  </script>
</body>
</html>
```

# AJAX meme
### PYTHON
```python=
from flask import Flask, render_template, request, jsonify
from flask.json import jsonify
import requests
import pprint

app = Flask('app')

@app.route('/')
def index():
  url = "https://api.imgflip.com/get_memes"
  klic = requests.get(url).json()
  values = klic['data']['memes']
  return render_template('index.html', values = values)

@app.route('/meme')
def meme():
  lin = ""
  ime = ""
  id = request.args['id']
  url = "https://api.imgflip.com/get_memes"
  klic = requests.get(url).json()
  for i in klic['data']['memes']:
    if i['id'] == id:
      lin = i['url']
      ime = i['name']
  img = f'<img src="{lin}" width="500" height="500" text-align="center">'
  return jsonify({'slika': img, 'name': ime})
app.run(host = '0.0.0.0', port = 8080, debug=True)
```
### HTML
```htmlmixed=
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Meme page</title>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
</head>
<body>
  <h1>MEME</h1>
  <form></form>
  <select id="izbrano">
    {% for i in values %}
    <option value="{{ i.id }}">{{ i.name }}</option>
    {% endfor %}
  </select>
  <button onclick="memeGet()">Dobi sliko</button>
  <h2 id="imeslike"></h2>
  <div id="slika"></div>
  <script>
    function memeGet() {
      let id = document.getElementById("izbrano").value;
      $.ajax({
        url: "/meme",
        data: {
          id: id
        },
        success: function(result) {
          $("#imeslike").text(result.name)
          console.log(result.slika)
          slika.innerHTML = result.slika
        }
      })
    }
  </script>
</body>
</html>
```
# AJAX vreme z LAT in LON
### PYTHON
```python=
from flask import Flask, render_template, request, jsonify
import requests
import pprint

app = Flask('app')

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

@app.route('/vreme')
def hello_world():
  id = request.args
  pprint.pprint(id)
  lat = id["lat"]
  lon = id["lon"]
  url = f"https://api.openweathermap.org/data/2.5/weather?lat={lat}&lon={lon}&appid=07f6bed890038cb7cd54961d3cdcbb73"
  klic = requests.get(url).json()
  pprint.pprint(klic)
  vreme1 = klic["weather"][0]["description"]
  return jsonify({'vreme': vreme1})
app.run(host='0.0.0.0', port=8080, debug=True)
```
### HTML
```htmlmixed=
<!DOCTYPE html>
<html>
  <head>
    <title>My Page</title>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
  </head>
  <body>
    <h1>Welcome to My Page</h1>
    <form id="location">
      <input type="text" id="lat" name="lat" placeholder="latitude"> <!-- Added id="lat" -->
      <input type="text" id="lon" name="lon" placeholder="longitude"> <!-- Added id="lon" -->
    </form>
    <button onclick="vremeGet()">dobi vreme</button>
    <p>vreme: <span id="vreme"></span></p> <!-- Added span with id="vzhod" -->
    <script>
      function vremeGet(){
        let lat = document.getElementById("lat").value;
        let lon = document.getElementById("lon").value;
        $.ajax({
          url:"/vreme",
          data: {
            lat: lat,
            lon: lon
          },
          success: function(result) {
            $("#vreme").text(result.vreme)
          }
        });
      }
    </script>
  </body>
</html>
```
# AJAX MIN/MID/MAX
### PYTHON
```python=
from flask import Flask, jsonify, render_template, request
import pprint
import requests

app = Flask('app')

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

@app.route("/numGet")
def numGet():
  stev1 = int(request.args.get("stevilo1"))
  stev2 = int(request.args.get("stevilo2"))
  stev3 = int(request.args.get("stevilo3"))
  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)

```
### HTML
```htmlmixed=
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
    <title>Sample Page</title>
</head>
<body>
    <h1>Hello, World!</h1>
    <form id="stevila">
      <input type="text" id="stevilo1" name="stevilo1" placeholder="stevilo1">
      <input type="text" id="stevilo2" name="stevilo2" placeholder="stevilo2">
      <input type="text" id="stevilo3" name="stevilo3" placeholder="stevilo3">
    </form>
    <button onclick="numGet()">Dobi sliko</button>
    <p id=minSt></p>
    <p id=midSt></p>
    <p id=maxSt></p>
  <script>
    function numGet(){
      let stevilo1 = document.getElementById("stevilo1").value
      let stevilo2 = document.getElementById("stevilo2").value
      let stevilo3 = document.getElementById("stevilo3").value
      $.ajax({
        url: "/numGet",
        data: {
          stevilo1: stevilo1,
          stevilo2: stevilo2,
          stevilo3: stevilo3
        },
        success: function(result){
          $("#minSt").text(result.min)
          $("#midSt").text(result.middle)
          $("#maxSt").text(result.max)
        }
          
        })
    }
  </script>
</body>
</html>
```

JINJA CHEATSHEET

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 %}
Library#
Basic usage
from jinja2 import Template
template = Template('Hello {{ name }}!')
template.render(name='John Doe') == u'Hello John Doe!'