์๋ฒ์ฐ๊ฒฐ (ํ์ด์ฌ)
import pymongo
import certifi
client = pymongo.MongoClient(
"mongodb+srv://test:sparta@cluster0.hd7sx.mongodb.net/Cluster0?retryWrites=true&w=majority",
tlsCAFile=certifi.where())
db = client.dbsparta
flask๋ก mongoDB์ฐ๊ฒฐ + HTML ์ฐ๊ฒฐ (ํ์ด์ฌ)
from flask import Flask, render_template, request, jsonify
app = Flask(__name__)
@app.route('/')
def home():
return render_template('index.html')
@app.route("/homework", methods=["POST"])
def homework_post():
sample_receive = request.form['sample_give']
print(sample_receive)
return jsonify({'msg': 'POST ์ฐ๊ฒฐ ์๋ฃ!'})
@app.route("/homework", methods=["GET"])
def homework_get():
return jsonify({'msg': 'GET ์ฐ๊ฒฐ ์๋ฃ!'})
if __name__ == '__main__':
app.run('0.0.0.0', port=5000, debug=True)
ํฌ๋กค๋ง(ํ์ด์ฌ)
import requests #pip install requests
from bs4 import BeautifulSoup #pip install bs4
@app.route("/movie", methods=["POST"])
def movie_post():
url_receive = request.form['url_give']
star_receive = request.form['star_give']
comment_receive = request.form['comment_give']
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64)AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.86 Safari/537.36'}
data = requests.get(url_receive, headers=headers)
soup = BeautifulSoup(data.text, 'html.parser')
title = soup.select_one('meta[property="og:title"]')['content']
image = soup.select_one('meta[property="og:image"]')['content']
desc = soup.select_one('meta[property="og:description"]')['content']
doc = {
'title': title,
'image': image,
'desc': desc,
'star': star_receive,
'comment': comment_receive
}
db.movies.insert_one(doc)
return jsonify({'msg':'์ ์ฅ ์๋ฃ'})
html (POST) ์น๋ด์ฉ DB์ ์ ์ฅํ๊ธฐ
function save_comment() {
let name = $('#name').val()
let comment = $('#comment').val()
$.ajax({
type: 'POST',
url: '/homework',
data: {name_give: name, comment_give: comment},
success: function (response) {
alert(response['msg'])
window.location.reload()
}
})
}
html (GET) DB๋ด์ฉ ์น์ ๋ณด์ฌ์ฃผ๊ธฐ
function show_comment() {
$.ajax({
type: "GET",
url: "/homework",
data: {},
success: function (response) {
let rows = response['fans']
for (let i = 0; i < rows.length; i++) {
let name = rows[i]['name']
let comment = rows[i]['comment']
let temp_html = `<div class="card">
<div class="card-body">
<blockquote class="blockquote mb-0">
<p>${comment}</p>
<footer class="blockquote-footer">${name}</footer>
</blockquote>
</div>
</div>`
$('#comment-list').append(temp_html)
}
}
})
}