카테고리 없음

스파르타 AI-8기 TIL(9/20)

kimjunki-8 2024. 9. 20. 18:04

Ah....Ah....................Ahh...

Tired....really....

how to use variables. var, let, const

var = -> function scope, may cause an error, not much used.

let = -> Block scope, mostly used, can be reallocated.

const = -> Unlike let, this cannot be reallocated.

Ex)

var name = "John";  // function scope
let age = 25;       // block scope
const country = "Korea";  // cannot reallocated

 

Conditional statements and loops

if, else if, else, switch, for, while

Ex.

conditional

let score = 85;
if (score >= 90) {
  console.log("A+");
} else if (score >= 80) {
  console.log("A");
} else {
  console.log("B");
}

 

loop

for (let i = 0; i < 5; i++) {
  console.log(i); 
}

List and dictionary

List Ex.

let a = [a, b, c, d, e]

console.log(a[0])

console.log(a[1])

console.log(a[2])

........

 

putting elements into list(.push)

a.push('h')

console.log(a)

 

getting the length of the list

console.log(a.length)

 

jQuery formal frame

Add!

<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.4/jquery.min.js"></script>
</head>

$(document).ready(function() {
  $('#myButton').click(function() {
    $('#header').text('Button Clicked!');
  });
});

 

names = [{'name':'bob','age':20},{'name':'carry','age':38}] or

 

 

$(document).ready() -> start the code when the page is fully loaded 

$('#elementID') -> Selects the HTML element with id elementID.

click() -> Add click event handler

text() -> Change the text of the chosen element 

 

Event Handler

Event Handler : click(), hover(), focus() 

Animation : fadeIn(), fadeOut(), slideToggle()

// Example of animation
$('#myButton').click(function() {
  $('#header').fadeOut(1000);  // will be gone slowly in 1 second
});

 

Fetch API

fetch(url): Sends an HTTP request to the specified URL.
response.json(): change the response from the server in JSON format.
then(): A callback function is executed when the request succeeds.
catch(): Handles errors when the request fails.

 

Ex. Fetch API

fetch('https://jsonplaceholder.typicode.com/posts/1')
  .then(response => response.json())  // Turn it into json type 
  .then(data => console.log(data))    // Data processing
  .catch(error => console.error('Error:', error));

 

Parameters & Arguments

def hey(): 
print("hey") 
hey() 


# a,b,c 
def sum(a,b,c): -> a, b, c -> parameters = receive
return a+b+c


result = sum(1,2,3) -> 1, 2, 3 -> arguments = send
print(result)

 

Default Parameters

def greet(name="Guest"): -> if there is no variables to put in, "Guest" will be shown as default
    return f"Hello, {name}!" -> f = f-string(format string) - ways to put the string easily

print(greet())       # output: Hello, Guest!
print(greet("Bob"))  # output: Hello, Bob!

 

Keyword Arguments

def introduce(name, age):
    return f"My name is {name} and I am {age} years old."

# ex.
print(introduce(age=30, name="Alice"))  # output: My name is Alice and I am 30 years old. -> without orders

 

**Variable arguments

 

# *args example
def sum_all(*args): // *args -> can send multiple variables, and receive in tuple shape
    return sum(args)

print(sum_all(1, 2, 3, 4, 5))  # 출력: 15

# **kwargs example
def print_info(**kwargs): -> can receive multiple keyword variables, receive in dictionary type
    for key, value in kwargs.items():
        print(f"{key}: {value}")

print_info(name="Alice", age=30, city="Seoul")
# 출력:
# name: Alice
# age: 30
# city: Seoul

 

Python Virtual Environment

Why should I use PVE?

To prevent version collection and corruption of the Python Environment

Making PVE

1. Ctrl + shift + p

2. Python : Create Environment

3. Venv

4. choose version 

 

Package(Scraping=crawling)

Getting some important info from another site

Web page request - use the requests(import requests) library to get the HTML source

HTML Parsing - through using beautifulSoup to inspect the HTML documents and to get needed information

Data extract: extract from the specific tags of HTML

Ex.

import requests -> requests
from bs4 import BeautifulSoup

# 1. requesting web page
url = "https://example.com"
response = requests.get(url) 

# 2. HTML parsing
soup = BeautifulSoup(response.text, "html.parser")

# 3. data extract (예시: <h1> extract the text of tags)
heading = soup.find('h1').text
print("페이지의 제목:", heading)

 

requests.get(url): Send an HTTP request to the given URL and get its response. In this case, we send a request to https://example.com.
BeautifulSoup(response.text, "html.parser"): response.text is the HTML of the web page, and we parse this HTML using html.parser.
soup.find('h1'): Find the first <h1> tag in the HTML.
.text: Extract the text content of the tag.

In HTML,

<!DOCTYPE html>
<html>
  <head>
    <title>Example Domain</title>
  </head>
  <body>
    <h1>Example Domain</h1>
    <p>This domain is for use in illustrative examples in documents.</p>
    <a href="https://www.iana.org/domains/example">More information...</a>
  </body>
</html>

The contents of the tag is "Example Domain"

 

Getting multiple data -> find_all

# find all texts from <p> tags
paragraphs = soup.find_all('p')
for p in paragraphs:
    print("contents:", p.text) -> 

Notice

p.text and p is different. If I want to extract the text from a certain line, must use .text, or getting the line itself, must use only p(variable)

# p.text
for p in paragraphs:
    print("paragraph contents:", p.text)  # only text
# p
for p in paragraphs:
    print("paragraph tags:", p)  # all tags

extract all the links from <a> tags
links = soup.find_all('a')
for link in links:
    print("link:", link['href'])

 

soup.find_all('p'): Finds all <p> tags in an HTML document and returns them as a list.
soup.find_all('a'): Finds all <a> tags and returns them. You can extract hyperlinks through the href attribute of each <a> tag.

 

In app.py, when I want to change something,

@app.route("/")
def home():
    name = 'Kevin'
    return render_template('motto.html', data = name)
    <div class="container">
        <div class="greeting">
            <h1>Hello, {{ data }}!</h1>
            <h1 id="current-time"></h1>
        </div>

Project

through making @app.route("/")

def home():
    name = 'Kevin'

    return render_template('motto.html', data = name)

means connect to the motto.html file, and makes it add data named kevin

 

and Hello, {{ data }} -> {{ data }} will be added based on the name

When writing more than one data,

@app.route("/")
def home():
    name = 'Kevin'
    motto = "Just do it"

    context = {
        "name" : name,
        "motto" : motto
    }
    return render_template('motto.html', data = context)

Make a dictionary to add more datas

 

   <div class="container">
        <div class="greeting">
            <h1>Hello, {{ data.name }}!</h1>
            <h1 id="current-time"></h1>
        </div>

        <div class="motto">
            <h3>My life's motto</h3>
            <h2>{{ data.motto }}</h2>
        </div>
    </div>

Since it's a dictionary, must use the key.(.name, .motto)

 

@app.route("/iloveyou/<name>")
def iloveyou(name):
    motto = f"{name} hey it's only you"

    context = {
        'name' : name,
        'motto' : motto
    }
    return render_template('motto.html', data = 'context')

<name> -> can be used as variable if you cover with <>

f"{}" -> if I use f, then I can put variables into the "{}"

meaning, I put /iloveyou/myname on the search bar, I can use it as a variable right away

 

Output:

 

a class="nav-link text-white" aria-current="page" href="{{ url_for('home') }}">Home</a>

url_for -> it will specify the link

 

Database types:

1. SQL -> save all the data in order (easy to analyze)

2. No-SQL - save data in dictionary type (not easy to analyze)

 

flask shell

from app import db, Song 
db.create_all()

song = Song(username="추천자", title="노래제목", 
            artist="가수", image_url="이미지 주소") // song이 db에 데이터 주입
db.session.add(song) // 이 줄이 db에 데이터를 업로드
db.session.commit() // db 데이터 저장

output:

 

How to add multiple rows

song1 = Song(username="추천자", title="노래제목1", 
            artist="가수1", image_url="이미지 주소1")

song2 = Song(username="스파르타", title="노래제목2", 
            artist="가수2", image_url="이미지 주소2")

song3 = Song(username="스파르타", title="노래제목3", 
            artist="가수3", image_url="이미지 주소3")
db.session.add(song1)
db.session.add(song2)
db.session.add(song3)

db.session.commit()

Output:

Just added the lines with the first method

 

How to check the data

song_list = Song.query.all()

song_list[0].(name of the info(ex.title, artist etc...)

 

Bring data under specific condition

Song.query.filter_by(condition).all()

Ex. Song.query.filter_by(username='추천자').all()(all()뿐만 아니라, 하나만 가져올때는 first()등이 이다)

 

Changing data

song_data = Song.query.filter_by(id = 4).first() -> choose the data

song_data.title = 'changed title' -> content you want to change

db.session.add(song_data)

db.session.commit()

 

Delete data

delete_data = Song.query.filter_by(id=3).first()

db.session.delete(delete_data)

db.session.commit()

Good night