본문으로 바로가기

flask가 requests를 핸들링하는 방법

category Django, Flask/🌶️ Flask 2020. 6. 5. 15:44

https://stackoverflow.com/questions/10434599/get-the-data-received-in-a-flask-request

 

Get the data received in a Flask request

I want to be able to get the data sent to my Flask app. I've tried accessing request.data but it is an empty string. How do you access request data? from flask import request @app.route('/', meth...

stackoverflow.com

 

렌더링한 html

<form action="/report" method="get">
  <input type="text" place="What job do you want?" required name="search" />
  <button>submit</button>
</form>

input작성 후 나온 도메인. 여기에서 ?(쿼리) 이후 부분을 추출하고 싶다면 flask의 request를 사용하면 됩니다.

http://....?search=react

from flask import Flask, render_template, request

app = Flask("job scrapper")

@app.route("/")
def home():
  return render_template("home.html")

@app.route("/report")
def report():
  # 도메인 쿼리부분을 dict 형태로 가져옵니다.
  word = request.args.get("search")
  return f"you search {word}"

app.run(host="0.0.0.0")

 

그런데 이는 get을 통해 전달된 값들의 URL을 빼다가 사용하는 것입니다. post나 다른 형태의 정보를 받을 때는 다른 방법이 필요합니다.

 

 

The docs describe the attributes available on the request. In most common cases request.data will be empty because it's used as a fallback:

request.data Contains the incoming request data as string in case it came with a mimetype Flask does not handle.

  • request.args: the key/value pairs in the URL query string
  • request.form: the key/value pairs in the body, from a HTML post form, or JavaScript request that isn't JSON encoded
  • request.files: the files in the body, which Flask keeps separate from form. HTML forms must use enctype=multipart/form-data or files will not be uploaded.
  • request.values: combined args and form, preferring args if keys overlap
  • request.json: parsed JSON data. The request must have the application/json content type, or use request.get_json(force=True) to ignore the content type.

All of these are MultiDict instances (except for json). You can access values using:

  • request.form['name']: use indexing if you know the key exists
  • request.form.get('name'): use get if the key might not exist
  • request.form.getlist('name'): use getlist if the key is sent multiple times and you want a list of values. get only returns the first value.

 

 

다음과 같은 post 명령을 받을 때는 request.form을 통해 받을 수 있습니다.

<form action="/add" method="post">
  <input placeholder="Write a subreddit name" name="new-subreddit" required></input>
  <button type="submit">Add</button>
</form>
@app.route("/add", methods=["POST"])
def add():
  newSub = request.form['new-subreddit']
  subreddits.append(newSub)
  return render_template("home.html", subreddits=subreddits)
 

darren, dev blog
블로그 이미지 DarrenKwonDev 님의 블로그
VISITOR 오늘 / 전체