if r.status_code !=200:  입력시 PEP 8: E225 missing whitespace around operator

if r.status_code != 200:  이렇게 공백을 주면 물결밑줄을 제거할 수 있다.

2021.06.26

jinja2 코드색이 흰색일 경우

jinja2 {% %} 코드색이 주황색이 아닌 흰색일 경우 코드를 인식하지 않는다고 생각했는데 입력하고 돌려봤더니 정상적으로 작동하고 있었다.에러가 발생하지 않는 한 계속 사용해도 무방할듯.이로하여 나중에 다른 에러가 발생할지도 모르겠지만 여하튼 지금은 내 생각대로 간다.go~

from markupsafe import escape
from markupsafe import Markup
from werkzeug.exceptions import abort as abort
from werkzeug.utils import redirect as redirect

from . import json as json
from .app import Flask as Flask
from .app import Request as Request
from .app import Response as Response
from .blueprints import Blueprint as Blueprint
from .config import Config as Config
from .ctx import after_this_request as after_this_request
from .ctx import copy_current_request_context as copy_current_request_context
from .ctx import has_app_context as has_app_context
from .ctx import has_request_context as has_request_context
from .globals import _app_ctx_stack as _app_ctx_stack
from .globals import _request_ctx_stack as _request_ctx_stack
from .globals import current_app as current_app
from .globals import g as g
from .globals import request as request
from .globals import session as session
from .helpers import flash as flash
from .helpers import get_flashed_messages as get_flashed_messages
from .helpers import get_template_attribute as get_template_attribute
from .helpers import make_response as make_response
from .helpers import safe_join as safe_join
from .helpers import send_file as send_file
from .helpers import send_from_directory as send_from_directory
from .helpers import stream_with_context as stream_with_context
from .helpers import url_for as url_for
from .json import jsonify as jsonify
from .signals import appcontext_popped as appcontext_popped
from .signals import appcontext_pushed as appcontext_pushed
from .signals import appcontext_tearing_down as appcontext_tearing_down
from .signals import before_render_template as before_render_template
from .signals import got_request_exception as got_request_exception
from .signals import message_flashed as message_flashed
from .signals import request_finished as request_finished
from .signals import request_started as request_started
from .signals import request_tearing_down as request_tearing_down
from .signals import signals_available as signals_available
from .signals import template_rendered as template_rendered
from .templating import render_template as render_template
from .templating import render_template_string as render_template_string

__version__ = "2.0.1"


class Flask:
pass

경고:E305 E302에 대한 해결방법

물결 밑줄이 생기면서 아래와같은 경고문이 뜨게되면~

PEP 8: E305 expected 2 blank lines after class or function definition(found 1)

서버에서 E305 에러발생 화면

대책:

공백을 한줄이 아닌 2줄을 띄워주는것으로 해결하였습니다.

공백 두줄 띄워준후 물결 밑줄이 사라졌습니다

E302 에러도 같은 방법으로 해결가능

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

jinja2 코드 {% %} 입력시 문자색이 변하지 않을 경우  (0) 2021.06.26
__init__.py  (0) 2021.06.23
나만의 단어집  (0) 2021.06.18
Coding 단어 집  (0) 2021.06.18
웹개발 플러스 2주차 (나만의 단어장)  (0) 2021.05.30

셀룰로스https://ko.wikipedia.org/wiki/%EC%85%80%EB%A3%B0%EB%A1%9C%EC%8A%A4

https://mommoo.tistory.com/55
컴포넌트(Component)란?

컴포넌트(Component)란?

컴포넌트(Component)개념의 등장배경 과 의미에 대해 기술한다. 컴포넌트 개념의 유래 많은 하드웨어 제품들은 각각 독립된 기능을 가진 모듈로 만들어진다. 이 제품들은 회사 상관없이 서로 조합

mommoo.tistory.com

https://useful-jang.tistory.com/146

[BS4] BeautifulSoup4 크롤링 사용법 정리

공식 사이트 : https://www.crummy.com/software/BeautifulSoup/bs4/doc/ 한글 번역 : https://www.crummy.com/software/BeautifulSoup/bs4/doc.ko/ 1. 라이브러리 설치 터미널에 아래 명령어를 입력하여 라이브..

useful-jang.tistory.com

Isn't STATICFILES_DIRS in settings.py enoughsettings.py의 STATICFILES_DIRS로도 충분하지 않습니까?

파이썬 함수 def
https://velog.io/@ednadev/%ED%8C%8C%EC%9D%B4%EC%8D%AC-%ED%95%A8%EC%88%98-def

파이썬 함수 def

함수란 입력(input)에 대해서 의도된 출력(output)을 전달하는 역할 내장 함수(built-in fuction) 함수 함수의 정의 def 키워드 사용 네이밍(naming) 함수 이름으로부터 기능이 명시. 의미와 반대되거나 맞지

velog.io

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

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

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

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

 

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

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

괜히 웹 개발 플러스 때 복습한다 치고 따라서 설치했더니 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