简体   繁体   English

带有Flask的iOS上的JSON POST

[英]JSON POST on iOS with Flask

Inside my flask python web program, I save a few parameters in SessionStorage in order to send them back to flask, then save this information as a txt file. 在我的flask python网络程序中,我将一些参数保存在SessionStorage中,以便将它们发送回flask,然后将此信息另存为txt文件。

For some reason, everything works flawlessly on PC and Android, couldn't get it to work on iOS devices. 由于某些原因,一切都可以在PC和Android上完美运行,而无法在iOS设备上运行。 it recognizes and saves the sessionStorgae elements before sending, but no txt file is created afterwards (at the end of the app). 它会在发送之前识别并保存sessionStorgae元素,但此后(在应用程序末尾)不会创建任何txt文件。

Client-side (HTML): 客户端(HTML):

 function func() { ... $.ajax({ url: "{{ url_for('getInfo', _external=True) }}", type: 'POST', dataType: 'json', contentType: 'application/json;charset=UTF-8', success: function (response) { console.log(response); }, accepts: { json: 'application/json', }, data: JSON.stringify(log) }); return; ... } 
  <form id = "myForm" name ="myForm" method="post" action="{{url_for('final')}}" onsubmit="return func()"> 

Server-side (Flask): 服务器端(烧瓶):

@app.route("/get_info",methods = ['POST'])
def getInfo():
    list = request.get_json()
    global id
    with open(id + '.txt', 'w+') as outfile:
            json.dump(list,outfile,indent=2)
    return 'OK'

I can't figure out the solution. 我不知道解决方案。 Also I can't remember if it used to work or not on iOS. 另外,我不记得它是否曾经在iOS上运行。 trying to run all kinds of tests as I'm writing this. 在编写本文时尝试运行各种测试。 Any help would be much appreciated. 任何帮助将非常感激。 Thanks. 谢谢。

If you believe more information is needed, I elaborated in the comments about the overall structure of that HTML page and web program. 如果您认为需要更多信息,那么我在评论中详细介绍了该HTML页面和Web程序的总体结构。

Your code in 'DEBUG' mode 您的代码处于“调试”模式

@app.route("/get_info",methods = ['POST'])
def getInfo():
    list = request.get_json()
    global id
    file_name = '{}.txt'.format(id)
    print('About to write {} to file {}'.format(str(list),file_name))
    with open(file_name, 'w+') as outfile:
            json.dump(list,outfile,indent=2)
    print('Data was written')
    return 'OK'

Found an answer for future readers: iOS puts ajax request in cache. 找到了未来读者的答案:iOS将ajax请求放入缓存。 which later on might give empty response, or don't trigger the function at all. 稍后可能会给出空响应,或者根本不会触发该函数。 you can solve that by adding a few parameters and headers to the ajax request, which will prevent it from happenning: 您可以通过在ajax请求中添加一些参数和标头来解决此问题,这将阻止该请求的发生:

cache: false,
processData: false,
async: true,
headers: {
    "cache-control": "no-cache"
},

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM