openweathermap.org/

 

Сurrent weather and forecast - OpenWeatherMap

Access current weather data for any location on Earth including over 200,000 cities! The data is frequently updated based on global and local weather models, satellites, radars and vast network of weather stations. how to obtain APIs (subscriptions with di

openweathermap.org

API 들어가기, currnet weather 했음 

 

첫번째 copy 

 

api.openweathermap.org/data/2.5/weather?q=daegu&appid={API key}

 

-터미널 설치 

pip install requests

 

 

- app.py 

추가 

@app.route('/')
def home():
    city = 'daegu'
    appid = 'e5d4ba22d1c0aae4130753ea87c69eec'
    url = f'http://api.openweathermap.org/data/2.5/weather?q={city}&appid={appid}'
    res = requests.get(url)
    # weather_data = json.loads(res.text)
    weather_data = res.json()

    description = weather_data["weather"][0]["description"]
    icon = weather_data["weather"][0]["icon"]
    temp = weather_data["main"]["temp"] - 273
    temp = round(temp, 1)
    return render_template('index.html', description=description, icon=icon, temp=temp)


@app.route('/weather', methods=['GET'])
def weather():
    city = 'daegu'
    appid = 'e5d4ba22d1c0aae4130753ea87c69eec'
    url = f'http://api.openweathermap.org/data/2.5/weather?q={city}&appid={appid}'
    res = requests.get(url)
    weather_data = res.json()

    print("weather_data: ", weather_data)
    print("날씨: ", weather_data["weather"][0]["description"])

    description = weather_data["weather"][0]["description"]
    icon = weather_data["weather"][1]["icon"]

    print("온도: ", weather_data["main"]["temp"]-273)
    temp = weather_data["main"]["temp"] - 273
    return render_template('weather.html', description=description, icon=icon, temp=temp)

 

- weather.html

{%  extends "layout.html" %}

{% block content %}
    <div class="weather box_shadow" style="width:250px;">
     <div style="display: block">
         {{ description }}
     </div>
     <div style="display: inline-block; ">
        <img src="http://openweathermap.org/img/wn/{{ icon }}@2x.png">
     </div>
     <div class="weather_body" style="display: block;">
      <div class="temp" style="display: block;">
        {{temp}}&deg;
      </div>
     </div>
    </div>

{%  endblock %}

 

-index.html

{% extends "layout.html" %}


{% block title %}
    홈
{% endblock %}

{% block weather %}
    <img src="http://openweathermap.org/img/wn/{{ icon }}@2x.png">
    {{ description }}
    {{ temp }}&deg;
{% endblock %}

{% block content %}
<div class="jumbotron">
  <h1 class="display-4">MongoDB 프로젝트</h1>
  <p class="lead">
      This is a simple hero unit, a simple jumbotron-style component for calling extra attention to featured content or information.</p>
  <hr class="my-4">
    <ul>
        <li>
            flask 기반의 MongoDB 관리 시스템 입니다.
        </li>
        <li>
            flask 기반의 MongoDB 관리 시스템 입니다.
        </li>
    </ul>
</div>
{% endblock %}

- app.py 

import base64
import random
from bson import ObjectId
from flask import Flask, render_template, request
from pymongo import MongoClient
from datetime import datetime

app = Flask(__name__)


class MyMongoClient():
    def __init__(self):
        self.client = MongoClient()
        self.database = self.client["ok-db"]
        self.collection = self.database["books"]


@app.route('/')
def hello_world():

    return render_template('index.html')


@app.route('/card', methods=['GET'])
def card():
    return render_template('card.html')


@app.route('/book_add', methods=['GET'])
def book_add():
    return render_template('book_add.html')


@app.route('/book_add_process', methods=['POST'])
def book_add_process():
    # client = MongoClient("mongodb://localhost:27017/")
    # database = client["ok-db"]
    # collection = database["books"]

    myclient = MyMongoClient()
    title = request.form['title']
    file = request.files['file']
    author = request.form['author']
    price = request.form['price']
    isbn = request.form['isbn']
    encoded_data = base64.b64encode(file.read())

    if encoded_data == bytes(0):
        doc = {'title': title, 'author': author, 'isbn': isbn,
               'price': price, 'created_date': datetime.now()}
    else:
        doc = {'title': title, 'encoded_data': encoded_data, 'author': author, 'isbn': isbn,
               'price': price, 'created_date': datetime.now()}

    #result = collection.insert_one(doc)
    result = myclient.collection.insert_one(doc)

    book_add_result = None
    if result.inserted_id is not None:
        print(result.inserted_id)
        book_add_result = "정상 등록"
    else:
        book_add_result = "등록 실패"

    return render_template('book_add_result.html',
                           book_add_result=book_add_result)


@app.route('/book_search', methods=['GET'])
def book_search():
    return render_template('book_search.html')


@app.route('/book_search_process', methods=['POST'])
def book_search_process():
    item = request.form['item_to_search']
    data = request.form['data_to_search']

    myclient = MyMongoClient()
    if item == 'id':
        query = {'_id': data}
    elif item == 'title':
        query = {'title': data}

    books = myclient.collection.find(query)

    return render_template('book_search_process_result.html', books=books)


@app.route('/book_id_search', methods=['GET'])
def book_id_search():
    return render_template('book_id_search.html')


@app.route('/book_id_search_process', methods=['POST'])
def book_id_search_process():
    # client = MongoClient()
    # database = client["ok-db"]
    # collection = database["books"]
    search = request.form['search']

    myclient = MyMongoClient()
    _id = request.form['id']

    query = {'_id': ObjectId(_id)}
    doc = myclient.collection.find_one(query)
    title = doc['title']
    decoded_data = doc['encoded_data'].decode('utf-8')
    img_src_data = f'data:image/png;base64, {decoded_data}'

    return render_template('book_id_search_result.html', title=title, img_src_data=img_src_data)


@app.route('/book_list', methods=['GET'])
def book_list():
    # client = MongoClient("mongodb://localhost:27017/")
    # database = client["ok-db"]
    # collection = database["books"]
    myclient = MyMongoClient()
    total_count = myclient.collection.find().count()

    books = myclient.collection.find()

    return render_template('book_list.html',
                           books=books, total_count=total_count)


@app.route('/book_details/<_id>', methods=['GET'])
def book_details(_id=None):
    print(_id)
    return render_template('book_details.html')


@app.route('/newgugu', methods=['GET', 'POST'])
def newgugu():
    gugu_list = []
    if request.method == 'POST':
        dan = int(request.form['dan'])

        for i in range(1, 10):
            gugu = f'{dan} × {i} = {dan * i}'
            gugu_list.append(gugu)
        return render_template('newgugu.html', gugu_list=gugu_list)
    else:
        return render_template('newgugu.html')


@app.route('/gugudan', methods=['GET'])
def gugudan():
    dan = 5
    gugu_list = [] # list()
    for i in range(1, 10):
        gugu = f'{dan} × {i} = {dan * i}'
        gugu_list.append(gugu)

    return render_template('gugudan.html', gugu_list=gugu_list)


@app.route('/jiji', methods=['GET', 'POST'])
def jiji():
    if request.method == 'POST':
        year = int(request.form['year'])
        jiji_list = ['자', '축', '인', '묘', '진', '사', '오', '미', '신', '유', '술', '해']
        jiji_index = (year - 4) % 12
        jiji = jiji_list[jiji_index]

    else:
        jiji = None
    return render_template('jiji.html', jiji=jiji)


@app.route('/game', methods=['GET'])
def game():
    my_list = ['1-1', '1-2', '2-1', '2-2', '3-1', '3-2', '4-1', '4-2', '5-1', '5-2',
               '6-1', '6-2', '7-1', '7-2', '8-1', '8-2', '9-1', '9-2', '10-1', '10-2'
    ]
    random.shuffle(my_list)
    selected_list = my_list[0:4]

    my_sum = int(selected_list[0].split('-')[0]) + int(selected_list[1].split('-')[0])
    computer_sum = int(selected_list[2].split('-')[0]) + int(selected_list[3].split('-')[0])
    my = my_sum % 10
    computer = computer_sum % 10

    # 판정
    winner = None
    if my > computer:
        winner = '내가 이겼다'
    elif my == computer:
        winner = '무승부'
    else:
        winner = '컴퓨터가 이겼다'

    return render_template('game.html',
                           selected_list=selected_list, winner=winner)

if __name__ == '__main__':
    #app.run(host='0.0.0.0', port=9900)
    app.run()

 

- book_search.html

{% extends "layout.html" %}

{% block content %}
<form action="/book_search_process" method="post">

    검색할 항목 선택:
    <select name="item_to_search" id="item_to_search">

        <option value="id">id</option>
        <option value="title">서적 제목</option>
        <option value="author">저자 명</option>
        <option value="published_date">출간일자</option>
        <option value="isbn">ISBN</option>
        <option value="created_date">등록일자</option>
    </select>

    <input type="text" name="data_to_search">
    <input type="submit" value="검 색">

</form>
{% endblock %}

 

-book_search_process_result.html 

{% extends "layout.html" %}

{% block content %}

{% endblock %}

 

-index.html

{% extends "layout.html" %}

{% block title %}
    홈
{% endblock %}

{% block content %}
{% with messages = get_flashed_messages(with_categories=true) %}
  {% if messages %}
    <ul class=flashes>
    {% for category, message in messages %}
      <li class="{{ category }}">{{ message }}</li>
    {% endfor %}
    </ul>
  {% endif %}
{% endwith %}

<div class="jumbotron">
  <h1 class="display-4">MongoDB 프로젝트</h1>
  <p class="lead">
      This is a simple hero unit, a simple jumbotron-style component for calling extra attention to featured content or information.</p>
  <hr class="my-4">
    <ul>
        <li>
            flask 기반의 MongoDB 관리 시스템 입니다.
        </li>
        <li>
            flask 기반의 MongoDB 관리 시스템 입니다.
        </li>
    </ul>
</div>
{% endblock %}

 

- layout.html

<!DOCTYPE html>
<html lang="ko">
<head>
    <meta charset="UTF-8">
    <title>
        {% block title %}
        {% endblock %}
    </title>

    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.0/dist/css/bootstrap.min.css" integrity="sha384-B0vP5xmATw1+K9KRQjQERJvTumQW0nPEzvF6L/Z6nronJ3oUOFUFpCjEUQouq2+l" crossorigin="anonymous">
    <style>
        body {
            font-family: '맑은고딕', 'Margun Gothic';
        }
        .top {
            width: 100%;
            height: 40px;
            background-image: url("../static/image/background-image.jpg");
        }

    </style>
</head>
<body>
<div class="top">

</div>
<nav class="navbar navbar-expand-lg navbar-light bg-light">
  <a class="navbar-brand" href="#">mongodb 프로젝트</a>
  <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
    <span class="navbar-toggler-icon"></span>
  </button>

  <div class="collapse navbar-collapse" id="navbarSupportedContent">
    <ul class="navbar-nav mr-auto">
      <li class="nav-item active">
        <a class="nav-link" href="#">Home <span class="sr-only">(current)</span></a>
      </li>
      <li class="nav-item">
        <a class="nav-link" href="#">Link</a>
      </li>
      <li class="nav-item dropdown">
        <a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
          서적 관리
        </a>
        <div class="dropdown-menu" aria-labelledby="navbarDropdown">
          <a class="dropdown-item" href="/book_add">등록</a>
          <a class="dropdown-item" href="/book_list">전체 조회</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="#">Something else here</a>
        </div>
      </li>
        <li class="nav-item dropdown">
        <a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
          서적 검색
        </a>
        <div class="dropdown-menu" aria-labelledby="navbarDropdown">
          <a class="dropdown-item" href="/book_search">검색</a>
          <a class="dropdown-item" href="/book_list">전체 조회</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="#">Something else here</a>
        </div>
      </li>
    </ul>
  </div>
</nav>

<div class="container" style="margin-top: 20px">
    <div id="current_datetime" align="right"></div>
    {% block content %}
    <!-- 여기는 콘텐츠가 replace -->
    {% endblock %}
</div>

<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.1/dist/umd/popper.min.js" integrity="sha384-9/reFTGAW83EW2RDu2S0VKaIzap3H66lZH81PoYlFhbGU+6BZp6G7niu735Sk7lN" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@4.6.0/dist/js/bootstrap.min.js" integrity="sha384-+YQ4JLhjyBLPDQt//I+STsc9iw4uQqACwlvpslubQzn4u2UU2UFM80nGisd026JF" crossorigin="anonymous"></script>

</body>
</html>

    <script>
        function current_datetime() {
            var today = new Date();
            var year = today.getFullYear()
            var month = today.getMonth() + 1
            var day = today.getDate()

            var hh = today.getHours();
            var mi = today.getMinutes();
            var ss = today.getSeconds();

        document.getElementById("current_datetime").innerHTML = year + '-'
        + month + '-' + day + ' ' + hh + ':' + mi + ':' + ss
        }Z


    setInterval(current_datetime,1000);
    </script>

- 아틀라스 연동 

 

copy

 

- 파이참에서 

파일 만들었음 

 

mongodb+srv://jinhae:qscft7259*@jinhae-cluster.lsfcp.mongodb.net/jinhae-db?retryWrites=true&w=majority

 

-터미널에서 설치 

pip install dnspython

 

-app.py 에 추가 

@app.route('/atlas_connect_info')
def atlas_connect_info():
    filename = 'atlas_connect_info.txt'
    with open(filename, encoding='utf-8') as f:
        atlas_connection_info = f.read()
    return render_template('atlas_connect_info.html',
                           atlas_connection_info=atlas_connection_info)

 

-layout.html  

수정 

<a class="dropdown-item" href="/atlas_connect_info">atlas 접속 정보</a>

 

- atlas_connect_info.html 

{% extends "layout.html" %}

{% block content %}
<form action="/atlas_connect_info_update" method="post">
  <div class="mb-3">
    <label for="atlas_connect_info" class="form-label">atlas 접속 정보:</label>
    <input type="text" value="{{ atlas_connection_info }}" class="form-control" id="atlas_connect_info" name="atlas_connect_info" aria-describedby="emailHelp">
    <div id="atlas_connect_info_Help" class="form-text">atlas 원격 접속 정보입니다.</div>
  </div>

  <button type="submit" class="btn btn-outline-secondary">저 장</button>
</form>

{% endblock content %}

 

- atlas_connect_info_update_result.html 

{% extends "layout.html" %}

{% block content %}

    결과

{% endblock content %}

 

 

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

(ip는 cmd창에서 ipconfig하고 확인하면 됨) 

 

- ip:포트번호 치면 홈페이지 뜸 

 

getbootstrap.com/

 

Bootstrap

The most popular HTML, CSS, and JS library in the world.

getbootstrap.com

Previous releases 클릭

 

- 4.6이 정식으로 나온 최신 버전이라서 사용했음 

4.6 눌렀음 

getbootstrap.com/docs/4.6/getting-started/introduction/

 

 

Introduction

Get started with Bootstrap, the world’s most popular framework for building responsive, mobile-first sites, with jsDelivr and a template starter page.

getbootstrap.com

-

CSS copy함
밑으로 내려서 Separate copy함

- CDN 방식 

인터넷에서 연결 

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.0/dist/css/bootstrap.min.css" integrity="sha384-B0vP5xmATw1+K9KRQjQERJvTumQW0nPEzvF6L/Z6nronJ3oUOFUFpCjEUQouq2+l" crossorigin="anonymous">

 

- Separate copy 

<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.1/dist/umd/popper.min.js" integrity="sha384-9/reFTGAW83EW2RDu2S0VKaIzap3H66lZH81PoYlFhbGU+6BZp6G7niu735Sk7lN" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@4.6.0/dist/js/bootstrap.min.js" integrity="sha384-+YQ4JLhjyBLPDQt//I+STsc9iw4uQqACwlvpslubQzn4u2UU2UFM80nGisd026JF" crossorigin="anonymous"></script>

 

 

- Search 에서 검색가능 

 

 

-button 검색하면 

copy 하기 

 <button type="button" class="btn btn-primary">Primary</button>
 <button type="button" class="btn btn-secondary">Secondary</button>
 <button type="button" class="btn btn-success">Success</button>
 <button type="button" class="btn btn-danger">Danger</button>
 <button type="button" class="btn btn-warning">Warning</button>
 <button type="button" class="btn btn-info">Info</button>
 <button type="button" class="btn btn-light">Light</button>
 <button type="button" class="btn btn-dark">Dark</button>
 <button type="button" class="btn btn-link">Link</button>

 

- html 파일 실행하면 

<!DOCTYPE html>
<html>
    <head>
        <title>
            제목
        </title>
        <meta charset="utf-8">

        <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.0/dist/css/bootstrap.min.css" integrity="sha384-B0vP5xmATw1+K9KRQjQERJvTumQW0nPEzvF6L/Z6nronJ3oUOFUFpCjEUQouq2+l" crossorigin="anonymous">

    </head>
    <body>
        <button type="button" class="btn btn-primary">Primary</button>
        <button type="button" class="btn btn-secondary">Secondary</button>
        <button type="button" class="btn btn-success">Success</button>
        <button type="button" class="btn btn-danger">Danger</button>
        <button type="button" class="btn btn-warning">Warning</button>
        <button type="button" class="btn btn-info">Info</button>
        <button type="button" class="btn btn-light">Light</button>
        <button type="button" class="btn btn-dark">Dark</button>
        <button type="button" class="btn btn-link">Link</button>



<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.1/dist/umd/popper.min.js" integrity="sha384-9/reFTGAW83EW2RDu2S0VKaIzap3H66lZH81PoYlFhbGU+6BZp6G7niu735Sk7lN" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@4.6.0/dist/js/bootstrap.min.js" integrity="sha384-+YQ4JLhjyBLPDQt//I+STsc9iw4uQqACwlvpslubQzn4u2UU2UFM80nGisd026JF" crossorigin="anonymous"></script>

    </body>
</html>

이렇게 뜸 

 

-navar 검색 

copy 

-html 파일 실행해보면 

<!DOCTYPE html>
<html>
    <head>
        <title>
            제목
        </title>
        <meta charset="utf-8">

        <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.0/dist/css/bootstrap.min.css" integrity="sha384-B0vP5xmATw1+K9KRQjQERJvTumQW0nPEzvF6L/Z6nronJ3oUOFUFpCjEUQouq2+l" crossorigin="anonymous">

    </head>
    <body>
        <nav class="navbar navbar-expand-lg navbar-light bg-light">
            <a class="navbar-brand" href="#">Navbar</a>
            <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
              <span class="navbar-toggler-icon"></span>
            </button>
          
            <div class="collapse navbar-collapse" id="navbarSupportedContent">
              <ul class="navbar-nav mr-auto">
                <li class="nav-item active">
                  <a class="nav-link" href="#">Home <span class="sr-only">(current)</span></a>
                </li>
                <li class="nav-item">
                  <a class="nav-link" href="#">Link</a>
                </li>
                <li class="nav-item dropdown">
                  <a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
                    Dropdown
                  </a>
                  <div class="dropdown-menu" aria-labelledby="navbarDropdown">
                    <a class="dropdown-item" href="#">Action</a>
                    <a class="dropdown-item" href="#">Another action</a>
                    <div class="dropdown-divider"></div>
                    <a class="dropdown-item" href="#">Something else here</a>
                  </div>
                </li>
                <li class="nav-item">
                  <a class="nav-link disabled" href="#" tabindex="-1" aria-disabled="true">Disabled</a>
                </li>
              </ul>
              <form class="form-inline my-2 my-lg-0">
                <input class="form-control mr-sm-2" type="search" placeholder="Search" aria-label="Search">
                <button class="btn btn-outline-success my-2 my-sm-0" type="submit">Search</button>
              </form>
            </div>
          </nav>



<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.1/dist/umd/popper.min.js" integrity="sha384-9/reFTGAW83EW2RDu2S0VKaIzap3H66lZH81PoYlFhbGU+6BZp6G7niu735Sk7lN" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@4.6.0/dist/js/bootstrap.min.js" integrity="sha384-+YQ4JLhjyBLPDQt//I+STsc9iw4uQqACwlvpslubQzn4u2UU2UFM80nGisd026JF" crossorigin="anonymous"></script>

    </body>
</html>

 

이렇게 뜸 

 


 

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title>
        </title>

    </head>
    <body>
        <ul> <!--unordered list --> 
            <li>
                사과
            </li>
            <li>
                배
            </li>
            <li>
                포도
            </li>
        </ul>
        <ol> <!--ordered list, 순서가 있음 --> 
            <li>
                사과
            </li>
            <li>
                배
            </li>
            <li>
                포도
            </li>
        </ol>
    </body>
</html>

 

- jumbotron  : 주로 제목 

- form 

- grid: 화면 조정, 길이 줄이기 

 

 

- index.html, book_add.html, book_list.html -> 수정,  layout.html(추가)

  index.html

{% extends "layout.html" %}


{% block content %}
<div class="jumbotron">
  <h1 class="display-4">MongoDB 프로젝트</h1>
  <p class="lead">
      This is a simple hero unit, a simple jumbotron-style component for calling extra attention to featured content or information.</p>
  <hr class="my-4">
    <ul>
        <li>
            flask 기반의 MongoDB 관리 시스템 입니다.
        </li>
        <li>
            flask 기반의 MongoDB 관리 시스템 입니다.
        </li>
    </ul>
</div>
{% endblock %}

 

book_add.html

{% extends "layout.html" %}

{% block content %}
<form action="/book_add_process" method="post" enctype="multipart/form-data">
<form>
  <div class="form-group col col-lg-8">
    <label for="title">제 목</label>
    <input type="text" class="form-control" id="title" name="title" placeholder="서적 제목 입력...">
  </div>
  <div class="form-group col col-lg-8">
    <label for="file">표 지</label>
    <input type="file" class="form-control" id="file" name="file" placeholder="표지 사진 선택...">
  </div>
  <div class="form-group col col-lg-8">
    <label for="author">저 자</label>
    <input type="text" class="form-control" id="author" name="author" placeholder="저자명 입력...">
  </div>
  <div class="form-group col col-lg-8">
    <label for="author">price</label>
    <input type="text" class="form-control" id="price" name="price" placeholder="가격 입력...">
  </div>
  <div class="form-group col col-lg-8">
    <label for="isbn">ISBN</label>
    <input type="text" class="form-control" id="isbn" name="isbn" placeholder="isbn 입력...">
  </div>
  <div class="form-group">
    <button type="submit" class="btn btn-outline-secondary">등 록</button>
  </div>
</form>
</form>
{% endblock %}

 

book_list.html

{% extends "layout.html" %}

{% block content %}
    <h3>서적 목록</h3>
    <div style="width: 1000px">
        <div style="width: 1000px; text-align: right">
        {{ total_count }}건 검색됨
        </div>
        <table class="table table-bordered table-hover">
            <tr>
                <td>_id</td>
                <td>제목</td>
                <td>표지</td>
                <td>저자</td>
                <td>가격</td>
                <td>ISBN</td>
                <td>등록일자</td>

                <td>
                </td>
            </tr>
            {% for book in books %}
            <tr>
                <td>{{ book._id }}</td>
                <td><a href="/book_details/{{ book._id }}">{{ book.title }}</a></td>
                {% if book.encoded_data != null %}
                    <td><img width="80px" src="data:image/png;base64,{{ book.encoded_data.decode('utf-8') }}"></td>
                {% else %}
                    <td></td>
                {% endif %}
                <td>{{ book.author }}</td>
                <td>{{ book.price }}</td>
                <td>{{ book.isbn }}</td>
                <td>{{ book.created_date }}</td>
                <td>
                    <a href="/book_edit/{{ book._id }}"><input type="button" value="수정" class="btn btn-outline-secondary"></a>
                    <input type="button" value="삭제">
                </td>
            </tr>
            {% endfor %}
        </table>
    </div>
{% endblock %}

layout.html

 

<!DOCTYPE html>
<html lang="ko">
<head>
    <meta charset="UTF-8">
    <title>
        {% block title %}
        {% endblock %}
    </title>

    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.0/dist/css/bootstrap.min.css" integrity="sha384-B0vP5xmATw1+K9KRQjQERJvTumQW0nPEzvF6L/Z6nronJ3oUOFUFpCjEUQouq2+l" crossorigin="anonymous">
    <style>
        body {
            font-family: '맑은고딕', 'Margun Gothic';
        }
        .top {
            width: 100%;
            height: 40px;
            background-image: url("../static/image/background-image.jpg");
        }

    </style>
</head>
<body>
<div class="top">

</div>
<nav class="navbar navbar-expand-lg navbar-light bg-light">
  <a class="navbar-brand" href="#">mongodb 프로젝트</a>
  <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
    <span class="navbar-toggler-icon"></span>
  </button>

  <div class="collapse navbar-collapse" id="navbarSupportedContent">
    <ul class="navbar-nav mr-auto">
      <li class="nav-item active">
        <a class="nav-link" href="#">Home <span class="sr-only">(current)</span></a>
      </li>
      <li class="nav-item">
        <a class="nav-link" href="#">Link</a>
      </li>
      <li class="nav-item dropdown">
        <a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
          서적 관리
        </a>
        <div class="dropdown-menu" aria-labelledby="navbarDropdown">
          <a class="dropdown-item" href="/book_add">등록</a>
          <a class="dropdown-item" href="/book_list">전체 조회</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="#">Something else here</a>
        </div>
      </li>
    </ul>
  </div>
</nav>

<div class="container" style="margin-top: 40px">
    {% block content %}
    <!-- 여기는 콘텐츠가 replace -->
    {% endblock %}
</div>

<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.1/dist/umd/popper.min.js" integrity="sha384-9/reFTGAW83EW2RDu2S0VKaIzap3H66lZH81PoYlFhbGU+6BZp6G7niu735Sk7lN" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@4.6.0/dist/js/bootstrap.min.js" integrity="sha384-+YQ4JLhjyBLPDQt//I+STsc9iw4uQqACwlvpslubQzn4u2UU2UFM80nGisd026JF" crossorigin="anonymous"></script>
</body>
</html>

 

- 글꼴 바꾸기 

layout.html 에서 바꾸기

 

 

 

 

 

 

-db에 저장돼있어야함 

 

- app.py

import base64
import random
from bson import ObjectId
from flask import Flask, render_template, request
from pymongo import MongoClient
from datetime import datetime

app = Flask(__name__)


class MyMongoClient():
    def __init__(self):
        self.client = MongoClient()
        self.database = self.client["ok-db"]
        self.collection = self.database["books"]


@app.route('/')
def hello_world():
    name = '이미자'
    return render_template('index.html', name=name)


@app.route('/book_add', methods=['GET'])
def book_add():
    return render_template('book_add.html')


@app.route('/book_add_process', methods=['POST'])
def book_add_process():
    # client = MongoClient("mongodb://localhost:27017/")
    # database = client["ok-db"]
    # collection = database["books"]

    myclient = MyMongoClient()
    title = request.form['title']
    file = request.files['file']
    author = request.form['author']
    price = request.form['price']
    isbn = request.form['isbn']
    encoded_data = base64.b64encode(file.read())

    if encoded_data == bytes(0):
        doc = {'title': title, 'author': author, 'isbn': isbn,
               'price': price, 'created_date': datetime.now()}
    else:
        doc = {'title': title, 'encoded_data': encoded_data, 'author': author, 'isbn': isbn,
               'price': price, 'created_date': datetime.now()}

    #result = collection.insert_one(doc)
    result = myclient.collection.insert_one(doc)

    book_add_result = None
    if result.inserted_id is not None:
        print(result.inserted_id)
        book_add_result = "정상 등록"
    else:
        book_add_result = "등록 실패"

    return render_template('book_add_result.html',
                           book_add_result=book_add_result)


@app.route('/book_id_search', methods=['GET'])
def book_id_search():
    return render_template('book_id_search.html')


@app.route('/book_id_search_process', methods=['POST'])
def book_id_search_process():
    # client = MongoClient()
    # database = client["ok-db"]
    # collection = database["books"]
    myclient = MyMongoClient()
    _id = request.form['id']

    query = {'_id': ObjectId(_id)}
    doc = myclient.collection.find_one(query)
    title = doc['title']
    decoded_data = doc['encoded_data'].decode('utf-8')
    img_src_data = f'data:image/png;base64, {decoded_data}'

    return render_template('book_id_search_result.html', title=title, img_src_data=img_src_data)


@app.route('/book_list', methods=['GET'])
def book_list():
    # client = MongoClient("mongodb://localhost:27017/")
    # database = client["ok-db"]
    # collection = database["books"]
    myclient = MyMongoClient()
    total_count = myclient.collection.find().count()

    books = myclient.collection.find()

    return render_template('book_list.html',
                           books=books, total_count=total_count)


@app.route('/book_details/<_id>', methods=['GET'])
def book_details(_id=None):
    print(_id)
    return render_template('book_details.html')


if __name__ == '__main__':
    app.run()

 

 

-book_list.html 

<!DOCTYPE html>
<html lang="ko">
<head>
    <meta charset="UTF-8">
    <title>서적 목록</title>
</head>
<body>
    <h3>서적 목록</h3>
    <div style="width: 1000px">
        <div style="text-align:right">{{ total_count }}건 검색됨</div>
    <table  border="1" bordercolor="blue">
        <tr>
            <td>_id</td>
            <th>제목</th>
            <td>표지</td>
            <td>저자</td>
            <td>가격</td>
            <td>ISBN</td>
            <td>등록일자</td>

            <td>
            </td>
       </tr>
            {% for book in books %}
            <tr>
                <td>{{ book._id }}</td>
                <td><a href="/book_details/{{ book._id }}">{{ book.title }}</a></td>
                {% if book.encoded_data != None %}
                    <td><a href="/book_details/{{ book._id }}"><img width="40px" src="data:image/jpg;base64,{{ book.encoded_data.decode('utf-8') }}"></a></td>
                {% else %}
                    <td></td>
                {% endif %}
                <td></td>
                <td></td>
                <td></td>
                <td></td>
                <td>
                <!--<a href="/book_edit/{{ book._id }}"> <input type=button" value="수정"></a>-->
                <input type="button" value="수정">
                <input type="button" value="삭제">
            </td>

        </tr>
        {% endfor %}
    </table>
    </div>

</body>
</html>

 

-프로젝트 만들기 

new project
html file 만들기

 

 

 

 

-app.py

from flask import Flask, render_template

app = Flask(__name__)


@app.route('/')
def hello_world():
    name = '이미자'
    return render_template('index.html', name=name)


@app.route('/book_add', methods=['GET'])
def book_add():
    return render_template('book_add.html')


@app.route('/book_add_process', methods=['POST'])
def book_add_process():

    return render_template('book_add_result.html')


if __name__ == '__main__':
    app.run()

 

-index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <h3>안녕 {{ name }}</h3>

</body>
</html>

 

-book_add.html

<!DOCTYPE html>
<html lang="ko">
<head>
    <meta charset="UTF-8">
    <title>서적 등록</title>
</head>
<body>
<form action="/book_add_process" method="post">
    <table width='300px' border="1" bordercolor="'blue">
        <tr>
            <td>
                제목
            </td>
            <td>
                <input type="text" name="title">
            </td>
        </tr>
        <tr>
            <td>
                표지
            </td>
            <td>
                <input type="file" name="file">
            </td>
        </tr>
        <tr>
            <td>
                저자
            </td>
            <td>
                <input type="text" name="author">
            </td>
        </tr>
        <tr>
            <td>
                가격
            </td>
            <td>
                <input type="text" name="price">
            </td>
        </tr>
        <tr>
            <td>
                ISBN
            </td>
            <td>
                <input type="text" name="isbn">
            </td>
        </tr>
        <tr>
            <td colspan="2" align="center">
                <input type="submit" value="등 록">
            </td>

        </tr>
    </table>
</form>
</body>
</html>

 

-book_add_result.html

<!DOCTYPE html>
<html lang="ko">
<head>
    <meta charset="UTF-8">
    <title>서적 등록</title>
</head>
<body>
    서적 등록 결과
</body>
</html>

 


-mongodb 연동 

 

pip install pymongo
from pymongo import MongoClient

 

-book_add.html

<!DOCTYPE html>
<html lang="ko">
<head>
    <meta charset="UTF-8">
    <title>서적 등록</title>
</head>
<body>
<form action="/book_add_process" method="post" enctype="multipart/form-data">
    <table width="300px" border="1" bordercolor="blue">
        <tr>
            <td>
                제목
            </td>
            <td>
                <input type="text" name="title">
            </td>
        </tr>
        <tr>
            <td>
                표지
            </td>
            <td>
                <input type="file" name="file">
            </td>
        </tr>
         <tr>
            <td>
                저자
            </td>
            <td>
                <input type="text" name="author">
            </td>
        </tr>
         <tr>
            <td>
                가격
            </td>
            <td>
                <input type="text" name="price">
            </td>
        </tr>
         <tr>
            <td>
                ISBN
            </td>
            <td>
                <input type="text" name="isbn">
            </td>
        </tr>
         <tr>
            <td colspan="2" align="center">
                <input type="submit" value="등 록">
            </td>

        </tr>
    </table>
</form>
</body>
</html>

-app.py

import base64

from flask import Flask, render_template, request
from pymongo import MongoClient
from datetime import datetime

app = Flask(__name__)


@app.route('/')
def hello_world():
    name = '이미자'
    return render_template('index.html', name=name)


@app.route('/book_add', methods=['GET'])
def book_add():
    return render_template('book_add.html')


@app.route('/book_add_process', methods=['POST'])
def book_add_process():
    client = MongoClient("mongodb://localhost:27017/")
    database = client["ok-db"]
    collection = database["books"]

    title = request.form['title']
    file = request.files['file']
    author = request.form['author']
    price = request.form['price']
    isbn = request.form['isbn']
    encoded_data = base64.b64encode(file.read())

    doc = {'title': title, 'encoded_data': encoded_data, 'author': author,
           'price': price, 'created_date': datetime.now()}

    collection.insert_one(doc)

    return render_template('book_add_result.html')


if __name__ == '__main__':
    app.run()

- studio 3t


 

import base64

from flask import Flask, render_template, request
from pymongo import MongoClient
from datetime import datetime

app = Flask(__name__)


@app.route('/')
def hello_world():
    name = '이미자'
    return render_template('index.html', name=name)


@app.route('/book_add', methods=['GET'])
def book_add():
    return render_template('book_add.html')


@app.route('/book_add_process', methods=['POST'])
def book_add_process():
    client = MongoClient("mongodb://localhost:27017/")
    database = client["ok-db"]
    collection = database["books"]

    title = request.form['title']
    file = request.files['file']
    author = request.form['author']
    price = request.form['price']
    isbn = request.form['isbn']
    encoded_data = base64.b64encode(file.read())

    doc = {'title': title, 'encoded_data': encoded_data, 'author': author,
           'price': price, 'created_date': datetime.now()}

    result = collection.insert_one(doc)

    book_add_result = None
    if result.inserted_id is not None:
        print(result.inserted_id)
        book_add_result = "정상 등록"
    else:
        book_add_result = "등록 실패"

    return render_template('book_add_result.html',
                           book_add_result=book_add_result)


if __name__ == '__main__':
    app.run()

print에서 밑에 id 뜸 

 

db.books.find({"_id": ObjectId("여기 넣기")})

 

확인할 수 있음 

 


-도서 추가/ id 검색해보기 

 

 

 

 

 


-app.py 

import base64

from bson import ObjectId
from flask import Flask, render_template, request
from pymongo import MongoClient
from datetime import datetime

app = Flask(__name__)


@app.route('/')
def hello_world():
    name = '이미자'
    return render_template('index.html', name=name)


@app.route('/book_add', methods=['GET'])
def book_add():
    return render_template('book_add.html')


@app.route('/book_add_process', methods=['POST'])
def book_add_process():
    client = MongoClient("mongodb://localhost:27017/")
    database = client["ok-db"]
    collection = database["books"]

    title = request.form['title']
    file = request.files['file']
    author = request.form['author']
    price = request.form['price']
    isbn = request.form['isbn']
    encoded_data = base64.b64encode(file.read())

    doc = {'title': title, 'encoded_data': encoded_data, 'author': author,
           'price': price, 'created_date': datetime.now()}

    result = collection.insert_one(doc)

    book_add_result = None
    if result.inserted_id is not None:
        print(result.inserted_id)
        book_add_result = "정상 등록"
    else:
        book_add_result = "등록 실패"

    return render_template('book_add_result.html',
                           book_add_result=book_add_result)


@app.route('/book_id_search', methods=['GET'])
def book_id_search():
    return render_template('book_id_search.html')


@app.route('/book_id_search_process', methods=['POST'])
def book_id_search_process():
    client = MongoClient()
    database = client["ok-db"]
    collection = database["books"]
    _id = request.form['id']

    query = {'_id': ObjectId(_id)}
    doc = collection.find_one(query)
    title = doc['title']

    return render_template('book_id_search_result.html', title=title)


if __name__ == '__main__':
    app.run()

 

-book_id_search.html

<!DOCTYPE html>
<html lang="ko">
<head>
    <meta charset="UTF-8">
    <title>서적 검색(id)</title>
</head>
<body>
<form action="/book_id_search_process" method="post">
    id:
    <input type="test" name="id">
    <input type="submit" value="검 색">
</form>
</body>
</html>

 

-book_id_search_result.html

<!DOCTYPE html>
<html lang="ko">
<head>
    <meta charset="UTF-8">
    <title>서적 검색(id) 결과</title>
</head>
<body>
<h3>서적 검색(id) 결과</h3>
<table width="300px" border="1" bordercolor="blue">
        <tr>
            <td>
                제목
            </td>
            <td>
                {{title}}
            </td>
        </tr>
        <tr>
            <td>
                표지
            </td>
            <td>

            </td>
        </tr>
         <tr>
            <td>
                저자
            </td>
            <td>

            </td>
        </tr>
         <tr>
            <td>
                가격
            </td>
            <td>

            </td>
        </tr>
         <tr>
            <td>
                ISBN
            </td>
            <td>

            </td>
        </tr>

    </table>
</body>
</html>

-나머지는 위의 코드와 동일 


 - 사진도 같이 나오게 하기 

 

-app.py 

import base64

from bson import ObjectId
from flask import Flask, render_template, request
from pymongo import MongoClient
from datetime import datetime

app = Flask(__name__)


@app.route('/')
def hello_world():
    name = '이미자'
    return render_template('index.html', name=name)


@app.route('/book_add', methods=['GET'])
def book_add():
    return render_template('book_add.html')


@app.route('/book_add_process', methods=['POST'])
def book_add_process():
    client = MongoClient("mongodb://localhost:27017/")
    database = client["ok-db"]
    collection = database["books"]

    title = request.form['title']
    file = request.files['file']
    author = request.form['author']
    price = request.form['price']
    isbn = request.form['isbn']
    encoded_data = base64.b64encode(file.read())

    doc = {'title': title, 'encoded_data': encoded_data, 'author': author,
           'price': price, 'created_date': datetime.now()}

    result = collection.insert_one(doc)

    book_add_result = None
    if result.inserted_id is not None:
        print(result.inserted_id)
        book_add_result = "정상 등록"
    else:
        book_add_result = "등록 실패"

    return render_template('book_add_result.html',
                           book_add_result=book_add_result)


@app.route('/book_id_search', methods=['GET'])
def book_id_search():
    return render_template('book_id_search.html')


@app.route('/book_id_search_process', methods=['POST'])
def book_id_search_process():
    client = MongoClient()
    database = client["ok-db"]
    collection = database["books"]
    _id = request.form['id']

    query = {'_id': ObjectId(_id)}
    doc = collection.find_one(query)
    title = doc['title']
    decoded_data = doc['encoded_data'].decode('utf-8')
    img_src_data = f'data:image/png;base64, {decoded_data}'

    return render_template('book_id_search_result.html', title=title, img_src_data=img_src_data)


if __name__ == '__main__':
    app.run()

 

-book_id_search_result.html 

<!DOCTYPE html>
<html lang="ko">
<head>
    <meta charset="UTF-8">
    <title>서적 검색(id) 결과</title>
</head>
<body>
<h3>서적 검색(id) 결과</h3>
<table width="300px" border="1" bordercolor="blue">
        <tr>
            <td>
                제목
            </td>
            <td>
                {{title}}
            </td>
        </tr>
        <tr>
            <td>
                표지
            </td>
            <td>
                <img src="{{ img_src_data }}">
            </td>
        </tr>
         <tr>
            <td>
                저자
            </td>
            <td>

            </td>
        </tr>
         <tr>
            <td>
                가격
            </td>
            <td>

            </td>
        </tr>
         <tr>
            <td>
                ISBN
            </td>
            <td>

            </td>
        </tr>

    </table>
</body>
</html>

 


구구단 

-5단 

 

-gugudan.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        ul{
            list-style: none;
        }
    </style>
</head>
<body>
<ul>
    {% for gugu in gugu_list %}
        <li>{{ gugu }}</li>
    {% endfor %}
</ul>

</body>
</html>

-app.py 

import base64

from bson import ObjectId
from flask import Flask, render_template, request
from pymongo import MongoClient
from datetime import datetime

app = Flask(__name__)


@app.route('/')
def hello_world():
    name = '이미자'
    return render_template('index.html', name=name)


@app.route('/book_add', methods=['GET'])
def book_add():
    return render_template('book_add.html')


@app.route('/book_add_process', methods=['POST'])
def book_add_process():
    client = MongoClient("mongodb://localhost:27017/")
    database = client["ok-db"]
    collection = database["books"]

    title = request.form['title']
    file = request.files['file']
    author = request.form['author']
    price = request.form['price']
    isbn = request.form['isbn']
    encoded_data = base64.b64encode(file.read())

    doc = {'title': title, 'encoded_data': encoded_data, 'author': author,
           'price': price, 'created_date': datetime.now()}

    result = collection.insert_one(doc)

    book_add_result = None
    if result.inserted_id is not None:
        print(result.inserted_id)
        book_add_result = "정상 등록"
    else:
        book_add_result = "등록 실패"

    return render_template('book_add_result.html',
                           book_add_result=book_add_result)


@app.route('/book_id_search', methods=['GET'])
def book_id_search():
    return render_template('book_id_search.html')


@app.route('/book_id_search_process', methods=['POST'])
def book_id_search_process():
    client = MongoClient()
    database = client["ok-db"]
    collection = database["books"]
    _id = request.form['id']

    query = {'_id': ObjectId(_id)}
    doc = collection.find_one(query)
    title = doc['title']
    decoded_data = doc['encoded_data'].decode('utf-8')
    img_src_data = f'data:image/png;base64, {decoded_data}'

    return render_template('book_id_search_result.html', title=title, img_src_data=img_src_data)


@app.route('/gugudan', methods=['GET'])
def gugudan():
    dan = 5
    gugu_list = [] # list()
    for i in range(1, 10):
        gugu = f'{dan} × {i} = {dan * i}'
        gugu_list.append(gugu)

    return render_template('gugudan.html', gugu_list=gugu_list)


if __name__ == '__main__':
    app.run()

docs.djangoproject.com/ko/3.1/intro/tutorial01/

 

첫 번째 장고 앱 작성하기, part 1 | Django 문서 | Django

Django The web framework for perfectionists with deadlines. Overview Download Documentation News Community Code Issues About ♥ Donate

docs.djangoproject.com

 

-cmd 창에서 설치 

pip install virtualenv

 

virtualenv env
cd env
dir/w

scripts\activate
pip install django
django-admin startproject mysite

 

cd mysite
python manage.py runserver

실행 중인 상태에서 

웹에서  

http://127.0.0.1:8000/

들어가면  django 나옴 

 

 

-앱 만들기 

python manage.py startapp polls

- C:\mydjango\env\mysite\polls 의 view파일 수정 

from django.http import HttpResponse


def index(request):
    return HttpResponse("Hello, world. You're at the polls index.")

 

-urls.py 파일 만들기 

from django.urls import path

from . import views

urlpatterns = [
    path('', views.index, name='index'),
]

 

- C:\mydjango\env\mysite\mysite에서 urls.py 수정 

from django.contrib import admin
from django.urls import include, path

urlpatterns = [
    path('polls/', include('polls.urls')),
    path('admin/', admin.site.urls),
]

 

-터미널 창에서 실행

python manage.py runserver

웹에서 주소 입력 

 http://localhost:8000/polls/

 

이렇게 뜸 

 

+ Recent posts