[Python] flask

Jay Mild Leeยท2022๋…„ 10์›” 11์ผ
0

web programming

๋ชฉ๋ก ๋ณด๊ธฐ
7/9
post-thumbnail

๐Ÿบ flask

์„œ๋ฒ„ ๊ตฌ๋™์„ ์œ„ํ•œ ๋ชจ๋“ˆ๋กœ, ๋‹ค์–‘ํ•œ ๊ธฐ๋Šฅ์„ ์ง€์›ํ•œ๋‹ค.

๐Ÿ• ์„ค์น˜

pip install flask

๐Ÿ• ๋ผ์šฐํŒ… ๊ฒฝ๋กœ ์„ค์ • ๋ฐ ์„œ๋ฒ„ ๊ตฌ๋™

from flask import Flask
app = Flask(__name__)

# ...์ƒ๋žต...

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

๐Ÿบ ๋ Œ๋”๋ง : render_template

๐Ÿ• Project setting

ํ”„๋กœ์ ํŠธ์˜ ๋””๋ ‰ํ† ๋ฆฌ์™€ ํŒŒ์ผ๋“ค์„ ์…‹ํŒ…ํ•ด๋‘์–ด์•ผ flask์—์„œ ์ •์ƒ์ ์œผ๋กœ ๊ธฐ๋Šฅ์ด ๊ตฌํ˜„๋œ๋‹ค. ์ผ๋ฐ˜์ ์ธ ๋ฐฉ๋ฒ•์€ ๋‹ค์Œ๊ณผ ๊ฐ™๋‹ค.

C:.
โ”œโ”€app.py
โ”œโ”€.venv
โ”‚  โ”œโ”€Include
โ”‚  โ”œโ”€Lib
โ”‚  โ””โ”€Scripts
โ”œโ”€static
โ”‚  โ”œโ”€index.css
โ”‚  โ””โ”€index.js
โ””โ”€templates
   โ””โ”€index.html

templates ํด๋” : html
static ํด๋” : css, js, img

๐Ÿ• html ๋‚ด css, img, js ์„ค์ •

ํ”„๋กœ์ ํŠธ์˜ css, img, js ๋“ฑ์˜ ์—ฐ๋™์„ ์œ„ํ•ด์„œ flask ๋ฌธ๋ฒ•์„ ํ†ตํ•ด ์„ค์ •ํ•ด์ค˜์•ผํ•œ๋‹ค.

  <link
      rel="stylesheet"
      href="{{url_for('static', filename='index.css')}}" />

  <script
     type="text/javascript"
     src="{{ url_for('static', filename='index.js') }}"></script>

  <img src="{{ url_for('static', filename='img1.png') }}" />

๐Ÿบ ๋ฐ์ดํ„ฐ ํŒŒ์‹ฑ : request

๐Ÿ• request.~

  • request.args : URL ์ฟผ๋ฆฌ ์ŠคํŠธ๋ง ์•ˆ์˜ ํ‚ค/๊ฐ’ ์Œ
  • request.form : HTML POST ํผ์˜ body ์•ˆ์˜ ํ‚ค/๊ฐ’ ์Œ. ๋˜๋Š” JSON ์ธ์ฝ”๋”ฉ์ด ์•„๋‹Œ ์ž๋ฐ”์Šคํฌ๋ฆฝํŠธ ์š”์ฒญ
  • request.files : Flask๊ฐ€ ํผ์—์„œ ๋ถ„๋ฆฌํ•ด ๊ฐ€์ง€๊ณ  ์žˆ๋Š” body ์•ˆ์˜ ํŒŒ์ผ. HTML ํผ์ด enctype=multipart/form-data๋ฅผ ์‚ฌ์šฉํ•ด์•ผ ์—…๋กœ๋“œ๋จ
  • request.values : args์™€ form์˜ ํ•ฉ์ฒด. ํ‚ค ์ค‘๋ณต ์‹œ args๋ฅผ ์šฐ์„ ์‹œํ•จ
  • request.json : ํŒŒ์‹ฑ๋œ JSON ๋ฐ์ดํ„ฐ. ์š”์ฒญ์ด application/json content ํƒ€์ž…์ด๊ฑฐ๋‚˜, request.get_json(force=True)๋ฅผ ์‚ฌ์šฉํ•ด content type์„ ๋ฌด์‹œํ•  ์ˆ˜ ์žˆ์Œ
  • request.data : ํ”Œ๋ผ์Šคํฌ๊ฐ€ ์ฒ˜๋ฆฌํ•˜์ง€ ์•Š๋Š” Media Type์œผ๋กœ ์š”์ฒญ ๋ฐ์ดํ„ฐ๊ฐ€ ๋“ค์–ด์˜ฌ ์‹œ ๋ฌธ์ž์—ด๋กœ ์ €์žฅ. Fallback์œผ๋กœ ์‚ฌ์šฉ๋จ

๐Ÿ• POST ํ™œ์šฉ : request.form[~]

request.form['name'] # ํ‚ค๋ฅผ ์ด์šฉํ•œ
request.form.get('name') # ํ‚ค๊ฐ€ ์กด์žฌํ•˜์ง€ ์•Š์„ ์ˆ˜๋„ ์žˆ๋‹ค๋ฉด ์‚ฌ์šฉ
request.form.getlist('name') # ํ‚ค๊ฐ€ ์—ฌ๋Ÿฌ๋ฒˆ ์ „์†ก๋˜๊ณ  ๊ฐ’์˜ ๋ฆฌ์ŠคํŠธ๋ฅผ ์›ํ•˜๋ฉด ์‚ฌ์šฉ

๐Ÿบ json ํ˜•ํƒœ๋กœ data ๋ฆฌํ„ด : jsonify

from flask import Flask, render_template, request, jsonify
app = Flask(__name__)


@app.route("/homework", methods=["POST"])
def homework_post():
    # receive data from html
    name_receive = request.form['name_give']
    comment_receive = request.form['comment_give']

    # test code
    print('DB POST: ', name_receive, ', ', comment_receive)

    # DB data set
    doc = {
        'name':name_receive,
        'comment' : comment_receive
    }
    # DB input
    db.fan.insert_one(doc)

    # msg
    return jsonify({'msg':'๋“ฑ๋ก ์™„๋ฃŒ!'})

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