python

[Flask] (7) REST API

Meng's Computer 2021. 1. 28. 03:28

πŸ“ REST API λž€ ?

REST API : REST 기반으둜 μ„œλΉ„μŠ€ API(Application Interface) λ₯Ό κ΅¬ν˜„ν•œ 것을 REST API 라고 ν•œλ‹€.

 

[Flask] (2) REST & HTTP Method & API/End Point

πŸ“ RESTλž€ 무엇인가 ? REST : Representational State Transfer = μžμ›μ„ 이름(μžμ›μ˜ ν‘œν˜„)으둜 κ΅¬λΆ„ν•˜μ—¬ ν•΄λ‹Ή μžμ›μ˜ μƒνƒœλ₯Ό μ£Όκ³  λ°›λŠ” 것을 μ˜λ―Έν•œλ‹€. = 즉, μžμ›(resourece) 의 ν‘œν˜„(representation)에 μ˜ν•œ "..

youngminieo1005.tistory.com

졜근 OpenAPI (λˆ„κ΅¬λ‚˜ μ‚¬μš©ν•  수 μžˆλ„λ‘ 곡개된 API), 마이크둜 μ„œλΉ„μŠ€ 등을 μ œκ³΅ν•˜λŠ” κΈ°μ—…μ—μ„œλŠ” λŒ€λΆ€λΆ„ REST APIλ₯Ό μ œκ³΅ν•œλ‹€.

πŸ’‘ REST API νŠΉμ§•

  • REST 기반으둜 μ‹œμŠ€ν…œμ„ λΆ„μ‚°ν•˜μ—¬ ν™•μž₯μ„±κ³Ό μž¬μ‚¬μš©μ„±μ„ λ†’μ—¬ μœ μ§€λ³΄μˆ˜λ₯Ό νŽΈλ¦¬ν•˜κ²Œ ν•  수  μžˆλ‹€.
  • RESTλŠ” HTTP ν‘œμ€€μ„ 기반으둜 κ΅¬ν˜„ν•˜κ³ , HTTPλ₯Ό μ§€μ›ν•˜λŠ” ν”„λ‘œκ·Έλž¨ μ–Έμ–΄λ‘œ ν΄λΌμ΄μ–ΈνŠΈ,μ„œλ²„λ₯Ό κ΅¬ν˜„ν•  수 μžˆλ‹€.

λ”°λΌμ„œ, REST APIλ₯Ό κ΅¬ν˜„ν•˜λ©΄, ν΄λΌμ΄μ–ΈνŠΈ 뿐만 μ•„λ‹ˆλΌ, JAVA, C#, WEB 등을 μ΄μš©ν•΄μ„œ ν΄λΌμ΄μ–ΈνŠΈλ₯Ό μ œμž‘ν•  수 μžˆλ‹€.

πŸ’‘ REST API κ·œμΉ™

RESTμ—μ„œ κ°€μž₯ μ€‘μš”ν•œ 기본적인 κ·œμΉ™μ€ 두 가지이닀.
URIλŠ” μžμ›μ„ ν‘œν˜„ν•˜λŠ” 데 집쀑학, ν–‰μœ„μ— λŒ€ν•œ μ •μ˜λŠ” HTTP Methodλ₯Ό 톡해 ν•˜λŠ” 것이 REST APIλ₯Ό μ„€κ³„ν•˜λŠ” 핡심이닀.

1. URIλŠ” μ •λ³΄μ˜ μžμ›μ„ ν‘œν˜„ν•΄μ•Ό ν•œλ‹€.

  • λ¦¬μ†ŒμŠ€λͺ…은 λ™μ‚¬λ³΄λ‹€λŠ” λͺ…사λ₯Ό μ‚¬μš©ν•œλ‹€.
  • URIλŠ” μžμ›μ„ ν‘œν˜„ν•˜λŠ” 데에 쀑점을 λ‘μ–΄μ•Όν•œλ‹€.
  • GET같은 ν–‰μœ„μ— λŒ€ν•œ ν‘œν˜„μ΄ λ“€μ–΄κ°€μ„œλŠ” μ•ˆλœλ‹€.
#μ•ˆ 쒋은 μ˜ˆμ‹œ
GET /getTodos/3
GET /todos/show/3

#쒋은 μ˜ˆμ‹œ
GET /todos/3

2. μžμ›μ— λŒ€ν•œ ν–‰μœ„λŠ” HTTP Method(GET, POST, PUT, DELETE λ“±)으둜 ν‘œν˜„ν•œλ‹€.

주둜 5κ°€μ§€μ˜ Method(GET, POST, PUT, DELETE , PATCH)λ₯Ό μ‚¬μš©ν•΄μ„œ CRUDλ₯Ό κ΅¬ν˜„ν•œλ‹€.

[ 좜처 : elice ]

#μ•ˆ 쒋은 μ˜ˆμ‹œ
GET /todos/delete/3

#쒋은 μ˜ˆμ‹œ
DELETE /todos/3

 

πŸ“ RESTful μ΄λž€ ?

  • RESTful은 일반적으둜 RESTλΌλŠ” μ•„ν‚€ν…μ²˜λ₯Ό κ΅¬ν˜„ν•˜λŠ” μ›Ή μ„œλΉ„μŠ€λ₯Ό λ‚˜νƒ€λ‚΄κΈ° μœ„ν•΄ μ‚¬μš©λ˜λŠ” μš©μ–΄μ΄λ‹€.
  • λ”°λΌμ„œ REST APIλ₯Ό μ‚¬μš©ν•˜λŠ” μ›Ή μ„œλΉ„μŠ€λ₯Ό μš°λ¦¬λŠ” "RESTfulν•˜λ‹€"κ³  ν•  수 μžˆλ‹€.
  • RESTful은 RESTλ₯Ό RESTλ‹΅κ²Œ μ“°κΈ° μœ„ν•œ λ°©λ²•μœΌλ‘œ λˆ„κ΅°κ°€κ°€ κ³΅μ‹μ μœΌλ‘œ λ°œν‘œν•œ 것이 μ•„λ‹ˆλ‹€.
  • REST의 원리λ₯Ό λ”°λ₯΄κ³  μ‚¬μš©ν•˜λŠ” μ‹œμŠ€ν…œμ„ RESTfulμ΄λΌλŠ” μš©μ–΄λ‘œ μΉ­ν•˜κ²Œ λœλ‹€.

πŸ’‘ RESTful의 λͺ©μ μ€ 무엇인가 ?

μ΄ν•΄ν•˜κΈ° 쉽고 μ‰¬μš΄ REST APIλ₯Ό λ§Œλ“œλŠ” 것이닀.

  • RESTfulν•œ APIλ₯Ό κ΅¬ν˜„ν•˜λŠ” 근본적인 λͺ©μ μ΄ μ„±λŠ₯ ν–₯상이 쀑점이 μ•„λ‹ˆλ‹€.
  • API의 이해도와 ν˜Έν™˜μ„±μ„ λ†’μ΄λŠ” 것이 주된 λͺ©μ μ΄λ‹€.
  • λ”°λΌμ„œ, μ„±λŠ₯이 μ€‘μš”ν•œ μƒν™©μ—μ„œλŠ” ꡳ이 RESTfulν•œ APIλ₯Ό κ΅¬ν˜„ν•  ν•„μš”κ°€ μ—†λ‹€.

 

πŸ“ REST API 섀계 κΈ°λ³Έ κ·œμΉ™

1. URIλŠ” μ •λ³΄μ˜ μžμ›μ„ ν‘œν˜„ν•΄μ•Ό ν•œλ‹€.

  • μžμ›μ€ λ™μ‚¬λ³΄λ‹€λŠ” λͺ…사λ₯Ό μ‚¬μš©
  • μžμ›μ€ λŒ€λ¬Έμžλ³΄λ‹€λŠ” μ†Œλ¬Έμž μ‚¬μš©
  • μžμ›μ˜ λ„νλ¨ΌνŠΈ μ΄λ¦„μœΌλ‘œλŠ” λ‹¨μˆ˜ λͺ…사λ₯Ό μ‚¬μš©
  • μžμ›μ˜ μ»¬λ ‰μ…˜ μ΄λ¦„μœΌλ‘œλŠ” 볡수 λͺ…사λ₯Ό μ‚¬μš©
  • μžμ›μ˜ μŠ€ν† μ–΄ μ΄λ¦„μœΌλ‘œλŠ” 볡수 λͺ…사λ₯Ό μ‚¬μš©
#μ•ˆ 쒋은 μ˜ˆμ‹œ
GET /Student/3

#쒋은 μ˜ˆμ‹œ
GET /students/3		# μ†Œλ¬Έμž,볡수λͺ…사 μ‚¬μš©

2. μžμ›μ— λŒ€ν•œ ν–‰μœ„λŠ” HTTP Method(GET, POST, PUT, DELETE λ“±)둜 ν‘œν˜„ν•œλ‹€.

- URI에 HTTP Methodκ°€ λ“€μ–΄κ°€λ©΄ μ•ˆλœλ‹€.

#μ•ˆ 쒋은 μ˜ˆμ‹œ
GET /students/delete/3

#쒋은 μ˜ˆμ‹œ
DELETE /students/3

- CRUD κΈ°λŠ₯을 λ‚˜νƒ€λ‚΄λŠ” 것은 URI에 μ‚¬μš©ν•˜μ§€ μ•ŠλŠ”λ‹€.

#μ•ˆ 쒋은 μ˜ˆμ‹œ
GET /students/show/3
GET /students/insert/4

#쒋은 μ˜ˆμ‹œ
GET /students/3
POST /students/4
  • : id λŠ” ν•˜λ‚˜μ˜ νŠΉμ • μžμ›μ„ λ‚˜νƒ€λ‚΄λŠ” κ³ μœ κ°’μ΄λ‹€.

    ex) studentλ₯Ό μƒμ„±ν•˜λŠ” route : POST/students
    ex) id=12인 studentλ₯Ό μ‚­μ œν•˜λŠ” route: DELETE/students/12

πŸ”Š μš©μ–΄

  • λ„κ·œλ¨ΌνŠΈ : 객체 μΈμŠ€ν„΄μŠ€λ‚˜ λ°μ΄ν„°λ² μ΄μŠ€ λ ˆμ½”λ“œμ™€ μœ μ‚¬ν•œ κ°œλ…
  • μ»¬λ ‰μ…˜ : μ„œλ²„μ—μ„œ κ΄€λ¦¬ν•˜λŠ” λ””λ ‰ν„°λ¦¬λΌλŠ” μžμ›
  • μŠ€ν† μ–΄ : ν΄λΌμ΄μ–ΈνŠΈμ—μ„œ κ΄€λ¦¬ν•˜λŠ” μžμ› μ €μž₯μ†Œ

 

πŸ“ REST API 섀계 κ·œμΉ™

1. μŠ¬λž˜μ‹œ (/) λŠ” 계측 관계λ₯Ό λ‚˜νƒ€λ‚΄λŠ” 데 μ‚¬μš©ν•œλ‹€.

ex) https://academy.elice.io/classroom/teach 

2. URI λ§ˆμ§€λ§‰ 문자둜 μŠ¬λž˜μ‹œ (/) λ₯Ό ν¬ν•¨ν•˜μ§€ μ•ŠλŠ”λ‹€.

ex) https://academy.elice.io/classroom/teach/ ← ( X )

  • URI에 ν¬ν•¨λ˜λŠ” λͺ¨λ“  κΈ€μžλŠ” μžμ›μ˜ μœ μΌν•œ μ‹λ³„μžλ‘œ μ‚¬μš©λ˜μ•Ό ν•œλ‹€.
  • URIκ°€ λ‹€λ₯΄λ‹€λŠ” 것은 λΆˆλŸ¬μ˜€λŠ” μžμ›μ΄ λ‹€λ₯΄λ‹€λŠ” 뜻이고, λ°˜λŒ€λ‘œ μžμ›μ΄ λ‹€λ₯΄λ©΄ URI도 달라져야 ν•œλ‹€.
  • REST APIλŠ” λΆ„λͺ…ν•œ URIλ₯Ό λ§Œλ“€μ–΄ 톡신을 ν•΄μ•Ό ν•˜κΈ° λ•Œλ¬Έμ— ν˜Όλ™μ„ 주지 μ•Šλ„λ‘ URI 경둜의 λ§ˆμ§€λ§‰μ—λŠ”
    μŠ¬λž˜μ‹œ (/) λ₯Ό μ‚¬μš©ν•˜μ§€ μ•ŠλŠ”λ‹€.

3. ν•˜μ΄ν”ˆ (-) 은 URI 가독성을 λ†’μ΄λŠ”λ° μ‚¬μš©ν•œλ‹€.

4. 밑쀄 ( _ ) 은 URI에 μ‚¬μš©ν•˜μ§€ μ•ŠλŠ”λ‹€.

5. URI κ²½λ‘œμ—λŠ” μ†Œλ¬Έμžλ₯Ό μ‚¬μš©ν•œλ‹€.

6. νŒŒμΌν™•μž₯μžλŠ” URI에 ν¬ν•¨ν•˜μ§€ μ•ŠλŠ”λ‹€.

ex) https://academy.elice.io/classroom/teach/111/python.png ← ( X )
ex) GET / classroom/teach/111/python HTTP/1.1 Host: academy.elice.io Accept: image/png ← ( O )

7. μžμ› 간에 μ—°κ΄€ 관계가 μžˆλŠ” 경우 λ‹€μŒκ³Ό 같이 μž‘μ„±ν•œλ‹€.

/μžμ›λͺ…/μžμ›ID/관계가 μžˆλŠ” λ‹€λ₯Έ μžμ›λͺ…
ex) GET : /students/{studentid}/classroom

[ 좜처 : elice ]

 

πŸ“ REST API : CRUD κ΅¬ν˜„ν•΄λ³΄κΈ°

μ•žμ„  ν¬μŠ€νŒ… ( Flask 1~ 6 )을 보면, render_template( ) λ©”μ†Œλ“œλ₯Ό μ΄μš©ν•΄μ„œ, html에 좜λ ₯ κ²°κ³Όλ₯Ό λ„μ›Œ 값듀을 ν™•μΈν–ˆμ—ˆλ‹€.그리고 htmlμ—μ„œλŠ” jinja2 λ¬Έλ²•μœΌλ‘œ ν•΄λ‹Ή λ‚΄μš©μ„ λ°›μ•„μ„œ html에 λ„μšΈ 수 μžˆμ—ˆλ‹€.

ν•˜μ§€λ§Œ, μ΄λŠ” "API μ„œλ²„"λ₯Ό κ°œλ°œν•œ 것이 μ•„λ‹Œ, Flaskλ₯Ό ν™œμš©ν•΄μ„œ "μ›Ή μ–΄ν”Œλ¦¬μΌ€μ΄μ…˜"을 κ°œλ°œν•œ 것이닀.

REST API μ„œλ²„λ₯Ό 개발 ν•  λ•ŒλŠ”, μ„œλ²„λ‹¨μ—μ„œ 직접 λ Œλ”λ§(Rendering)ν•΄μ„œ νŽ˜μ΄μ§€λ₯Ό λ³΄μ—¬μ£ΌλŠ” 것이 μ•„λ‹ˆλΌ
μ›Ή νŽ˜μ΄μ§€λ₯Ό κ΅¬μ„±ν•˜λŠ”λ° ν•„μš”ν•œ "정보λ₯Ό λ°˜ν™˜" 해주도둝 κ΅¬ν˜„ν•΄μ•Ό ν•œλ‹€.

λ”°λΌμ„œ, λ°±μ—”λ“œ μ„œλ²„λŠ” ν΄λΌμ΄μ–ΈνŠΈ(ν”„λ‘ νŠΈ μ—”λ“œ) 와 데이터λ₯Ό μ£Όκ³  λ°›μŒμœΌλ‘œμ¨ 톡신을 ν•˜κ²Œ λ˜λŠ” 것이닀.

πŸ”Š μ›Ή μƒμ—μ„œ κ°€μž₯ 많이 μ“°μ΄λŠ” 데이터 ν˜•μ‹μ€ JSON ν˜•μ‹μ˜ 데이터λ₯Ό μ£Όκ³  λ°›λŠ”λ‹€.

πŸ”Š [Tips] REST APIλ₯Ό μœ„ν•΄ κ΅¬ν˜„λ˜λŠ” CRUD의 λ©”μ†Œλ“œμ™€ URL의 이름은 CRUD에 λ§žμΆ”λŠ” 것이 μΌλ°˜μ μ΄λ‹€.

 

from flask import Flask, render_template, request, redirect, url_for
import json

app = Flask(__name__)

board = []  # μ‹€μ œ DBκ°€ μ•„λ‹Œ, 예제λ₯Ό μœ„ν•œ board 리슀트

# root 경둜 
@app.route('/')
def index():
    return render_template("Boards.html", rows = board)

# POST : CREATE (C)
@app.route("/create", methods=["POST"])
def create():
    name = request.form["name"]
    context = request.form["context"]
    board.append([name,context])

    return json.dumps( { "status":200, "result" : { "id" : len(board)} } )  # json.dumps({ HTTP μƒνƒœ, λ°˜ν™˜ν•  κ²°κ³Ό }) = 데이터λ₯Ό json ν˜•νƒœλ‘œ λ³€ν™˜ν•΄μ€€λ‹€.


# GET : READ (R)
@app.route("/read", methods=["GET"])
def read():
    return json.dumps({"status":200, "result":board})


if __name__ == '__main__':
    app.run()
<!-- ./templates/Boards.html -->

<!doctype html>
<html lang="ko">
    <head>
        <meta charset="UTF-8">
        <meta name="Generator" content="EditPlus®">
        <meta name="Author" content="">
        <meta name="Keywords" content="">
        <meta name="Description" content="">
        <title>κ²Œμ‹œνŒ 등둝</title>
        <style type="text/css">
            body{ text-align: center; }
        </style>
     </head>
    <body>
        <h1>κ²Œμ‹œνŒ</h1>
        <h4>μΆ”κ°€</h4>
        <form action = "/create" method = "POST">
            이름<br>
            <input type = "text" name = "name" /><br>
            λ‚΄μš©<br>    
            <textarea name = "context" cols="50" rows="10"></textarea><br><br>
            <input type = "submit" value = "게 μ‹œ" /><br>
        </form>
        <h4>λͺ©λ‘λ³΄κΈ°</h4>
        <table class="table" border="1" width = 600 style = "word-break:break-all" style="table-layout: fixed" align="center">
        <thread>
            <th width="4%">λͺ©μ°¨</th>
            <th width="15%">이름</th>
            <th width="25%">λ‚΄μš©</th>
        </thread>
        {% for row in rows %}
        <tr>
            <td>{{ loop.index }}</td>
            <td>{{ row[0] }}</td>
            <td>{{ row[1] }}</td>
        </tr>
        {% endfor %}
        </table>
    </body>
</html>

πŸ’‘ CREATE : POST

νŽ˜μ΄μ§€μ—μ„œ 데이터 μž…λ ₯
μž…λ ₯된 값을 json ν˜•νƒœλ‘œ λ³€ν™˜ν•œκ²ƒμ„ λ°˜ν™˜ν•œ κ²°κ³Ό

 

πŸ’‘ READ : GET

/read 둜 GET ν–ˆμ„ λ•Œ ( 데이터 ν•˜λ‚˜λ„ μž…λ ₯ μ•ˆν•œμƒν™© )

 

πŸ“Œ UPDATE(PUT)와 DELETE(DLEDTE)λŠ” μ•žμ„ , CREATE(POST), READ(GET)κ³Ό 달리, Ajaxλ₯Ό μ΄μš©ν•΄μ„œ κ΅¬ν˜„λ˜κΈ°λ„ ν•œλ‹€.

πŸ“ Ajax : 비동기식(Asynchronous)  JavaScript + XML 이닀.

Ajax λŠ” REST APIλ₯Ό μ†μ‰½κ²Œ κ΅¬ν˜„ν•˜κΈ° μœ„ν•΄ μ‚¬μš©λ˜λŠ” "ν”„λ ˆμž„μ›Œν¬"이며, html νŒŒμΌμ—μ„œ κ°„λ‹¨νžˆ μ‚¬μš©ν•˜λŠ” 방법을 ν•΄λ³΄μž.
( μ΄λ²ˆμ—λŠ”, html νŒŒμΌμ„ 더, 주의깊게 보자. ( Ajax λΆ€λΆ„ ) )

# Ajax_Example.py

from flask import Flask, render_template, request, jsonify  # Flask의 λ‚΄μž₯된 jsonify = json.dump() 와 같은 κΈ°λŠ₯이닀. json ν˜•νƒœλ‘œ 데이터 λ°˜ν™˜

app = Flask(__name__)

board = []  # μž„μ‹œ DB κ°œλ… (사싀,리슀트)

# root
@app.route("/")
def index():
    return render_template("ajax_index.html", rows=board)

@app.route("/ajax", methods=["POST"])
def ajax():
    data = request.get_json()   # request.get_json() = POST μš”μ²­μ„ 톡해 얻은 데이터 -> json ν˜•μ‹μœΌλ‘œ μ–»κΈ° μœ„ν•œ λ©”μ†Œλ“œ
    board.append(data)

    return jsonify(result="success", result2=data)  # json_dumps({}) 와 κΈ°λŠ₯은 κ°™λ‹€.

if __name__ == '__main__':
    app.run()
<!--ajax_index.html-->

<html>

<head>
    <script src="https://code.jquery.com/jquery-latest.min.js"></script>
</head>

<body>
    <p id="example">AJAX</p>
    <input type="text" id="id1" placeholder="id">
    <input type="text" id="name1" placeholder="name">
    <input type="text" id="context1" placeholder="context">
    <input type="button" id="execute" value="execute">


    <script>
        $('#execute').click(function () {
            var id = $('#id1').val();
            var name = $('#name1').val();
            var context = $('#context1').val();

            var postdata = {
                'id': id, 'name': name, 'context': context
            }
            
            // ajax ν˜•μ‹μœΌλ‘œ -> ajax example.py둜 데이터 전솑
            $.ajax({
                type: 'POST',
                url: '{{url_for("ajax")}}',
                data: JSON.stringify(postdata),		// μ„œλ²„λ‘œ 데이터λ₯Ό λ„˜κΈΈλ•ŒλŠ”, JSON.stringify(데이터)둜 Stringν˜•μ‹μœΌλ‘œ λ„˜κ²¨μ€€λ‹€.
                dataType: 'JSON',
                contentType: "application/json",
                success: function (data) {
                    alert('성곡! 데이터 κ°’:' + data.result2['id'] + " " + data.result2['name'] + " " + data.result2['context'])
                },
                error: function (request, status, error) {
                    alert('ajax 톡신 μ‹€νŒ¨')
                    alert(error);
                }
            })
        })
    </script>
    <table border=1 width="600">
        <thead>
            <td>λͺ©μ°¨</td>
            <td>이름</td>
            <td>λ‚΄μš©</td>
        </thead>

        {% for row in rows %}
        <tr>
            <td>{{ loop.index }}</td>
            <td>{{ row['name'] }}</td>
            <td>{{ row['context'] }}</td>
        </tr>
        {% endfor %}
    </table>

</body>

</html>

 

 

πŸ’‘ UPDATE & DELETE ( PUT & DELETE )

from flask import Flask, render_template, jsonify, request

app = Flask(__name__)

board = [{"id": 1, "name": "elice", "context": "test"}]

@app.route('/')
def index():
    return render_template('index.html', rows = board)

@app.route('/create', methods=['POST'])
def create():
    data = request.get_json()
    board.append(data)
    return jsonify(result = "success", result2= data)


@app.route('/delete', methods=['POST'])
def delete():
    del board[-1]

    return jsonify(result="success")
    

@app.route('/put', methods=['POST'])
def put():
    
    data = request.get_json()
    board.append(data)

    return jsonify(result="success",result2=data)
<!--index.html-->

<html>
<head>
    <script src="https://code.jquery.com/jquery-latest.min.js"></script>
</head>
<body>
    <p id="example">AJAX</p>
    <input type="text" id="id1" placeholder="id">
    <input type="text" id="name1" placeholder="name">
    <input type="text" id="context1" placeholder="context">
    <input type="button" id="create" value="create">
    <input type="button" id="update" value="update">
    <input type="button" id="delete" value="delete">
    
    
    <script>
    	// POST (CREATE)
        $('#create').click(function(){
            var id = $('#id1').val();
            var name = $('#name1').val();
            var context = $('#context1').val();

            var postdata = {
                'id':id, 'name':name, 'context':context
            }
            $.ajax({
                type: 'POST',
                url: '{{url_for("create")}}',
                data: JSON.stringify(postdata),
                dataType : 'JSON',
                contentType: "application/json",
                success: function(data){
                    alert('성곡! 데이터 κ°’:' + data.result2['id']+" " + data.result2['name']+ " " + data.result2['context'])
                },
                error: function(request, status, error){
                    alert('ajax 톡신 μ‹€νŒ¨')
                    alert(error);
                }
            })
        })
        
        // PUT (UPDATE)
        $('#update').click(function(){
            var id = $('#id1').val();
            var name = $('#name1').val();
            var context = $('#context1').val();

            var postdata = {
                'id':id, 'name':name, 'context':context
            }
            $.ajax({
                type: 'POST',
                url: '{{url_for("put")}}',
                data: JSON.stringify(postdata),
                dataType : 'JSON',
                contentType: "application/json",
                success: function(data){
                    alert('성곡! μˆ˜μ •λœ 데이터 κ°’:' + data.result2['id']+" " + data.result2['name']+ " " + data.result2['context'])
                },
                error: function(request, status, error){
                    alert('ajax 톡신 μ‹€νŒ¨')
                    alert(error);
                }
            })
        })
        
        // DELETE (DELETE)
        $('#delete').click(function(){
            $.ajax({
                type: 'POST',
                url: '{{url_for("delete")}}',
                contentType: "application/json",
                success: function(){
                    alert('성곡! 데이터 μ‚­μ œ μ™„λ£Œ')
                },
                error: function(request, status, error){
                    alert('ajax 톡신 μ‹€νŒ¨')
                    alert(error);
                }
            })
        })
    </script>
	<table border=1 width="600">
        <thead>
        <td>λͺ©μ°¨</td>
		<td>이름</td>
		<td>λ‚΄μš©</td>
		</thead>
        
    {% for row in rows %}
		<tr>
            <td>{{ loop.index }}</td>
			<td>{{ row['name'] }}</td>
			<td>{{ row['context'] }}</td>
		</tr>
	{% endfor %}
	</table>
</body>
</html>

 

728x90
λ°˜μ‘ν˜•