4์ฃผ์ฐจ WIL๐Ÿฑโ€๐Ÿ‘คFlask, API์„ค๊ณ„

Winteringยท2022๋…„ 4์›” 12์ผ
0

๋‚ด์ผ๋ฐฐ์›€์บ ํ”„

๋ชฉ๋ก ๋ณด๊ธฐ
4/17

Flask ํ”„๋ ˆ์ž„์›Œํฌ ๐ŸŽ€

: ์„œ๋ฒ„๋ฅผ ๊ตฌ๋™์‹œ์ผœ์ฃผ๋Š” ํŽธํ•œ ์ฝ”๋“œ ๋ชจ์Œ. ์„œ๋ฒ„๋ฅผ ๊ตฌ๋™ํ•˜๋ ค๋ฉด ํ•„์š”ํ•œ ๋ณต์žกํ•œ ์ผ๋“ค์„ ์‰ฝ๊ฒŒ ๊ฐ€์ ธ๋‹ค ์”€

  • flask ์‹œ์ž‘ ์ฝ”๋“œ
from flask import Flask
app = Flask(__name__)

@app.route('/')
def home():
   return 'This is Home!'

if __name__ == '__main__':
   app.run('0.0.0.0',port=5000,debug=True)
  • flask ๊ธฐ๋ณธ๊ตฌ์กฐ

    • static : css๋‚˜ ์ด๋ฏธ์ง€ํŒŒ์ผ์„ ๋‹ด์•„๋‘˜ ๋•Œ ์‚ฌ์šฉ

    • templates : html ํŒŒ์ผ์„ ๋‹ด์•„๋‘˜ ๋•Œ ์‚ฌ์šฉ

  • flask ์‹œ์ž‘ ์ฝ”๋“œ์— template๋ฅผ ๋ฐ›์„ ์ˆ˜ ์žˆ๊ฒŒ ๋ณ€๊ฒฝ (HTML ํŒŒ์ผ๊ณผ ์—ฐ๊ฒฐ)
from flask import Flask, render_template		#render_template ์ถ”๊ฐ€
app = Flask(__name__)

@app.route('/')
def home():
   return render_template('index.html')			#templates ํด๋”์˜ index.html์„ ์—ฐ๊ฒฐ

if __name__ == '__main__':
   app.run('0.0.0.0',port=5000,debug=True)

๋‚˜ํ™€๋กœ ๋ฉ”๋ชจ์žฅ์œผ๋กœ ์•Œ์•„๋ณด๋Š” API ๐ŸŽ€

  1. ๊ธฐ๋ณธ์„ธํŒ…
    • new - app.py ์ƒ์„ฑ
    • new - (directory) templates ์ƒ์„ฑ
    • new - (directory) static ์ƒ์„ฑ
  2. ํŒจํ‚ค์ง€ ์„ค์น˜
  • File - Setting - Project - Python Interpreter - (+)
    • flask (์„œ๋ฒ„)
    • pymongo (DB)
    • requests (ํฌ๋กค๋ง)
    • bs4 (ํฌ๋กค๋ง)
  1. API ์„ค๊ณ„
    • URL๊ณผ ์ฝ”๋ฉ˜ํŠธ๋ฅผ ์„œ๋ฒ„๋กœ ์ „์†กํ•˜์—ฌ, ์„œ๋ฒ„์—์„œ ๋ฐ์ดํ„ฐ ์ €์žฅ (Create) > [POST๋ฐฉ์‹]
    • ์ €์žฅ ๋œ ์นด๋“œ ๋ณด์—ฌ์ฃผ๊ธฐ, ๋ฐ์ดํ„ฐ ์ถœ๋ ฅ (Read) > [GET๋ฐฉ์‹]
    • ์ œ๋ชฉ / ํฌ์Šคํ„ฐ์ด๋ฏธ์ง€ / ์š”์•ฝ / ์ฝ”๋ฉ˜ํŠธ / ํด๋ฆญ์‹œ ์˜ํ™” ๋งํฌ(url) 5๊ฐ€์ง€์˜ ๋ฐ์ดํ„ฐ ์ €์žฅ ๋ฐ ์ถœ๋ ฅ ํ•„์š”

(+) TEST _ ๋ฉ”ํƒ€ ํƒœ๊ทธ๋ฅผ ์ด์šฉํ•œ ํฌ๋กค๋ง๐ŸŽ€

import requests
from bs4 import BeautifulSoup

url = 'https://movie.naver.com/movie/bi/mi/basic.nhn?code=171539'   #๊ฐ€์ ธ์˜ฌ ์˜ํ™” URL

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,headers=headers)

soup = BeautifulSoup(data.text, 'html.parser')

# title = soup.select_one('head > meta:nth-child(9)')
# print(title)

# ๋ฉ”ํƒ€ ํƒœ๊ทธ๋กœ ํฌ๋กค๋ง ํ•ด์˜ค๋Š” ๋ฐฉ๋ฒ•
title = soup.select_one('meta[property="og:title"]')['content']
image = soup.select_one('meta[property="og:url"]')['content']
desc = soup.select_one('meta[property="og:description"]')['content']

print(title, image, desc)
# title = soup.select_one('head > meta:nth-child(9)')
# print(title)
  • ์ด ๋ฐฉ์‹์˜ ๊ฒฝ์šฐ, ์ง์ ‘ ๋ธŒ๋ผ์šฐ์ €์— ๋“ค์–ด๊ฐ€์„œ ๋‚˜์˜ค๋Š” meta tag์˜ ์ˆœ์„œ์™€ ํŒŒ์ด์ฌ ์ฝ”๋“œ๋กœ ์ ‘์†ํ•ด์„œ ์ฝ๋Š” meta tag์˜ ์ˆœ์„œ๊ฐ€ ๋‹ฌ๋ผ์„œ ์ถœ๋ ฅ๊ฐ’์ด ์ œ๋Œ€๋กœ ๋‚˜์˜ค์ง€ ์•Š๋Š”๋‹ค (none์ด ์ถœ๋ ฅ๋จ)
title = soup.select_one('meta[property="og:title"]')['content']
image = soup.select_one('meta[property="og:url"]')['content']
desc = soup.select_one('meta[property="og:description"]')['content']
  • meta tag๋ฅผ ์‚ฌ์šฉํ•  ๋•Œ๋Š”, copy selector๊ฐ€ ์•„๋‹Œ meta tag์˜ id๊ฐ’์„ ํ™œ์šฉ
  • cf) meta tag๋Š” ํƒœ๊ทธ ์•ˆ์— ์กด์žฌํ•จ

๋‚˜ํ™€๋กœ ๋ฉ”๋ชจ์žฅ POST ๐ŸŽ€

  1. ํด๋ผ์ด์–ธํŠธ - ์„œ๋ฒ„ ์—ฐ๊ฒฐ
  2. ์„œ๋ฒ„ ๋งŒ๋“ค๊ธฐ (app.py)
@app.route('/memo', methods=['POST'])
def saving():
    url_receive = request.form['url_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,
        'url': url_receive,
        'comment': comment_receive
    }

    db.articles.insert_one(doc)

    return jsonify({'msg': '์ €์žฅ์ด ์™„๋ฃŒ ๋˜์—ˆ์Šต๋‹ˆ๋‹ค!'})
  1. ํด๋ผ์ด์–ธํŠธ ๋งŒ๋“ค๊ธฐ (index.html)
function postArticle() {
     let url = $('#post-url').val()
     let comment = $('#post-comment').val()

     $.ajax({
       	type: "POST",
        url: "/memo",
        data: {url_give : url, comment_give : comment},
        success: function ( response) { // ์„ฑ๊ณตํ•˜๋ฉด
           alert(response["msg"]);
           window.location.reload()    //์ƒˆ๋กœ๊ณ ์นจ
       			}
   			})
 		}


`
`
`

<div id="post-box" class="form-post" style="display:none">
    <div>
	    <div class="form-group">
		     <label for="post-url">์•„ํ‹ฐํด URL</label>        <!-- url์ด ์ž…๋ ฅ๋˜๋Š”๋ถ€๋ถ„ -->
             <input id="post-url" class="form-control" placeholder="">
        </div>
        <div class="form-group">
             <label for="post-comment">๊ฐ„๋‹จ ์ฝ”๋ฉ˜ํŠธ</label>
             <textarea id="post-comment" class="form-control" rows="2"></textarea>
        </div>
        <button type="button" class="btn btn-primary" onclick="postArticle()">๊ธฐ์‚ฌ์ €์žฅ</button>
     </div>
</div>

๋‚˜ํ™€๋กœ ๋ฉ”๋ชจ์žฅ GET ๐ŸŽ€

  1. ํด๋ผ์ด์–ธํŠธ - ์„œ๋ฒ„ ์—ฐ๊ฒฐ
  2. ์„œ๋ฒ„ ๋งŒ๋“ค๊ธฐ (app.py)
@app.route('/memo', methods=['GET'])
def listing():
    articles = list(db.articles.find({}, {'_id': False}))
    return jsonify({'all_articles': articles})
  1. ํด๋ผ์ด์–ธํŠธ ๋งŒ๋“ค๊ธฐ (index.html)
function showArticles() {
  $.ajax({
      type: "GET",
      url: "/memo",
      data: {},
      success: function (response) {
          let articles = response[`all_articles`]

          for(let i = 0; i < articles.length; i++) {
              let title = articles[i]['title']
              let image = articles[i]['image']
              let url = articles[i]['url']
              let desc = articles[i]['desc']
              let comment = articles[i]['comment']

              let temp_html = ` <div class="card">
                                   <img class="card-img-top"
                                        src="${image}"
                                         alt="Card image cap">
                                   <div class="card-body">
                                        <a target="_blank" href="${url}" class="card-title">${title}</a>
                                        <p class="card-text">${desc}</p>
                                        <p class="card-text comment">${comment}</p>
                                   </div>`

               $('#cards-box').append(temp_html)
                    }
                 }
            })
        }

0๊ฐœ์˜ ๋Œ“๊ธ€