Programing

Flask 요청에서받은 데이터 가져 오기

lottogame 2020. 10. 3. 09:43
반응형

Flask 요청에서받은 데이터 가져 오기


내 Flask 앱으로 전송 된 데이터를 얻고 싶습니다. 액세스를 시도 request.data했지만 빈 문자열입니다. 요청 데이터에 어떻게 액세스합니까?

@app.route('/', methods=['GET', 'POST'])
def parse_request():
    data = request.data  # data is empty
    # need posted data here

이 질문에 대한 대답은 다음 으로 Content-Type 헤더에 관계없이 Python Flask에서 원시 POST 본문 가져 오기를 요청했습니다. 이는 구문 분석 된 데이터가 아닌 원시 데이터를 가져 오는 것에 관한 것입니다.


문서는 요청에 속성을 사용할 수 설명합니다. 대부분의 경우 request.data대체로 사용되기 때문에 비어 있습니다.

request.data MIME 유형과 함께 제공된 경우 Flask가 처리하지 않는 경우 수신 요청 데이터를 문자열로 포함합니다.

  • request.args: URL 쿼리 문자열의 키 / 값 쌍
  • request.form: 본문의 키 / 값 쌍, HTML 게시물 양식 또는 JSON으로 인코딩되지 않은 JavaScript 요청
  • request.files: Flask가 form. HTML 양식을 사용해야합니다 enctype=multipart/form-data. 그렇지 않으면 파일이 업로드되지 않습니다.
  • request.values: 결합 argsform, args키가 겹치는 경우 선호
  • request.json: 구문 분석 된 JSON 데이터입니다. 요청에는 application/json콘텐츠 유형이 있거나 콘텐츠 유형 request.get_json(force=True)을 무시하는 데 사용 되어야합니다.

이들 모두는 MultiDict인스턴스입니다 (제외 json). 다음을 사용하여 값에 액세스 할 수 있습니다.

  • request.form['name']: 키가있는 경우 인덱싱 사용
  • request.form.get('name'): get키가없는 경우 사용
  • request.form.getlist('name'): getlist키가 여러 번 전송되고 값 목록이 필요한 경우 사용합니다. get첫 번째 값만 반환합니다.

원시 데이터를 얻으려면 request.data. 이것은 양식 데이터로 구문 분석 할 수없는 경우에만 작동합니다. 그렇지 않으면 비어 있고 request.form구문 분석 된 데이터를 갖게됩니다.

from flask import request
request.data

URL 쿼리 매개 변수의 경우 request.args.

search = request.args.get("search")
page = request.args.get("page")

게시 된 양식 입력의 경우 request.form.

email = request.form.get('email')
password = request.form.get('password')

콘텐츠 유형으로 게시 된 JSON의 application/json경우 request.get_json().

data = request.get_json()

다음은 게시 된 JSON 데이터를 구문 분석하고 다시 에코하는 예입니다.

from flask import Flask, request, jsonify

app = Flask(__name__)

@app.route('/foo', methods=['POST']) 
def foo():
    data = request.json
    return jsonify(data)

curl을 사용하여 JSON을 게시하려면 :

curl -i -H "Content-Type: application/json" -X POST -d '{"userId":"1", "username": "fizz bizz"}' http://localhost:5000/foo

또는 Postman을 사용하려면 :

using postman to post JSON


콘텐츠 유형으로 JSON을 게시하는 경우를 application/json사용 request.get_json()하여 Flask에서 가져옵니다. 컨텐츠 유형이 올바르지 않으면 None이 리턴됩니다. 데이터가 JSON이 아닌 경우 오류가 발생합니다.

@app.route("/something", methods=["POST"])
def do_something():
    data = request.get_json()

콘텐츠 유형에 관계없이 원시 게시물 본문을 가져 오려면 request.get_data(). 을 사용 request.data하면을 호출 request.get_data(parse_form_data=True)하여을 채우고 request.form MultiDict비워 data둡니다.


To get request.form as a normal dict with all the values for each key, use request.form.to_dict(flat=False). This might be useful to store the data with something that doesn't understand MultiDict.

To return JSON data for an API, pass it to jsonify.

This example returns form data as JSON data.

@app.route('/form_to_json', methods=['POST'])
def form_to_json():
    data = request.form.to_dict(flat=False)
    return jsonify(data)

Here's an example of POST form data with curl, returning as JSON:

$ curl http://127.0.0.1:5000/data -d "name=ivanleoncz&role=Software Developer"
{
  "name": "ivanleoncz", 
  "role": "Software Developer"
}

To get JSON posted without the application/json content type, use request.get_json(force=True).

@app.route('/process_data', methods=['POST'])
def process_data():
    req_data = request.get_json(force=True)
    language = req_data['language']
    return 'The language value is: {}'.format(language)

To parse JSON, use request.get_json().

@app.route("/something", methods=["POST"])
def do_something():
    result = handle(request.get_json())
    return jsonify(data=result)

The raw data is passed in to the Flask application from the WSGI server as request.stream. The length of the stream is in the Content-Length header.

length = request.headers["Content-Length"]
data = request.stream.read(length)

It is usually safer to use request.get_data() instead.


Use request.get_json() to get posted JSON data.

data = request.get_json()
name = data.get('name', '')

Use request.form to get data when submitting a form with the POST method.

name = request.form.get('name', '')

Use request.args to get data passed in the query string of the URL, like when submitting a form with the GET method.

request.args.get("name", "")

request.form etc. are dict-like, use the get method to get a value with a default if it wasn't passed.


If the content type is recognized as form data, request.data will parse that into request.form and return an empty string.

To get the raw data regardless of content type, call request.get_data(). request.data calls get_data(parse_form_data=True), while the default is False if you call it directly.


If the body is recognized as form data, it will be in request.form. If it's JSON, it will be in request.get_json(). Otherwise the raw data will be in request.data. If you're not sure how data will be submitted, you can use an or chain to get the first one with data.

def get_request_data():
    return (
        request.args
        or request.form
        or request.get_json(force=True, silent=True)
        or request.data
    )

request.args contains args parsed from the query string, regardless of what was in the body, so you would remove that from get_request_data() if both it and a body should data at the same time.


To post JSON with jQuery in JavaScript, use JSON.stringify to dump the data, and set the content type to application/json.

var value_data = [1, 2, 3, 4];

$.ajax({
    type: 'POST',
    url: '/process',
    data: JSON.stringify(value_data),
    contentType='application/json',
    success: function (response_data) {
        alert("success");
    }   
});

Parse it in Flask with request.get_json().

data = request.get_json()

When posting form data with an HTML form, be sure the input tags have name attributes, otherwise they won't be present in request.form.

@app.route('/', methods=['GET', 'POST'])
def index():
    print(request.form)
    return """
<form method="post">
    <input type="text">
    <input type="text" id="txt2">
    <input type="text" name="txt3" id="txt3">  
    <input type="submit">
</form>
"""
ImmutableMultiDict([('txt3', 'text 3')])

Only the txt3 input had a name, so it's the only key present in request.form.

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

반응형