TIL Python Basics Day 57 - Templating with Jinja / URL Building

이다연·2021년 2월 13일
0

Udemy Python Course

목록 보기
53/64

Jinja

Jinja is a Templating language.
To use python code in your website: put{{ python code }}in your html file.

  • main.py

    Passing over keyword arguments to be used in html file

import random

@app.route("/")
def home():
    random_num = random.randint(1, 10)
    return render_template("index.html", num=random_num )
  • index.html

    Use double curly brackets to hold python code, which was passed over keyword argument from function at main.py

<h2>Random number: {{num}}</h2>

server.py

@app.route("/")
def home():

    today_year =  datetime.today().year
    return render_template("index.html", today_year=today_year)
    ```

index.html

<body>
    <p>Copyright {{today_year}}. Built by Daylee </p>
</body>

Task. Name and Age/Gender guess

Goal: Use name data API, create a url guess game.

Agify
Genderize

solution

server.py

variable rules, passing url:<name>, guess function goes through the decorator method, it's going to give a value for this name variable(url typed by user), and catch that name send it over when I render the template

from flask import Flask, render_template
from datetime import datetime
import requests


app = Flask(__name__)


@app.route("/")
def home():
    today_year = datetime.today().year
    return render_template("index.html", today_year=today_year)

@app.route("/guess/<name>")
def guess(name):
    today_year = datetime.today().year
    parameters = {
        "name": name,
    }
    response_gender = requests.get(url="https://api.genderize.io", params=parameters)
    response_gender.raise_for_status()

    gender_data = response_gender.json()
    gender = gender_data['gender']

    parameters = {
        "name": name,
    }
    response_age = requests.get(url="https://api.agify.io", params=parameters)
    response_age.raise_for_status()

    age_data = response_age.json()
    age = age_data['age']
    count = age_data['count']
    
    return render_template("guess.html", name=name, gender=gender, age=age, count=count, today_year=today_year)


if __name__ == "__main__":
    app.run(debug=True)

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Guess</title>
</head>
<body>
    <h1>Welcome to Guess!</h1>
    <h2>Give me your name, I will guess your age.</h2>
    <img src="https://media.giphy.com/media/13RcbHeXlLNysE/giphy.gif">
    <p>Copyright {{today_year}}. Built by Daylee </p>
</body>
</html>

guess.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Guess {{name}}'s age...</title>
</head>
<body>
    <h1>Hey <em>{{name.title()}}!</em> </h1>
    <h2>I think you are {{gender}}.</h2>
    <h3>And maybe {{age}} years old.</h3>
    <p>Am I right? Am I right?</p>
    <img src="https://media.giphy.com/media/Vu8bdTGdxEzCg/giphy.gif">
    <p>I am accurate as I searched <em>{{count}}</em> online references for it!</p>
    <p>Copyright {{today_year}}. Built by Daylee </p>

</body>
</html>

Multi line statement

for, if ...etc statements

{% for %}
   {{}}
{% endfor %}

n:point: creating API


<body>

    {% for blog_post in posts: %}
    
        {% if blog_post['id'] == 2: %}
            <h1>{{ blog_post['title'] }}</h1>
            <h2>{{ blog_post['subtitle'] }}</h2>
        {% endif %}
        
    {% endfor %}

</body>

URL Building

To generate a hypelink, use anchor href and direct user to a specific page.
a href = {{ url_for('name of a function in the server') }}

server.py----------
@app.route('/blog')
	def get_blog():
  		
  
index.html----------   
<a href="{{ url_for('get_blog') }}">Go To Blog</a>

When you click on the link, it directs to /blog

Specific url

Add parameters just like rendering html using keyword argument.
Be aware: {{ url_for('get_blog', num=3) }} parameter needs brackets!!!

server.py----------
@app.route('/blog/<index>')
def get_blog(index):

index.html----------  
    <a href="{{ url_for('get_blog', index=3) }}">Go To Blog</a>

Task: Blog

  • server.py

    1) route function got input from user,
    which is the value inside angle bracket <>
    2) blog_posts function got hold of input value from decorator
    3) return values to be used html template with Jinja

@app.route('/post/<int:number>')  #1)
def blog_posts(number):  #2)
  	    response = requests.get(url="https://api.npoint.io/5ab~")
    data = response.json()
    print(number)
    return render_template("post.html", posts=data, num=number)  #3)
  • index.html

    link: created an anchor href at home url('/'), it goes to blog_posts page, that has url path /post/1

 <a href="{{ url_for('blog_posts', number=1) }}">Read</a>
  • post.html

    Use json data values, which was returned from def_blog_posts(). With Jinja {{ }}, it reads Json data.

Project: Blog

Behaviour focused Docstring writing practice.

profile
Dayeon Lee | Django & Python Web Developer

0개의 댓글