728x90
반응형

https://www.notion.so/dfb89a042c6f4b29b64ea4da03a37ea6#cf5611d0d873436f9983ed3a96268231

[스파르타코딩클럽] 파이썬 문법 뽀개기

 

문자열

 

문자열 길이

text = 'jeonghoon'
result = len(text)
#값은 9

문자열 자르기

text = 'jeonghoon'
result = text[0:5]
#결과는 jeong

문자열 나누기

myemail = 'abc@sparta.co'
result = myemail.spit('@')[1].split('.')[0]
#답은 sparta

 

리스트와 딕셔너리

 

리스트는 순서가 중요하게 값을 담음

딕셔너리는 key와 value가 중요함

 

리스트 추가

a_list = [1,2,3,4,5]
a_list.append(99)

 

리스트 정렬

a_list = [1,5,3,7,9]
a_list.sort()

리스트 확인

a_list = [1,5,6,3,2]
result = ( 5 in a_list )
#들어있다면 true, 없다면 false

 

딕셔너리 형태

a_dict = {'name':'bob', 'age':27, 'friend' : ['영희','철수']}
a_dict['height'] = 180
result = ('height' in a_dict)

퀴즈 스미스의 과학 점수를 가져오기

people = [
    {'name': 'bob', 'age': 20, 'score':{'math':90,'science':70}},
    {'name': 'carry', 'age': 38, 'score':{'math':40,'science':72}},
    {'name': 'smith', 'age': 28, 'score':{'math':80,'science':90}},
    {'name': 'john', 'age': 34, 'score':{'math':75,'science':100}}
]
result = people[2]['score']['science']
print (result)

 

조건문, 반복문

money = 3000

if money > 3800:
	print('택시를 타자!')
elif money > 1200:
	print('버스를 타자!')
else:
	print('걸어가자!')

기초 반복문

fruits = ['사과', '배', '감']
for fruit in fruits:
    print(fruit)

 

people = [
    {'name': 'bob', 'age': 20},
    {'name': 'carry', 'age': 38},
    {'name': 'john', 'age': 7},
    {'name': 'smith', 'age': 17},
    {'name': 'ben', 'age': 27},
    {'name': 'bobby', 'age': 57},
    {'name': 'red', 'age': 32},
    {'name': 'queen', 'age': 25}
]

for person in people:
    name = person['name']
    age = person['age']
    print (name, age)

짝수 갯수세기

num_list = [1, 2, 3, 6, 3, 2, 4, 5, 6, 2, 4]

count = 0

for num in num_list:
    if (num % 2 == 0):
        count+= 1

print(count)

가장 큰 수 구하기

num_list = [1, 2, 3, 6, 3, 2, 4, 5, 6, 2, 4]

max = 0

for num in num_list:
    if max < num:
        max = num

print (max)

함수

주민번호를 입력받아 남여 판별하는 함수

def check_gender(pin):
    num = pin.split('-')[1][:1]
    if int(num) % 2 == 1 :
        print('남자')
    if int(num) % 2 == 0 :
        print('여자')

check_gender('991111-1234567')
check_gender('991111-2234567')

 

튜플(순서가 있고, 불변형)

a = (1,2,3)
print(a[0])

#아래와 같이 변형 불가능
a = (1,2,3)
a[0] = 99

집합( set( ) , 중복을 제거해줌 )

a = [1,1,2,3,3,3,4,4,5,5]
a_set = set(a)

#출력값 {1,2,3,4,5}
student_a = ['물리2','국어','수학1','음악','화학1','화학2','체육']
student_b = ['물리1','수학1','미술','화학2','체육']

a_set = set(student_a)
b_set = set(student_b)

print (a_set & b_set) #교집함
print (a_set | b_set) #합집합
print (a_set - b_set) #차집합

f-string (f'{name}')

scores = [
    {'name':'영수','score':70},
    {'name':'영희','score':65},
    {'name':'기찬','score':75},
    {'name':'희수','score':23},
    {'name':'서경','score':99},
    {'name':'미주','score':100},
    {'name':'병태','score':32}    
]

for s in scores:
    name = s['name']
    score = s['score']
    print (name+'의 점수는 '+str(score)+'점입니다')
    print(f'{name}의 점수는 {score}점입니다.')

try-except 예제

people = [
    {'name': 'bob', 'age': 20},
    {'name': 'carry', 'age': 38},
    {'name': 'john', 'age': 7},
    {'name': 'smith', 'age': 17},
    {'name': 'ben', 'age': 27},
    {'name': 'bobby'},
    {'name': 'bobby', 'age': 57},
    {'name': 'red', 'age': 32},
    {'name': 'queen', 'age': 25}
]

for person in people:
    try:
        if person['age'] > 20:
            print(person['name'])
    except:
        print(person['name'], '에러입니다')

 

파일 불러오기

from main_func import *

say_hi()
say_hi_to('영수')
def say_hi():
    print('안녕!')

def say_hi_to(name):
    print(f'{name}님 안녕하세요')

if문 삼항연산자

num = 3
result = ('짝수' if num % 2 == 0 else '홀수')
print(f'{num}은 {result}입니다.')

반복문

a_list = [1,2,2,5,1,2]
b_list = [a*2 for a in a_list]
print(b_list)

 

map, filter, lamda식

people = [
    {'name': 'bob', 'age': 20},
    {'name': 'carry', 'age': 38},
    {'name': 'john', 'age': 7},
    {'name': 'smith', 'age': 17},
    {'name': 'ben', 'age': 27},
    {'name': 'bobby', 'age': 57},
    {'name': 'red', 'age': 32},
    {'name': 'queen', 'age': 25}
]

def check_adult(person):
    return ('성인' if person['age'] > 20 else '청소년')

#맵
result = map(check_adult, people)

#람다
result = map(lambda person: ('성인' if person['age']>20 else '청소년'), people)

#필터
result = filter(lambda person: person['age']>20, people)

print(list(result))

클래스

class Monster():
    hp = 100
    alive = True

    def damge(self, attack):
        self.hp = self.hp - attack
        if self.hp < 0 :
            self.alive = False

    def status_check(self):
        if self.alive:
            print('살았다')
        else:
            print('죽었다')

m1 = Monster()
m1.damge(120)
m1.status_check()

m2 = Monster()
m2.damge(90)
m2.status_check()

 

728x90
반응형

'코딩공부 > 파이썬' 카테고리의 다른 글

파이썬 코딩 무료강의 (조코딩)  (0) 2022.11.16
[3] 팬사이트(팬명록) 만들기 퀴즈  (0) 2022.10.26
[2] 영화 감상평 사이트  (0) 2022.10.26
[1] 화성땅 공동구매 프로젝트  (0) 2022.10.26
monggoDB 기초  (0) 2022.10.23
728x90
반응형

자료형

 

자료에 대한 타입

숫자, 문자열, 불 

 

어떤 값을 담는 자료 구조

변수, 리스트, 튜플, 딕셔너리, 집합

 

숫자형

정수 int (1,2,-2)

실수 float (1.24, -34.56)

 

딕셔너리 개념

딕셔너리

 

연관배열 또는 해시(Hash)

Key를 통해 Value를 얻는다. ["이름" (Key) : "홍길동" (Value)]

 

 

728x90
반응형
728x90
반응형

app.py

from flask import Flask, render_template, request, jsonify
app = Flask(__name__)

from pymongo import MongoClient
client = MongoClient('mongodb+srv://text:sparta@cluster0.tvnfddc.mongodb.net/Cluster0?retryWrites=true&w=majority')
db = client.dbsparta

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

@app.route("/homework", methods=["POST"])
def homework_post():
    name_receive = request.form['name_give']
    comment_receive = request.form['comment_give']

    doc = {
        'name' : name_receive,
        'comment' : comment_receive
    }
    db.homework.insert_one(doc)

    return jsonify({'msg':'댓글 완료~!'})

@app.route("/homework", methods=["GET"])
def homework_get():
    homework_list = list(db.homework.find({}, {'_id': False}))
    return jsonify({'homework': homework_list})

if __name__ == '__main__':
   app.run('0.0.0.0', port=5000, debug=True)

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">

    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet"
        integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js"
        integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM"
        crossorigin="anonymous"></script>

    <title>🎻릴러말즈 팬사이트🎻</title>

    <link href="https://fonts.googleapis.com/css2?family=Noto+Serif+KR:wght@200;300;400;500;600;700;900&display=swap" rel="stylesheet">
    <style>
        * {
            font-family: 'Noto Serif KR', serif;
        }
        .mypic {
            width: 100%;
            height: 300px;

            background-image: linear-gradient(0deg, rgba(0, 0, 0, 0.5), rgba(0, 0, 0, 0.5)), url('https://mblogthumb-phinf.pstatic.net/MjAyMTEyMzBfMjU3/MDAxNjQwODIzNTM5ODU4.4N5iYjgtyzTpiKCe5RlPuNM5aRqP-rxu8Lv4M7PIYy8g.FYFlO1cup4cXoyBEgOtSEWpw_baR76D5h_JwiJdCQyIg.JPEG.letis_make_idea/asdasd.jpg?type=w800');
            background-position: center 30%;
            background-size: cover;

            color: white;

            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
        }

        .mypost {
            width: 95%;
            max-width: 500px;
            margin: 20px auto 20px auto;

            box-shadow: 0px 0px 3px 0px black;
            padding: 20px;
        }

        .mypost > button {
            margin-top: 15px;
        }

        .mycards {
            width: 95%;
            max-width: 500px;
            margin: auto;
        }

        .mycards > .card {
            margin-top: 10px;
            margin-bottom: 10px;
        }
    </style>
    <script>
        $(document).ready(function(){
            set_temp()
            show_comment()
        });
        function set_temp(){
            $.ajax({
                type: "GET",
                url: "http://spartacodingclub.shop/sparta_api/weather/seoul",
                data: {},
                success: function (response) {
                    $('#temp').text(response['temp'])
                }
            })
        }
        function save_comment(){
            let name = $('#name').val()
            let comment = $('#comment').val()

            $.ajax({
                type: 'POST',
                url: '/homework',
                data: { name_give:name, comment_give:comment},
                success: function (response) {
                    alert(response['msg'])
                    window.location.reload()
                }
            })
        }
        function show_comment(){
            $.ajax({
                type: "GET",
                url: "/homework",
                data: {},
                success: function (response) {
                    let rows = response['homework']
                    for ( i=0; i < rows.length; i++){
                        let name = rows[i]['name']
                        let comment = rows[i]['comment']

                        let temp_html = ` <div class="card">
                                            <div class="card-body">
                                                <blockquote class="blockquote mb-0">
                                                    <p>${comment}</p>
                                                    <footer class="blockquote-footer">${name}</footer>
                                                </blockquote>
                                            </div>
                                        </div>`
                        $('#comment-list').append(temp_html)
                    }
                }
            });
        }
    </script>
</head>
<body>
    <div class="mypic">
         <h1>🎻릴러말즈 팬사이트🎻</h1>
        <p>현재기온: <span id="temp">36</span>도</p>
    </div>
    <div class="mypost">
        <div class="form-floating mb-3">
            <input type="text" class="form-control" id="name" placeholder="url">
            <label for="floatingInput">닉네임</label>
        </div>
        <div class="form-floating">
            <textarea class="form-control" placeholder="Leave a comment here" id="comment"
                style="height: 100px"></textarea>
            <label for="floatingTextarea2">응원댓글</label>
        </div>
        <button onclick="save_comment()" type="button" class="btn btn-dark">응원 남기기</button>
    </div>
    <div class="mycards" id="comment-list">

    </div>
</body>
</html>
728x90
반응형
728x90
반응형

필요한 라이브러리

필요한 인터프리터

 

디렉토리 설정

 

app.py

from flask import Flask, render_template, request, jsonify
app = Flask(__name__)

import requests
from bs4 import BeautifulSoup

from pymongo import MongoClient
client = MongoClient('mongodb+srv://text:sparta@cluster0.tvnfddc.mongodb.net/Cluster0?retryWrites=true&w=majority')
db = client.dbsparta


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

@app.route("/movie", methods=["POST"])
def movie_post():
    url_receive = request.form['url_give']
    star_receive = request.form['star_give']
    comment_receive = request.form['comment_give']

    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64)AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.86 Safari/537.36'}
    data = requests.get(url_receive, headers=headers)

    soup = BeautifulSoup(data.text, 'html.parser')

    title = soup.select_one('meta[property="og:title"]')['content']
    image = soup.select_one('meta[property="og:image"]')['content']
    desc = soup.select_one('meta[property="og:description"]')['content']

    doc = {
        'title' : title,
        'image' : image,
        'desc' : desc,
        'star' : star_receive,
        'comment' : comment_receive
    }
    db.movies.insert_one(doc)

    return jsonify({'msg':'저장완료!'})

@app.route("/movie", methods=["GET"])
def movie_get():
    movie_list = list(db.movies.find({}, {'_id': False}))
    return jsonify({'movies':movie_list})

if __name__ == '__main__':
   app.run('0.0.0.0', port=5000, debug=True)

index.html

<!doctype html>
<html lang="en">

<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet"
          integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js"
            integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM"
            crossorigin="anonymous"></script>

    <title>스파르타 피디아</title>

    <link href="https://fonts.googleapis.com/css2?family=Gowun+Dodum&display=swap" rel="stylesheet">

    <style>
        * {
            font-family: 'Gowun Dodum', sans-serif;
        }

        .mytitle {
            width: 100%;
            height: 250px;

            background-image: linear-gradient(0deg, rgba(0, 0, 0, 0.5), rgba(0, 0, 0, 0.5)), url('https://movie-phinf.pstatic.net/20210715_95/1626338192428gTnJl_JPEG/movie_image.jpg');
            background-position: center;
            background-size: cover;

            color: white;

            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
        }

        .mytitle > button {
            width: 200px;
            height: 50px;

            background-color: transparent;
            color: white;

            border-radius: 50px;
            border: 1px solid white;

            margin-top: 10px;
        }

        .mytitle > button:hover {
            border: 2px solid white;
        }

        .mycomment {
            color: gray;
        }

        .mycards {
            margin: 20px auto 0px auto;
            width: 95%;
            max-width: 1200px;
        }

        .mypost {
            width: 95%;
            max-width: 500px;
            margin: 20px auto 0px auto;
            padding: 20px;
            box-shadow: 0px 0px 3px 0px gray;

            display: none;
        }

        .mybtns {
            display: flex;
            flex-direction: row;
            align-items: center;
            justify-content: center;

            margin-top: 20px;
        }
        .mybtns > button {
            margin-right: 10px;
        }
    </style>
    <script>
        $(document).ready(function(){
          listing();
        });

        function listing() {
            $('#cards-box').empty()
            $.ajax({
                type: 'GET',
                url: '/movie',
                data: {},
                success: function (response) {
                    let rows = response['movies']
                    for(let i = 0; i < rows.length; i++) {
                        let image = rows[i]['image']
                        let title = rows[i]['title']
                        let desc = rows[i]['desc']
                        let star = rows[i]['star']
                        let comment = rows[i]['comment']

                        let star_image = '⭐'.repeat(star)

                        let temp_html = `<div class="col">
                                            <div class="card h-100">
                                                <img src="${image}"
                                                     class="card-img-top">
                                                <div class="card-body">
                                                    <h5 class="card-title">${title}</h5>
                                                    <p class="card-text">${desc}</p>
                                                    <p>${star_image}</p>
                                                    <p class="mycomment">${comment}</p>
                                                </div>
                                            </div>
                                        </div>`

                        $('#cards-box').append(temp_html)
                    }
                }
            })
        }

        function posting() {
            let url = $('#url').val()
            let star = $('#star').val()
            let comment = $('#comment').val()

            $.ajax({
                type: 'POST',
                url: '/movie',
                data: {url_give: url, star_give: star, comment_give: comment},
                success: function (response) {
                    alert(response['msg'])
                    window.location.reload()
                }
            });
        }

        function open_box(){
            $('#post-box').show()
        }
        function close_box(){
            $('#post-box').hide()
        }
    </script>
</head>

<body>
<div class="mytitle">
    <h1>내 생애 최고의 영화들</h1>
    <button onclick="open_box()">영화 기록하기</button>
</div>
<div class="mypost" id="post-box">
    <div class="form-floating mb-3">
        <input id="url" type="email" class="form-control" placeholder="name@example.com">
        <label>영화URL</label>
    </div>
    <div class="input-group mb-3">
        <label class="input-group-text" for="inputGroupSelect01">별점</label>
        <select class="form-select" id="star">
            <option selected>-- 선택하기 --</option>
            <option value="1">⭐</option>
            <option value="2">⭐⭐</option>
            <option value="3">⭐⭐⭐</option>
            <option value="4">⭐⭐⭐⭐</option>
            <option value="5">⭐⭐⭐⭐⭐</option>
        </select>
    </div>
    <div class="form-floating">
        <textarea id="comment" class="form-control" placeholder="Leave a comment here"></textarea>
        <label for="floatingTextarea2">코멘트</label>
    </div>
    <div class="mybtns">
        <button onclick="posting()" type="button" class="btn btn-dark">기록하기</button>
        <button onclick="close_box()" type="button" class="btn btn-outline-dark">닫기</button>
    </div>
</div>
<div class="mycards">
    <div class="row row-cols-1 row-cols-md-4 g-4" id="cards-box">

    </div>
</div>
</body>

</html>

meta_prac.py

import requests
from bs4 import BeautifulSoup

url = 'https://movie.naver.com/movie/bi/mi/basic.naver?code=191597'

headers = {'User-Agent' : 'Mozilla/5.0 (Windows NT 10.0; Win64; x64)AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.86 Safari/537.36'}
data = requests.get(url,headers=headers)

soup = BeautifulSoup(data.text, 'html.parser')

title = soup.select_one('meta[property="og:title"]')['content']
image = soup.select_one('meta[property="og:image"]')['content']
desc = soup.select_one('meta[property="og:description"]')['content']
print(title,image,desc)
728x90
반응형
728x90
반응형

필요한 인터프리터

flask , pymongo, dnspython (설정-파이썬 인터프리터 -> (+) -> 설치)

필요한 인터프리터
디렉토리 설정

app.py

from flask import Flask, render_template, request, jsonify
app = Flask(__name__)

from pymongo import MongoClient
client = MongoClient('mongodb+srv://text:sparta@cluster0.tvnfddc.mongodb.net/Cluster0?retryWrites=true&w=majority')
db = client.dbsparta

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

@app.route("/mars", methods=["POST"])
def web_mars_post():
    name_receive = request.form['name_give']
    address_receive = request.form['address_give']
    size_receive = request.form['size_give']

    doc = {
        'name' :name_receive,
        'address' :address_receive,
        'size' :size_receive
    }
    db.mars.insert_one(doc)

    return jsonify({'msg' : '주문 완료!'})

    return jsonify({'msg': 'POST 연결 완료!'})

@app.route("/mars", methods=["GET"])
def web_mars_get():
    order_list = list(db.mars.find({}, {'_id' : False}))
    return jsonify({'orders': order_list})

if __name__ == '__main__':
   app.run('0.0.0.0', port=5000, debug=True)

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">

    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet"
        integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js"
        integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM"
        crossorigin="anonymous"></script>

    <link href="https://fonts.googleapis.com/css2?family=Gowun+Batang:wght@400;700&display=swap" rel="stylesheet">

    <title>선착순 공동구매</title>

    <style>
        * {
            font-family: 'Gowun Batang', serif;
            color: white;
        }

        body {
            background-image: linear-gradient(0deg, rgba(0, 0, 0, 0.5), rgba(0, 0, 0, 0.5)), url('https://cdn.aitimes.com/news/photo/202010/132592_129694_3139.jpg');
            background-position: center;
            background-size: cover;
        }

        h1 {
            font-weight: bold;
        }

        .order {
            width: 500px;
            margin: 60px auto 0px auto;
            padding-bottom: 60px;
        }

        .mybtn {
            width: 100%;
        }

        .order > table {
            margin : 40px 0;
            font-size: 18px;
        }

        option {
            color: black;
        }
    </style>
    <script>
        $(document).ready(function () {
            show_order();
        });
        function show_order() {
            $.ajax({
                type: 'GET',
                url: '/mars',
                data: {},
                success: function (response) {
                    let rows = response['orders']
                    for (let i = 0; i < rows.length; i++){
                        let name = rows[i]['name']
                        let address = rows[i]['address']
                        let size = rows[i]['size']

                        let temp_html = `<tr>
                                            <th scope="col">${name}</th>
                                            <th scope="col">${address}</th>
                                            <th scope="col">${size}</th>
                                          </tr>`
                        $('#order-box').append(temp_html)
                    }
                }
            });
        }
        function save_order() {
            let name = $('#name').val()
            let address = $('#address').val()
            let size = $('#size').val()

            $.ajax({
                type: 'POST',
                url: '/mars',
                data: { name_give: name , address_give : address, size_give: size },
                success: function (response) {
                    alert(response['msg'])
                    window.location.reload()
                }
            });
        }
    </script>
</head>
<body>
    <div class="mask"></div>
    <div class="order">
        <h1>화성에 땅 사놓기!</h1>
        <h3>가격: 평 당 500원</h3>
        <p>
            화성에 땅을 사둘 수 있다고?<br/>
            앞으로 백년 간 오지 않을 기회. 화성에서 즐기는 노후!
        </p>
        <div class="order-info">
            <div class="input-group mb-3">
                <span class="input-group-text">이름</span>
                <input id="name" type="text" class="form-control">
            </div>
            <div class="input-group mb-3">
                <span class="input-group-text">주소</span>
                <input id="address" type="text" class="form-control">
            </div>
            <div class="input-group mb-3">
                <label class="input-group-text" for="size">평수</label>
                <select class="form-select" id="size">
                  <option selected>-- 주문 평수 --</option>
                  <option value="10평">10평</option>
                  <option value="20평">20평</option>
                  <option value="30평">30평</option>
                  <option value="40평">40평</option>
                  <option value="50평">50평</option>
                </select>
              </div>
              <button onclick="save_order()" type="button" class="btn btn-warning mybtn">주문하기</button>
        </div>
        <table class="table">
            <thead>
              <tr>
                <th scope="col">이름</th>
                <th scope="col">주소</th>
                <th scope="col">평수</th>
              </tr>
            </thead>
            <tbody id="order-box">

            </tbody>
          </table>
    </div>
</body>
</html>
728x90
반응형

'코딩공부 > 파이썬' 카테고리의 다른 글

[3] 팬사이트(팬명록) 만들기 퀴즈  (0) 2022.10.26
[2] 영화 감상평 사이트  (0) 2022.10.26
monggoDB 기초  (0) 2022.10.23
파이썬 크롤링(requests 라이브러리)  (0) 2022.10.23
파이썬 함수  (0) 2022.10.23
728x90
반응형

기초 코드

from pymongo import MongoClient
client = MongoClient('mongodb+srv://text:sparta@cluster0.tvnfddc.mongodb.net/Cluster0?retryWrites=true&w=majority')
db = client.dbsparta

 

# 저장 - 예시
doc = {'name':'bobby','age':21}
db.users.insert_one(doc)

# 한 개 찾기 - 예시
user = db.users.find_one({'name':'bobby'})

# 여러개 찾기 - 예시 ( _id 값은 제외하고 출력)
all_users = list(db.users.find({},{'_id':False}))

# 바꾸기 - 예시
db.users.update_one({'name':'bobby'},{'$set':{'age':19}})

# 지우기 - 예시
db.users.delete_one({'name':'bobby'})

 

첫단계 데이터 쌓기

from pymongo import MongoClient
client = MongoClient('mongodb+srv://text:sparta@cluster0.tvnfddc.mongodb.net/Cluster0?retryWrites=true&w=majority')
db = client.dbsparta

doc = {
    'name' : 'bob',
    'age' : 27
}

db.users.insert_one(doc)

유저 리스트 부르기

from pymongo import MongoClient
client = MongoClient('mongodb+srv://text:sparta@cluster0.tvnfddc.mongodb.net/Cluster0?retryWrites=true&w=majority')
db = client.dbsparta

all_users = list(db.users.find({},{'_id':False}))

for user in all_users:
    print(user)
728x90
반응형
728x90
반응형

Requests

import requests # requests 라이브러리 설치 필요

r = requests.get('http://spartacodingclub.shop/sparta_api/seoulair')
rjson = r.json()

rows = rjson['RealtimeCityAir']['row']

for row in rows:
    gu_name = row['MSRSTE_NM']
    gu_mise = row['IDEX_MVL']
    if gu_mise < 60:
        print(gu_name)

Requests + bs4 조합 기본코드

 

import requests
from bs4 import BeautifulSoup

headers = {'User-Agent' : 'Mozilla/5.0 (Windows NT 10.0; Win64; x64)AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.86 Safari/537.36'}
data = requests.get('https://movie.naver.com/movie/sdb/rank/rmovie.naver?sel=pnt&date=20210829',headers=headers)

soup = BeautifulSoup(data.text, 'html.parser')

print (soup)

크롤링 예제1

import requests
from bs4 import BeautifulSoup

headers = {'User-Agent' : 'Mozilla/5.0 (Windows NT 10.0; Win64; x64)AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.86 Safari/537.36'}
data = requests.get('https://movie.naver.com/movie/sdb/rank/rmovie.naver?sel=pnt&date=20210829',headers=headers)

soup = BeautifulSoup(data.text, 'html.parser')

#old_content > table > tbody > tr:nth-child(2) > td.title > div > a

movies = soup.select('#old_content > table > tbody > tr')

for moive in movies:
    a = moive.select_one('td.title > div > a')
    if a is not None:
        print(a.text)

크롤링 예제2

import requests
from bs4 import BeautifulSoup

headers = {'User-Agent' : 'Mozilla/5.0 (Windows NT 10.0; Win64; x64)AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.86 Safari/537.36'}
data = requests.get('https://movie.naver.com/movie/sdb/rank/rmovie.naver?sel=pnt&date=20210829',headers=headers)

soup = BeautifulSoup(data.text, 'html.parser')

#old_content > table > tbody > tr:nth-child(2) > td.title > div > a

#old_content > table > tbody > tr:nth-child(2) > td:nth-child(1) > img
#old_content > table > tbody > tr:nth-child(3) > td:nth-child(1) > img

#old_content > table > tbody > tr:nth-child(2) > td.point
#old_content > table > tbody > tr:nth-child(9) > td.point

movies = soup.select('#old_content > table > tbody > tr')

for moive in movies:
    a = moive.select_one('td.title > div > a')

    if a is not None:
        title = a.text
        rank = moive.select_one('td:nth-child(1) > img')['alt']
        star = moive.select_one('td.point').text
        print(rank, title, star)
728x90
반응형

'코딩공부 > 파이썬' 카테고리의 다른 글

[3] 팬사이트(팬명록) 만들기 퀴즈  (0) 2022.10.26
[2] 영화 감상평 사이트  (0) 2022.10.26
[1] 화성땅 공동구매 프로젝트  (0) 2022.10.26
monggoDB 기초  (0) 2022.10.23
파이썬 함수  (0) 2022.10.23
728x90
반응형

함수

def sum(a,b) :
    print('더하자!')
    return a+b

result = sum(1,2)
print(result)

조건문

def is_adult(age):
    if age > 20:
        print('성인입니다')
    else:
        print('청소년입니다')

is_adult(15)

반복문 (리스트예제)

fruits = ['사과','배','배','감','수박','귤','딸기','사과','배','수박']

count = 0
for fruit in fruits:
    if fruit == '사과':
        count += 1

print(count)

반복문 (딕셔너리예제)

people = [{'name': 'bob', 'age': 20}, 
          {'name': 'carry', 'age': 38},
          {'name': 'john', 'age': 7},
          {'name': 'smith', 'age': 17},
          {'name': 'ben', 'age': 27}]

for person in people:
    if person['age'] > 20:
        print(person['name'])
728x90
반응형

+ Recent posts