플라스크에서 'Imtable MultiDict'에서 데이터를 가져오는 방법
나는 아약스와 플라스크의 사용법을 배우고 있다, 그래서 내가 하는 일은 아약스 요청을 보내고 데이터를 받는 것입니다.post내 파이썬 파일의 요청
My html file contains this code
var data = {"name":"John Doe","age":"21"};
$.ajax({
url:'/post/data',
datatype : "json",
contentType: "application/json; charset=utf-8",
data : JSON.stringify(data),
success : function(result) {
jQuery("#clash").html(result);
},error : function(result){
console.log(result);
}
});
그리고 내 파이썬 파일은 다음을 포함합니다.
@app.route('/post/data',methods=['GET','POST'])
def postdata():
#do some
data = str(request.args)
json_dumps = json.dumps(data)
return json_dumps
이것은 페이지에 다음과 같은 데이터를 제공합니다.
"ImmutableMultiDict([('{\"name\":\"John Doe\",\"age\":\"21\"}', u'')])"
그리고 이것이 나의 것입니다.request.query_string표정{%22name%22:%22John%20Doe%22,%22age%22:%2221%22}
그럼 어떻게 해야 하나요?name그리고.age제가 틀린 곳이 있으면 고쳐주세요.잘 부탁드립니다.
실제로 데이터를 얻을 필요는 없습니다.ImmutableMultiDict몇 가지 오류로 인해 응답을 json 데이터로 끌어낼 수 없습니다.먼저 Ajax 호출의 매개 변수를 약간 조정해야 합니다.통화 유형을 다음과 같이 추가해야 합니다.POST.더 나아가,datatype로써야 합니다.dataType새로운 문의 사항:
var data = {"name":"John Doe","age":"21"};
$.ajax({
type: 'POST',
contentType: 'application/json',
url: '/post/data',
dataType : 'json',
data : JSON.stringify(data),
success : function(result) {
jQuery("#clash").html(result);
},error : function(result){
console.log(result);
}
});
데이터는 이제 실제로 사후 요청으로 전송됩니다.jsonType. Flask 서버에서 이제 다음과 같이 데이터 아들 정보를 읽을 수 있습니다.
@app.route('/post/data',methods=['GET','POST'])
def postdata():
jsonData = request.get_json()
print jsonData['name']
print jsonData['age']
return "hello world" #or whatever you want to return
인쇄됩니다.John Doe그리고.21성공적으로
이것이 당신에게 효과가 있거나 추가적인 질문이 있으면 알려주세요!
편집: 플라스크에서 다음과 같이 아약스 호출에 성공을 반환할 수 있습니다.
# include this import at the tomb
from flask import jsonify
@app.route('/post/data',methods=['GET','POST'])
def postdata():
...
return jsonify(success=True, data=jsonData)
요청에 따라 _dict로 전화하시면 됩니다.form 개체(예: http://www.seanbehan.com/how-to-get-a-dict-from-flask-request-form/ )
AJAX로 양식을 보내려다가 드디어 해결책을 찾아서 이 페이지에 왔습니다.그리고 해결책은 JSON을 건너뛰는 것입니다(이것이 같은 검색에서 다른 사람들에게 도움이 되기를 바랍니다).
$.ajax({
type: "POST",
url: my_url,
data: $("#formID").serialize(), //form containing name and age
success: function(result){
console.log(result);
}
});
그런 다음 Flask 서버에서 다음을 수행합니다.
app.route('/my_url', methods = [POST])
def some_function():
name = request.form['name']
age = request.form['age']
# do what you want with these variables
return 'You got it right'
내용을 추가하여 문제를 해결했습니다.application/J로 입력SON like so
data ={
type:'POST',
contentType:'application/json',
otherData: 'foo'
}
이제 플라스크 백엔드의 데이터에 다음과 같이 액세스할 수 있습니다.
app.route('/my_url', methods = ["POST"])
def some_function():
other_data = request.form['otherData']
# do something
참고: 이 jQuery가 아닌 vanilla JavaScript를 사용했습니다.
이 작업은 다음과 같습니다.
var data = {"name":"John Doe","age":"21"};
$.ajax({
type: 'POST',
contentType: 'application/json',
url: '/my_url',
dataType : 'json',
data : JSON.stringify(data),
success : function(result) {
jQuery("#clash").html(result);
},error : function(result){
console.log(result);
}
});
플라스크 앱: imtjson
@app.route('/my_url',methods=['POST,GET']) #
def some_function():
dataList=list(request.form)[0] # output is string ==> '{"name":"John Doe","age":"21"}'
b=json.loads(dataList) # output is dictionary ==> {"name":"John Doe","age":"21"}
print(b) #{"name":"John Doe","age":"21"}
return 'OK'
언급URL : https://stackoverflow.com/questions/29091070/how-to-get-data-from-immutablemultidict-in-flask
'programing' 카테고리의 다른 글
| 태그 지정을 위한 데이터베이스 설계 (0) | 2023.07.29 |
|---|---|
| 시스템 교체.Data.Oracle Client에서 Oracle로.데이터 액세스(ODP).NET) (0) | 2023.07.29 |
| 인덱스 이름이 Mysql의 전체 데이터베이스에서 고유해야 합니까? (0) | 2023.07.29 |
| 두 날짜 사이의 차이(월 단위 및 일 단위)를 sql로 가져옵니다. (0) | 2023.07.29 |
| 읽기 및 쓰기를 동시에 열기 (0) | 2023.07.24 |