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

+ Recent posts