๐Ÿ‘ฆ ๋‚ด์ผ๋ฐฐ์›€์บ ํ”„/TIL(Today I Learned)

TIL_220504

  • -

ํŒ€ ํ”„๋กœ์ ํŠธ๊ฐ€ ์‹œ์ž‘๋˜๊ณ  3์ผ์ฐจ ๋˜๋Š” ๋‚ 

 

์•„๋ฌด๋Ÿฐ ์ง„์ „์ด ์—†๋‹ค..

 

๋งก์€ ์—ญํ• ์˜ ๊ด€๋ จ ๊ฐ•์˜๋ฅผ ์ฐพ์•„ ๋‹ค์‹œ ๋ฐฐ์›Œ๋ณธ๋‹ค.

 

 

 


 

 

Flask ํ”„๋ ˆ์ž„์›Œํฌ

  • ์„œ๋ฒ„๋ฅผ ๊ตฌ๋™์‹œ์ผœ์ฃผ๋Š” ํŽธํ•œ ์ฝ”๋“œ ๋ชจ์Œ
  • ํ”„๋ ˆ์ž„์›Œํฌ๋Š” ๊ฐœ๋ฐœ์ž๋“ค์˜ 3๋ถ„ ์š”๋ฆฌ
  • flask ๊ธฐ๋ณธ๊ตฌ์กฐ
 
 
from flask import Flask, render_template, request, jsonify
app = Flask(__name__)

@app.route('/')
def home():
   return render_template('index.html')
   
   if __name__ == '__main__':
   app.run('0.0.0.0',port=5000,debug=True)

 

Flask ๊ธฐ์ดˆ

  • static ํด๋” (์ด๋ฏธ์ง€, cssํŒŒ์ผ์„ ๋„ฃ์–ด๋‘ก๋‹ˆ๋‹ค)
  • templates ํด๋” (htmlํŒŒ์ผ์„ ๋„ฃ์–ด๋‘ก๋‹ˆ๋‹ค)
  • app.py ํŒŒ์ผ

 

GET, POST

GET

  • ๋ฐ์ดํ„ฐ ์กฐํšŒ(Read)๋ฅผ ์š”์ฒญํ•  ๋•Œ
  • ๋ฐ์ดํ„ฐ ์ „๋‹ฌ : URL ๋’ค์— ๋ฌผ์Œํ‘œ๋ฅผ ๋ถ™์—ฌ key=value๋กœ ์ „๋‹ฌ
  • ์˜ˆ: google.com?q=๋ถ๊ทน๊ณฐ
function hey() {
    $.ajax({
        type: "GET",
        // /test ๋ผ๋Š” ์ฐฝ๊ตฌ์— ๊ฐ€๋Š”๋ฐ title_give ๋ผ๋Š” '์ด๋ฆ„์œผ๋กœ ๋ด„๋‚ ์€๊ฐ„๋‹ค' ๋ฅผ ๊ฐ€์ ธ๊ฐˆ๊ฒŒ
        url: "/test?title_give=๋ด„๋‚ ์€๊ฐ„๋‹ค",
        data: {},
        // ์ž˜ ๋œ๋‹ค๋ฉด console ์— ์ฐ์–ด๋ณผ๊ฒŒ
        success: function (response) {
            console.log(response)
        }
    })
}
@app.route('/test', methods=['GET'])
def test_get():
   # title_give ์ด๋ฆ„์œผ๋กœ ๋ญ”๊ฐ€๋ฅผ ๋ฐ›์•„์™€์„œ title_receive ๋ผ๋Š” ๋ณ€์ˆ˜์— ๋„ฃ๊ณ 
   title_receive = request.args.get('title_give')
   # title_receive ๋ฅผ ํ‘œ์‹œํ•œ๋‹ค.
   print(title_receive)
   return jsonify({'result': 'success', 'msg': '์ด ์š”์ฒญ์€ GET!'})

 

POST

  • ๋ฐ์ดํ„ฐ ์ƒ์„ฑ(Create), ๋ณ€๊ฒฝ(Update), ์‚ญ์ œ(Delete) ์š”์ฒญ ํ•  ๋•Œ
  • ์˜ˆ) ํšŒ์›๊ฐ€์ž…, ํšŒ์›ํƒˆํ‡ด, ๋น„๋ฐ€๋ฒˆํ˜ธ ์ˆ˜์ •
  • ๋ฐ์ดํ„ฐ ์ „๋‹ฌ : ๋ฐ”๋กœ ๋ณด์ด์ง€ ์•Š๋Š” HTML body์— key:value ํ˜•ํƒœ๋กœ ์ „๋‹ฌ
function hey() {
    $.ajax({
        type: "POST",
        // /test ์— ์žˆ๋Š”
        url: "/test",
        // ๋ด„๋‚ ์€๊ฐ„๋‹ค ๊ฐ’์„ ๊ฐ€์ ธ๊ฐ„๋‹ค.
        data: {title_give: '๋ด„๋‚ ์€๊ฐ„๋‹ค'},
        success: function (response) {
            console.log(response)
        }
    })
}
# /test ๋ผ๋Š” ์ฐฝ๊ตฌ๋ฅผ ๋งŒ๋“ค๊ณ  ๊ทธ ์ฐฝ๊ตฌ์—๋Š” POST ๋งŒ ๋ฐ›๋Š” ๊ฒƒ์€ ์ด์ชฝ์œผ๋กœ ์™€๋ผ
@app.route('/test', methods=['POST'])
def test_post():
   # title_give ๋ฅผ ๋ฐ›์•„์™€์„œ title_receive ๋กœ ๋„˜๊ฒจ์ฃผ๊ณ 
   title_receive = request.form['title_give']
   #
   print(title_receive)
   return jsonify({'result':'success', 'msg': '์š”์ฒญ์„ ์ž˜ ๋ฐ›์•˜์–ด์š”!'})

 

 

 

 
Contents

ํฌ์ŠคํŒ… ์ฃผ์†Œ๋ฅผ ๋ณต์‚ฌํ–ˆ์Šต๋‹ˆ๋‹ค

์ด ๊ธ€์ด ๋„์›€์ด ๋˜์—ˆ๋‹ค๋ฉด ๊ณต๊ฐ ๋ถ€ํƒ๋“œ๋ฆฝ๋‹ˆ๋‹ค.