-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>
'mongodb' 카테고리의 다른 글
몽고디비- 홈페이지 ip:포트번호 로 접속하기 (0) | 2021.01.21 |
---|---|
몽고디비- 6일차/ bootstrap 활용해서 bookstore 업데이트 (0) | 2021.01.21 |
파이참 프로페셔널 버전 (0) | 2021.01.19 |
몽고디비 3일차- django, 장고 (0) | 2021.01.18 |
몽고디비 3일차- 웹연동, postman (0) | 2021.01.18 |