有一次,我在pycharm中新建model.py,无论如何都识别为文本格式,就是输入代码没有提示等功能,一看就是文本格式,这种问题,是因为把改文件加入了文本中,具体做法,可以参考下面的链接

File -- settings -- Editor -- File Types

如下图,然后删除就ok


版权声明:本文为CSDN博主「ML_BOY」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/qq1483661204/article/details/103574716

힘들었어요.여태껏 제일 어려운 수강인것 같다.

수강시간 때문에 숙제도 베껴쓰다싶이 해서 제출하였지만 아직도 확신이 가질 않는다.

목록페이지,상세페이지,메인페이지(서버페이지) 사이를 왔다갔다하니 정신을 못추겠다.나중에 시간나는대로 첨부터 다시한번 확인하는걸로 하고 일단 한단락 마무리.

복습단계에서 다시 해보고서야 알것같다.하다가 빼먹은 부호는 마지막에 전체 완성코드와 비교하면서 보충했다.

 

app.py

from flask import Flask, render_template, request, jsonify, redirect, url_for
from pymongo import MongoClient
import requests

app = Flask(__name__)

client = MongoClient(''mongodb://아이디:비밀번호@내 아이피', 27017)
db = client.dbsparta_plus_week2


@app.route('/')
def main():
# DB에서 저장된 단어 찾아서 HTML에 나타내기
msg = request.args.get("msg")
words = list(db.words.find({}, {"_id": False}))
return render_template("index.html", words=words, msg=msg)


@app.route('/detail/<keyword>')
def detail(keyword):
status_receive = request.args.get("status_give", "old")
# API에서 단어 뜻 찾아서 결과 보내기
r = requests.get(f"https://owlbot.info/api/v4/dictionary/{keyword}", headers={"Authorization": "Token f1ddfa0f93c711a50c23b6c7d0f15df7c93c055b"})
if r.status_code != 200:
return redirect(url_for("main", msg="Word not found in dictionary; Try another word"))
result = r.json()
print(result)
return render_template("detail.html", word=keyword, result=result, status=status_receive)


@app.route('/api/save_word', methods=['POST'])
def save_word():
# 단어 저장하기
word_receive = request.form["word_give"]
definition_receive = request.form["definition_give"]
doc = {"word": word_receive, "definition": definition_receive}
db.words.insert_one(doc)
return jsonify({'result': 'success', 'msg': f'word "{word_receive}" saved'})


@app.route('/api/delete_word', methods=['POST'])
def delete_word():
# 단어 삭제하기
word_receive = request.form["word_give"]
db.words.delete_one({"word": word_receive})

db.examples.delete_many({"word": word_receive})
return jsonify({'result': 'success', 'msg': f'word "{word_receive}" deleted'})


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.0"/>
<title>Sparta Vocabulary Notebook</title>
<meta property="og:title" content="Sparta Vocabulary Notebook"/>
<meta property="og:description" content="mini project for Web Plus"/>
<meta property="og:image" content="{{ url_for('static', filename='logo_red.png') }}"/>
<link rel="shortcut icon" href="{{ url_for('static', filename='favicon.ico') }}" type="image/x-icon">
<link rel="icon" href="{{ url_for('static', filename='favicon.ico') }}" type="image/x-icon">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css"
integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm"
crossorigin="anonymous">

<link href="//maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet">
<link href='{{ url_for("static", filename="mystyle.css") }}' rel="stylesheet">
<!-- Optional JavaScript -->
<!-- jQuery first, then Popper.js, then Bootstrap JS -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js"
integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q"
crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"
integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl"
crossorigin="anonymous"></script>
<style>
.search-box {
width: 70%;
margin: 50px auto;
max-width: 700px;
}

.table {
width: 80%;
max-width: 800px;
margin: auto;
table-layout: fixed;
}

.table th {
border-top-style: none;
}

td {
background-color: white;
text-overflow: ellipsis;
overflow: hidden;
white-space: nowrap;
}

td > a, a:visited, a:hover, a:active {
color: black;
}

thead:first-child tr:first-child th:first-child {
border-radius: 10px 0 0 0;
}

thead:first-child tr:first-child th:last-child {
border-radius: 0 10px 0 0;
}

tbody:last-child tr:last-child td:first-child {
border-radius: 0 0 0 10px;
}

tbody:last-child tr:last-child td:last-child {
border-radius: 0 0 10px 0;
}

tr.highlight > td {
background-color: #34e873;
color: #6434e8;
}

tr.highlight > td > a {
color: #6434e8;
}
</style>
<script>
// console.log("{{msg}}")
{% if msg %}
alert("{{msg}}")
{% endif %}
let words = {{ words|tojson }};
let word_list = [];
for (let i = 0; i < words.length; i++) {
word_list.push(words[i]["word"])
}
// console.log(word_list)

function find_word() {
let word = $("#input-word").val().toLowerCase();
if (word == "") {
alert("please write something first:)")
return
}
if (word_list.includes((word))) {
// 리스트에 있으면 하이라이트
$(`#word-${word}`).addClass("highlight")
$(`#word-${word}`).siblings().removeClass("highlight");
$(`#word-${word}`)[0].scrollIntoView();
} else {
// 리스트에 없으면 새 단어를 위한 상세페이지로
window.location.href = `/detail/${word}?status_give=new`
}
}
</script>
</head>
<body>
<div class="wrap">
<div class="banner" onclick="window.location.href='/'">

</div>
<div class="search-box d-flex justify-content-center">
<input id="input-word" class="form-control" style="margin-right: 0.5rem">
<button class="btn btn-light" onclick="find_word()"><i class="fa fa-search"></i>
</button>
</div>
<table class="table">
<thead class="thead-light">
<tr>
<th scope="col" style="width:30%">WORD</th>
<th scope="col">MEANING</th>

</tr>
</thead>
<tbody id="tbody-box">
{% for word in words %}
<tr id="word-{{word.word}}">
<td><a href="/detail/{{word.word}}?status_give=old">{{word.word}}</a></td>
<td>
{{ word.definition|safe }}
</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
</body>
</html>

 

detail.html

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<title>Sparta Vocabulary Notebook</title>
<meta property="og:title" content="Sparta Vocabulary Notebook"/>
<meta property="og:description" content="mini project for Web Plus"/>
<meta property="og:image" content="{{ url_for('static', filename='logo_red.png') }}"/>
<link rel="shortcut icon" href="{{ url_for('static', filename='favicon.ico') }}" type="image/x-icon">
<link rel="icon" href="{{ url_for('static', filename='favicon.ico') }}" type="image/x-icon">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css"
integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm"
crossorigin="anonymous">
<link href="//maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet">
<link href='{{ url_for("static", filename="mystyle.css") }}' rel="stylesheet">
<!-- Optional JavaScript -->
<!-- jQuery first, then Popper.js, then Bootstrap JS -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js"
integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q"
crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"
integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl"
crossorigin="anonymous"></script>

<style>

span.example {
color: gray;
font-size: 14px;
}

.btn-sparta {
color: #fff;
background-color: #e8344e;
border-color: #e8344e;
}

.btn-outline-sparta {
color: #e8344e;
background-color: transparent;
background-image: none;
border-color: #e8344e;
}
</style>
<script>
let word = "{{ word }}"
$(document).ready(function () {
// get_definitions()
})

function get_definitions() {
$.ajax({
type: "GET",
url: `https://owlbot.info/api/v4/dictionary/${word}`,
beforeSend: function (xhr) {
xhr.setRequestHeader("Authorization", "Token [내 토큰]");
},
data: {},
error: function (xhr, status, error) {
alert("에러 발생!");
},
success: function (response) {
console.log(response)
$("#word").text(response["word"])
if (response["pronunciation"] == null) {
$("#pronunciation".text(""))
} else {
$("#pronunciation").text(`/${response["pronunciation"]}/`)
}

let definitions = response["definitions"]
$("#definitions").empty()
for (let i = 0; i < definitions.length; i++) {
let definition = definitions[i]
let html_temp = ""
if (definition["example"] == null) {
html_temp = `<div style="padding:10px">
<i>${definition["type"]}</i>
<br>${definition["definition"]}<br>
</div>`
} else {
html_temp = `<div style="padding:10px">
<i>${definition["type"]}</i>
<br>${definition["definition"]}<br>
<span class="example">${definition["example"]}</span>
</div>`
}
$("#definitions").append(html_temp)
}
}
})
}

function save_word() {
$.ajax({
type: "POST",
url: `/api/save_word`,
data: {
word_give: "{{ word }}",
definition_give: "{{ result.definitions[0].definition }}"
},
success: function (response) {
alert(response["msg"])
window.location.href = "/detail/{{ word }}?status_give=old"
}
});
}

function delete_word() {
$.ajax({
type: "POST",
url: `/api/delete_word`,
data: {
word_give: "{{ word}}"
},
success: function (response) {
alert(response["msg"])
window.location.href = "/"
}
});
}
</script>
</head>
<body>
<div class="wrap">
<div class="banner" onclick="window.location.href = '/'">
</div>
<div class="container">
<div class="d-flex justify-content-between align-items-end">
<div>
<h1 id="word" style="display: inline;">{{ result.word }}</h1>
{% if result.pronunciation != None %}
<h5 id="pronunciation" style="display: inline;">/{{ result.pronunciation }}/</h5>
{% endif %}
</div>
{% if status=="new" %}
<button id="btn-save" class="btn btn-outline-sparta btn-lg" onclick="save_word()">
<i class="fa fa-floppy-o" aria-hidden="true"></i>
</button>
{% else %}
<button id="btn-delete" class="btn btn-sparta btn-lg" onclick="delete_word()">
<i class="fa fa-trash-o" aria-hidden="true"></i>
</button>
{% endif %}
</div>
<hr>
<div id="definitions">
{% for definition in result.definitions %}
<div style="padding:10px">
<i>{{definition.type}}</i>
<br>{{definition.definition.encode('ascii','ignore').decode('utf-8')}}<br>
{% if definition.example %}
<span class="example">{{definition.example.encode('ascii','ignore').decode('utf-8')|safe}}</span>
{% endif %}
</div>
{% endfor %}
</div>
</div>
</div>
</body>
</html>

mystyle.css

.wrap {
background-color: RGBA(232, 52, 78, 0.2);
min-height: 100vh;
padding-bottom: 50px;
}

.banner {
width: 100%;
height: 200px;

background-color: #344ce8;
background-image: url("logo_red.png");

background-position: center;
background-size: contain;
background-repeat: no-repeat;

cursor: pointer;
}

.container {
width: 80%;
max-width: 800px;
margin: 30px auto;
padding: 20px;
background-color: white;

border: solid 1px gray;
border-radius: 10px;
}

'coding > Python coding' 카테고리의 다른 글

__init__.py  (0) 2021.06.23
E305 ,E302 expected 2 blank lines after class or function definition 해결안  (0) 2021.06.20
나만의 단어집  (0) 2021.06.18
Coding 단어 집  (0) 2021.06.18
웹 개발 플러스 1주차  (0) 2021.05.18

힘들었어요.여태껏 제일 어려운 것같다.

수강시간 때문에 숙제도 베껴쓰다싶이 해서 제출하였지만 아직도 확신이 가질않는다.

왔다갔다하니 정신을 못추겠다.나중에 시간나는대로 첨부터 다시한번 확인하는걸로 하고 일단 한단락 마무리.

app.py

from flask import Flask, render_template, request, jsonify, redirect, url_for
from pymongo import MongoClient
import requests

app = Flask(__name__)

client = MongoClient('54.180.83.188', 27017, username="test", password="test")
db = client.dbsparta_plus_week2


@app.route('/')
def main():
# DB 저장된 단어 찾아서 HTML's 나타내기
msg = request.args.get("msg")
words = list(db.words.find({}, {"_id": False}))
return render_template("index.html", words=words, msg=msg)


@app.route('/detail/<keyword>')
def detail(keyword):
# API 단어 뜻 찾아서 결과 보내기
status_receive = request.args.get("status_give", "old")
r = requests.get(f"https://owlbot.info/api/v4/dictionary/{keyword}",
headers={"Authorization": "Token f1ddfa0f93c711a50c23b6c7d0f15df7c93c055b"})
if r.status_code != 200:
return redirect(url_for("main", msg="단어가 이상해요 ㅠㅠ"))
result = r.json()
print(result)
return render_template("detail.html", word=keyword, result=result, status=status_receive)


@app.route('/api/save_word', methods=['POST'])
def save_word():
# 단어 저장하기
word_receive = request.form["word_give"]
definition_receive = request.form["definition_give"]
doc = {"word": word_receive, "definition": definition_receive}
db.words.insert_one(doc)
return jsonify({'result': 'success', 'msg': f'단어 "{word_receive}" 저장'})


@app.route('/api/delete_word', methods=['POST'])
def delete_word():
# 단어 삭제하기
word_receive = request.form["word_give"]
db.words.delete_one({"word": word_receive})
db.examples.delete_many({"word": word_receive})
return jsonify({'result': 'success', 'msg': f'단어 "{word_receive}" 삭제!'})


@app.route('/api/get_exs', methods=['GET'])
def get_exs():
# 예문 가져오기
word_receive = request.args.get("word_give")
result = list(db.examples.find({"word": word_receive}, {'_id': False}))
print(word_receive, len(result))
return jsonify({'result': 'success', 'examples': result})


@app.route('/api/save_ex', methods=['POST'])
def save_ex():
# 예문 저장하기
word_receive = request.form['word_give']
example_receive = request.form['word_give']
doc = {"word": word_receive, "example": example_receive}
db.examples.insert_one(doc)
return jsonify({'result': 'success', 'msg': f'example"{example_receive}"saved'})


@app.route('/api/delete_ex', methods=['POST'])
def delete_ex():
# 예문 삭제하기
word_receive = request.form['word_give']
number_receive = int(request.form["number_give"])
example = list(db.examples.find({"word": word_receive}))[number_receive]["example"]
print(word_receive, example)
db.examples.delete_one({"word": word_receive, "example": example})
return jsonify({'result': 'success', 'msg': f'example #{number_receive} of"{word_receive}" deleted'})


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.0"/>
<title>우리단어장</title>
<meta property="og:title" content="Sparta Vocabulary Notebook"/>
<meta property="og:description" content="mini project for Web Plus"/>
<meta property="og:image" content="{{ url_for('static', filename='logo_red.png') }}"/>
<link rel="shortcut icon" href="{{ url_for('static', filename='favicon.ico') }}" type="image/x-icon">
<link rel="icon" href="{{ url_for('static', filename='favicon.ico') }}" type="image/x-icon">

<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css"
integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm"
crossorigin="anonymous">
<link href="//maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet">
<link href='{{ url_for("static", filename="mystyle.css") }}' rel="stylesheet">

<!-- Optional JavaScript -->
<!-- jQuery first, then Popper.js, then Bootstrap JS -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js"
integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q"
crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"
integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl"
crossorigin="anonymous"></script>
<style>
.search-box {
width: 70%;
margin: 50px auto;
max-width: 700px;
}
.table {
width: 80%;
max-width: 800px;
margin: auto;
table-layout: fixed;
}

.table th {
border-top-style: none;
}

td {
background-color: white;
text-overflow: ellipsis;
overflow: hidden;
white-space: nowrap;
}

td > a, a:visited, a:hover, a:active {
color: black;
}

thead:first-child tr:first-child th:first-child {
border-radius: 10px 0 0 0;
}

thead:first-child tr:first-child th:last-child {
border-radius: 0 10px 0 0;
}

tbody:last-child tr:last-child td:first-child {
border-radius: 0 0 0 10px;
}

tbody:last-child tr:last-child td:last-child {
border-radius: 0 0 10px 0;
}


</style>
<script>
// console.log("{{ msg }}")
{% if msg %}
alert("{{ msg }}")
{% endif %}
let words = {{ words|tojson}};
let word_list = [];
for (let i = 0; i < words.length; i++) {
word_list.push(words[i]["word"])
}


function find_word() {
let word = $("#input-word").val().toLowerCase();
if (word == "") {
alert("값을 입력해주세요!")
return
}
if (word_list.includes(word)) {
// 리스트에 있으면 하이라이트
$(`#word-${word}`).addClass("highlight").siblings().removeClass("highlight");
$(`#word-${word}`)[0].scrollIntoView();
} else {
// 리스트에 없으면 새 단어를 위한 상세페이지로
window.location.href = '/detail/${word}?status_give=new'
}
}
</script>
</head>
<body>
<div class="wrap">
<div class="banner" onclick="window.location.href='/'">
</div>
<div class="search-box d-flex justify-content-center">
<input id="input-word" class="form-control" style="margin-right: 0.5rem">
<button class="btn btn-light" onclick="find_word()"><i class="fa fa-search"></i></button>
</div>
<table class="table">
<thead class="thead-light">
<tr>
<th scope="col" style="width:30%">WORD</th>
<th scope="col">MEANING</th>
</tr>
</thead>
<tbody id="tbody-box">
{% for word in words %}
<tr id="word-{{ word.word }}">
<td><a href="/detail/{{ word.word }}?status_give=old">{{ word.word }}</a></td>
<td>{{ word.definition|safe }}
</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
</body>
</html>

 

detail.html

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<title>Sparta Vocabulary Notebook</title>
<meta property="og:title" content="Sparta Vocabulary Notebook"/>
<meta property="og:description" content="mini project for Web Plus"/>
<meta property="og:image" content="{{ url_for('static', filename='logo_red.png') }}"/>
<link rel="shortcut icon" href="{{ url_for('static', filename='favicon.ico') }}" type="image/x-icon">
<link rel="icon" href="{{ url_for('static', filename='favicon.ico') }}" type="image/x-icon">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css"
integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm"
crossorigin="anonymous">
<link href="//maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet">
<link href='{{ url_for("static", filename="mystyle.css") }}' rel="stylesheet">
<!-- Optional JavaScript -->
<!-- jQuery first, then Popper.js, then Bootstrap JS -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js"
integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q"
crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"
integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl"
crossorigin="anonymous"></script>

<style>


span.example {
color: gray;
font-size: 14px;
}

.btn-sparta {
color: #fff;
background-color: #e8344e;
border-color: #e8344e;
}

.btn-outline-sparta {
color: #e8344e;
background-color: transparent;
background-image: none;
border-color: #e8344e;
}
</style>
<script>
let word = '{{ word }}'

function success() {

}

$(document).ready(function () {
// get_definitions()

{% if status=="old" %}
get_examples()
{% endif %}
})


function save_word() {
$.ajax({
type: "POST",
url: `/api/save_word`,
data: {
word_give: "{{ word }}",
definition_give: "{{ result.definitions[0].definition }}"
},
success: function (response) {
alert(response["msg"])
window.location.href = "/detail/{{ word }}?status=old"
}
})
}

function delete_word() {
$.ajax({
type: "POST",
url: `/api/delete_word`,
data: {
word_give: "{{ word }}"
},
success: function (response) {
alert(response["msg"])
window.location.href = "/"
}
});
}

function get_examples() {
$("#example-list").empty()
$.ajax({
type: "GET",
url: `/api/get_exs?word_give=${word}`,
data: {},
success: function (response) {
let examples = response["examples"];
for (let i = 0; i < examples.length; i++) {
let example = examples[i]["example"];
console.log(example)
let html_temp = `<li id="ex-${i}">${example["example"]}&nbsp;&nbsp;&nbsp;<a
href="javascript:delete_ex(${i})">delete</a></li>`
$("#example-list").append(html_temp)
}

}
});
}


function add_ex() {
let new_ex = $('#new-example').val();
if (!new_ex.toLowerCase().includes(word.toLowerCase())) {
alert(`the word '${word}' is not included.`);
return;
}
console.log(new_ex)
// new_ex.toLowerCase(), word.toLowerCase()

$.ajax({
type: "POST",
url: `/api/save_ex`,
data: {
word_give: word,
example_give: new_ex
},
success: function (response) {
console.log(response)

get_examples()
$("#new-example").val("");
}
});


}

function delete_ex(i) {
console.log("deleting", i)
$.ajax({
type: "POST",
url: `/api/delete_ex`,
data: {
word_give: word,
number_give: i
},
success: function (response) {
get_examples()
}
});
}
</script>
</head>
<body>
<div class="wrap">
<div class="banner" onclick="window.location.href = '/'">
</div>
<div class="container">
<div class="d-flex justify-content-between align-items-end">
<div>
<h1 id="word" style="display: inline;">{{ result.word }}</h1>
{% if result.pronunciation %}
<h5 id="pronunciation" style="display: inline;">/{{ result.pronunciation }}/</h5>
{% endif %}
</div>
{% if status=="new" %}
<button id="btn-save" class="btn btn-outline-sparta btn-lg" onclick="save_word()">
<i class="fa fa-floppy-o" aria-hidden="true"></i></button>
{% else %}
<button id="btn-delete" class="btn btn-sparta btn-lg" onclick="delete_word()">
<i class="fa fa-trash-o" aria-hidden="true"></i>
</button>
{% endif %}
</div>
<hr>
<div id="definitions">
{% set definitions = result.definitions %}
{% for definition in result.definitions %}
<div style="padding:10px">
<i>{{ definition.type }}</i>
<br>{{ definition.definition.encode('ascii','ignore').decode('utf-8') }}<br>
{% if definition.example %}
<span class="example">{{ definition.example.encode('ascii','ignore').decode('utf-8') }}</span>
{% endif %}
</div>
{% endfor %}
</div>
</div>
</div>
{% if status=="old" %}
<div id="examples" class="container">
<h3 style="text-align: center;margin-bottom:1rem">Write your own sentences!</h3>
<ul id="example-list">
<li id="ex-0">This sentence contains the word 'word'.&nbsp;&nbsp;&nbsp;<a
href="javascript:delete_ex(0)">delete</a></li>
<li id="ex-1">I don't like using the MS Word program.&nbsp;&nbsp;&nbsp;<a
href="javascript:delete_ex(1)">delete</a></li>
</ul>
<div class="d-flex justify-content-between" style="margin-left:20px;">
<input id="new-example" class="form-control form-control-sm" style="margin-right: 0.5rem">
<button class="btn btn-outline-secondary btn-sm" onclick="add_ex()">add</button>
</div>
</div>
{% endif %}
</div>
</body>
</html>

웹 개발  종합반에서 배운 세팅을 그대로 두었을걸 ~

괜히 웹 개발 플러스 때 복습한다 치고 따라서 설치했더니 Robo 3T에서 mongo db에 들어갈 수 없다,

슬랙에서 튜터님들과 질문을 했지만 인스턴스 지우고  처음부터 Download, install, setting 할것을 추천받았다.

첨부터 다시 공부한다고 생각하고 첨부터 다시 시도해봤다.

수업내용이 웹개발 종합반에서 배운 내용과 거의 비슷하고나 조금 업그래드 한 듯한 느낌이다.

이제부턴 튜터님이 강의하신 내용을 다 들은 후에 설정을 다시 검토해봐야겠다.

수강 내용의 뜻을 이해하지 못한채 무작정  따라한것이 제일 큰 차질이었다.섣불리 따라 했다간 큰 낭패다.

 

app.py

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

from pymongo import MongoClient
# client = MongoClient('localhost', 27017)
client = MongoClient('mongodb://test:test@localhost', 27017)

db = client.dbsparta_plus_week1

from datetime import datetime

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

@app.route('/diary', methods=['GET'])
def show_diary():
diaries = list(db.diary.find({}, {'_id': False}))
return jsonify({'all_diary': diaries})

@app.route('/diary', methods=['POST'])
def save_diary():
title_receive = request.form['title_give']
content_receive = request.form['content_give']

file = request.files["file_give"]

extension = file.filename.split('.')[-1]

today = datetime.now()
mytime = today.strftime('%Y-%m-%d-%H-%M-%S')

filename = f'file-{mytime}'

save_to = f'static/{filename}.{extension}'
file.save(save_to)

doc = {
'title':title_receive,
'content':content_receive,
'file': f'{filename}.{extension}',
'time':today.strftime('%Y-%m-%d')
}
db.diary.insert_one(doc)

return jsonify({'msg': '저장 완료!'})
if __name__ == '__main__':
app.run('0.0.0.0', port=5000, debug=True)

 

index.html

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

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

<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css"
integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">

<!-- Optional JavaScript -->
<!-- jQuery first, then Popper.js, then Bootstrap JS -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js"
integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q"
crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"
integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl"
crossorigin="anonymous"></script>

<title>스파르타코딩클럽 | 부트스트랩 연습하기</title>

<script src="https://cdn.jsdelivr.net/npm/bs-custom-file-input/dist/bs-custom-file-input.js"></script>

<link rel="preconnect" href="https://fonts.gstatic.com">
<link href="https://fonts.googleapis.com/css2?family=Jua&display=swap" rel="stylesheet">
<style>
* {
font-family: 'Jua', sans-serif;
}

.posting-box {
width: 500px;
margin-top: 20px;
}

.wrap {
width: 900px;
margin: auto;
}

.container {
padding-left: 50px;
}

.posting-box > .custom-file {
margin-bottom: 20px;
}

.card-time {
color: gray;
font-size: 15px;
margin-bottom: 0;
}
</style>
<script>
$(document).ready(function () {
bsCustomFileInput.init()
listing()
})

function listing() {
$.ajax({
type: "GET",
url: "/diary",
data: {},
success: function (response) {
let diaries = response['all_diary']
for (let i = 0; i < diaries.length; i++) {
let title = diaries[i]['title']
let content = diaries[i]['content']
let file = diaries[i]['file']
let time = diaries[i]['time']

let temp_html = `<div class="card">
<img src="../static/${file}" class="card-img-top">
<div class="card-body">
<h5 class="card-title">${title}</h5>
<p class="card-text">${content}</p>
<p class="card-time">${time}</p>
</div>
</div>`
$('#cards-box').append(temp_html)
}
}
})
}
function posting() {
let title = $('#title').val()
let content = $("#content").val()

let file = $('#file')[0].files[0]
let form_data = new FormData()

form_data.append("file_give", file)
form_data.append("title_give", title)
form_data.append("content_give", content)

$.ajax({
type: "POST",
url: "/diary",
data: form_data,
cache: false,
contentType: false,
processData: false,
success: function (response) {
alert(response["msg"])
window.location.reload()
}
});
}
</script>
</head>

<body>
<div class="wrap">
<div class="jumbotron jumbotron-fluid">
<div class="container">
<h1 class="display-4">나홀로 일기장</h1>
<div class="posting-box">
<div class="custom-file">
<input type="file" class="custom-file-input" id="file">
<label class="custom-file-label" for="file">사진 선택하기</label>
</div>
<div class="form-group">
<input type="email" class="form-control" id="title" placeholder="사진 제목">
</div>
<div class="form-group">
<textarea class="form-control" id="content" rows="3"
placeholder="내용 입력"></textarea>
</div>
<button onclick="posting()" type="button" class="btn btn-primary">저장하기</button>
</div>

</div>
</div>
<div class="card-columns" id="cards-box">
<div class="card">
<!-- <img class="card-img-top" src="..." alt="Card image cap">-->
<div class="card-body">
<h5 class="card-title">창덕궁</h5>
<p class="card-text">날씨가 참 좋았다.</p>
</div>
</div>

</div>
</div>

</body>

</html>

'coding > Python coding' 카테고리의 다른 글

__init__.py  (0) 2021.06.23
E305 ,E302 expected 2 blank lines after class or function definition 해결안  (0) 2021.06.20
나만의 단어집  (0) 2021.06.18
Coding 단어 집  (0) 2021.06.18
웹개발 플러스 2주차 (나만의 단어장)  (0) 2021.05.30

+ Recent posts