Python Flask 发布并返回 json 对象

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29155339/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 04:09:12  来源:igfitidea点击:

Python Flask post and return json objects

pythonflaskstripe-payments

提问by dickiebow

Apologies if this seems rudimental as I am new to Python. The task I am trying to complete is to send a json object from an iPhone app to a python script that will process a stripe payment. The problem I have is I cannot figure out how to get Python to recognise the incoming json object to extract data from it and pass onto Stripe.

如果这看起来很初级,我很抱歉,因为我是 Python 新手。我试图完成的任务是将一个 json 对象从 iPhone 应用程序发送到将处理条带支付的 python 脚本。我遇到的问题是我不知道如何让 Python 识别传入的 json 对象以从中提取数据并传递给 Stripe。

I have taken a step back to simplify the problem. I have a python script that attempts to post a json object with four value pairs to another function that should extract the values, create a new json object and return that object. I cannot get it to work and any help would be greatly appreciated as I've been stuck on this for a while. I am using Flask:

我已经退后一步来简化问题。我有一个 python 脚本,它尝试将具有四个值对的 json 对象发布到另一个应该提取值的函数,创建一个新的 json 对象并返回该对象。我无法让它工作,任何帮助将不胜感激,因为我已经坚持了一段时间。我正在使用烧瓶:

`
import json
import stripe
import smtplib
import requests

from flask import Flask, request, jsonify

@application.route('/run_post')
def run_post():
    url = 'http://xxx.pythonanywhere.com/stripetest'
    data = {'stripeAmount': '199', 'stripeCurrency': 'USD', 'stripeToken': '122', 'stripeDescription': 'Test post'}
    headers = {'Content-Type' : 'application/json'}

    r = requests.post(url, data, headers=headers)

    #return json.dumps(r.json(), indent=4)
    return r.text

@application.route('/stripetest', methods=["POST"])
def stripeTest():

    if request.method == "POST":

        json_dict = json.loads(request.body.raw)

        stripeAmount = json_dict['stripeAmount']
        stripeCurrency = json_dict['stripeCurrency']
        stripeToken = json_dict['stripeToken']
        stripeDescription = json_dict['stripeDescription']

        data = "{'stripeAmountRet': " +  stripeAmount + ", 'stripeCurrencyRet': " + stripeCurrency + ", 'stripeTokenRet': " + stripeToken + ", 'stripeDescriptionRet': " + stripeDescription + "}"

        return jsonify(data)
    else:

        return """<html><body>
        Something went horribly wrong
        </body></html>"""

`

`

I get the following returned in the error log when I run this:

运行此命令时,我在错误日志中返回以下内容:

`

2015-03-19 21:07:47,148 :Starting new HTTP connection (1): xxx.pythonanywhere.com
    2015-03-19 21:07:47,151 :Exception on /stripetest [POST]
    Traceback (most recent call last):
      File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1687, in wsgi_app
        response = self.full_dispatch_request()
      File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1360, in full_dispatch_request
        rv = self.handle_user_exception(e)
      File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1358, in full_dispatch_request
        rv = self.dispatch_request()
      File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1344, in dispatch_request
        return self.view_functions[rule.endpoint](**req.view_args)
      File "/var/www/xxx_pythonanywhere_com_wsgi.py", line 156, in stripeTest
        json_dict = json.loads(request.body.raw)
      File "/usr/local/lib/python2.7/dist-packages/werkzeug/local.py", line 336, in __getattr__
        return getattr(self._get_current_object(), name)
    AttributeError: 'Request' object has no attribute 'body'

`

`

采纳答案by Jason Brooks

You have a couple of issues with the code. First of all, you need to properly define the jsondata when you make the request from the requestslibrary. You can do this as follows:

您的代码有几个问题。首先,json当您从requests库中发出请求时,您需要正确定义数据。您可以按如下方式执行此操作:

@application.route('/run_post')
def run_post():
    url = 'http://xxx.pythonanywhere.com/stripetest'
    data = {'stripeAmount': '199', 'stripeCurrency': 'USD', 'stripeToken': '122', 'stripeDescription': 'Test post'}
    headers = {'Content-Type' : 'application/json'}

    r = requests.post(url, data=json.dumps(data), headers=headers)

    #return json.dumps(r.json(), indent=4)
    return r.text

Notice that we call json.dumpsinstead of just passing the data directly. Otherwise, the incoming request is not interpreted as jsondata.

请注意,我们调用json.dumps而不是直接传递数据。否则,传入的请求不会被解释为json数据。

Next, in your receiving function, we change it as follows:

接下来,在您的接收函数中,我们将其更改如下:

@application.route('/stripetest', methods=["POST"])
def stripeTest():

    if request.method == "POST":
        json_dict = request.get_json()

        stripeAmount = json_dict['stripeAmount']
        stripeCurrency = json_dict['stripeCurrency']
        stripeToken = json_dict['stripeToken']
        stripeDescription = json_dict['stripeDescription']


        data = {'stripeAmountRet': stripeAmount, 'stripeCurrencyRet': stripeCurrency, 'stripeTokenRet': stripeToken, 'stripeDescriptionRet': stripeDescription}
        return jsonify(data)
    else:

        return """<html><body>
        Something went horribly wrong
        </body></html>"""

A couple of things are changed. First, we read in the data by calling request.get_json(), which properly parses the incoming jsondata. Note from above that we needed to change how we actually made the request for it to parse the data properly. The next issue was how you returned the data. To properly jsonifythe data to return, we put the data into a python dictionary rather than into a string.

有几件事发生了变化。首先,我们通过调用读request.get_json()json数据,正确解析传入的数据。请注意,我们需要更改我们实际发出请求以正确解析数据的方式。下一个问题是如何返回数据。为了正确jsonify返回数据,我们将数据放入 python 字典而不是字符串中。

If you're calling your function to process the stripe payment from somewhere else (i.e. not using the python requestslibrary), another issue is that you may not be defining the jsonrequest properly for Flask to later interpret. If the issue still persists after making the above change to the processing function, post how you're making the jsonrequest elsewhere and I can take a look.

如果您正在调用您的函数来处理来自其他地方的条带支付(即不使用 pythonrequests库),另一个问题是您可能没有正确定义jsonFlask 稍后解释的请求。如果对处理功能进行上述更改后问题仍然存在,请在json其他地方发布您如何提出请求,我可以查看。

Let me know if this fixes your problems!

如果这能解决您的问题,请告诉我!

回答by Zyber

You should check the document Flask requests

您应该检查文档Flask requests

It does not define a body, instead you should try with

它没有定义一个主体,而是你应该尝试

request.get_json()

You just need to make sure you are specifying the correct mimetype which would be "application/json".

您只需要确保指定了正确的 mimetype,即“application/json”。

See request.get_json()methodfor more info

查看request.get_json()方法了解更多信息