Forums

flask.get_json() doesnt return the complete data?

I am using python requests.post to send json data from my client to my server.

I use flask.get_json() to retrieve the posted data but this is all i am getting back as shown in my server log.

{'local_id': 'TR7bNoUzKiS3D4FGzdVLjFTQ7s62', 'id_token': 'eyJhbGciOiJSUzI1NiIsImtpZCI6IjUxNDAyYjNkMDQyYjI5NzY5NDNmMDVmZTJlZDQyOWI3MzY0M2Y2NTEiLCJ0eXAiOiJKV1QifQ.eyJpc3MiOiJodHRwczovL3NlY3VyZXRva2VuLmdvb2dsZS5jb20vb21uaXZlcnNlLWEwZDc2IiwiYXVkIjoib21uaXZlcnNlLWEwZDc2IiwiYXV0aF90aW1lIjoxNTYyNDI5MDAxLCJ1c2VyX2lkIjoiVFI3Yk5vVXpLaVMzRDRGR3pkVkxqRlRRN3M2MiIsInN1YiI6IlRSN2JOb1V6S2lTM0Q0Rkd6ZFZMakZUUTdzNjIiLCJpYXQiOjE1NzkwMTMyMDcsImV4cCI6MTU3OTAxNjgwNywiZW1haWwiOiJhc2RhZGFzQGdtYWlsLmNvbSIsImVtYWlsX3ZlcmlmaWVkIjpmYWxzZSwiZmlyZWJhc2UiOnsiaWRlbnRpdGllcyI6eyJlbWFpbCI6WyJhc2RhZGFzQGdtYWlsLmNvbSJdfSwic2lnbl9pbl9wcm92aWRlciI6InBhc3N3b3JkIn19.dSN2tGi34gA_hbPt-rA7KMrvkhvri02XDqUA5gkq-6o6Mka_LmYPlBGs5T5SFjY5SuM5XsMYQpheTHPjAZo7vhtM2D6RKZvzCy-aLpqNLcube0hpV0vSsw9qyC-GVeX1GW27yh0XCpCsbehZlpx68bGOB1vec_rMKu71xHBpgPKosM9AQvjvl6enMcnpkVojvNKBfzsVHc26BfI16WZJTgkFOzXqoE3XuiwBI7ca9SLkBByOwYUPrnIxM6tbJlAjYD0EfP4iz72WbpIs6CRtF2C4hmKvb4qsp7nB7jr8RZTPmCdRNuQZlMuhJ

As shown above, the json isnt complete as there is no closing curly bracket "}" and there are more remaining characters missing behind. May i know what can be done to get the complete form of data? Thanks in advance.

[edit by admin: formatting]

I do something like this to print out the full json/dictionary , then work on splitting it up:

r10 = requests.get('http://api.openweathermap.org/data/2.5/weather?***********')
    a10 = BeautifulSoup(r10.text, 'html.parser')

    jayson10 = str(a10)
    b10 = json.loads(jayson10)
    d10 = b10

print(d10)

top line needs to be inline with others

just to clarify my client here is the mobile app to post json to my server, should i still use html parser for my case?

The server logs may truncate very long log lines to ensure that the log server does not spend all it's time logging a gigantic line and preventing other users from logging.

I don't understand what the beautiful soup is there for in your code. If the API returns json, just process the json that the API returns.

I just realized that my server runs the function twice.

When i set user_id and print it, the second responds is return as None. Which means i cant subscript the json causing it to crash.

user_id = request.get_json()
print(user_id) ****returns None
print(user_id['local_id']) *****returns Nonetype is not subscriptable.

Any idea how to disable it from running twice? Because the first responds is fine. Just the second responds is returning None. Thanks

Could you post the full code for your view function?

import stripe import json from flask import Flask, render_template, request from flask_http_response import success, error #, result, error

app = Flask(__name__)

with open ('/home/sean123/stripe_api_key.txt') as f:
    key = f.read()

stripe.api_key = key

@app.route('/stripe-webhook',methods=['POST'])
def webhook():
    webhook_data=request.data
    event = None
    try:
        event = stripe.Event.construct_from(
            json.loads(webhook_data),stripe.api_key
            )
    except ValueError as e:
        # Invalid payload
        return error.return_response(message='Successfully Incomplete', status=400)

    # Handle the event
    if event.type == 'checkout.session.completed':
        #payment_intent = event.data.object
        print('PaymentIntent was successful!')
    elif event.type == 'payment_method.attached':
        #payment_method = event.data.object # contains a stripe.PaymentMethod
        print('PaymentMethod was attached to a Customer!')
    # ... handle other event types
    else:
        # Unexpected event type
        return error.return_response(message='Unexpected event.', status=400)

    return success.return_response(message='Successfully Completed', status=200)

@app.route('/',methods=['GET', 'POST'])
def payment():
    #global user_id
    #global user_token
    print ("the data received is",request.is_json)
    user_id = request.get_json()
        #print (value)
    print(user_id)
    session = stripe.checkout.Session.create(
      customer_email=None,
      payment_method_types=['card'],
      line_items=[{
        'name': 'T-shirt',
        'description': 'Comfortable cotton t-shirt',
        'images': ['https://example.com/t-shirt.png'],
        'amount': 1000,
        'currency': 'myr',
        'quantity': 1,
      }],
      success_url='https://example.com/success/?session_id={CHECKOUT_SESSION_ID}',
      cancel_url='https://example.com',
      billing_address_collection = 'required'
    )

    session_id = session['id']
    return render_template("web.html", data=session_id)


if __name__ == "__main__":
    app.run(debug=False)



##    from waitress import serve
##    serve(app, host="0.0.0.0", port=8080)

import stripe import json from flask import Flask, render_template, request from flask_http_response import success, error #, result, error

app = Flask(__name__)

with open ('/home/sean123/stripe_api_key.txt') as f:
    key = f.read()

stripe.api_key = key

@app.route('/stripe-webhook',methods=['POST'])
def webhook():
    webhook_data=request.data
    event = None
    try:
        event = stripe.Event.construct_from(
            json.loads(webhook_data),stripe.api_key
            )
    except ValueError as e:
        # Invalid payload
        return error.return_response(message='Successfully Incomplete', status=400)

    # Handle the event
    if event.type == 'checkout.session.completed':
        #payment_intent = event.data.object
        print('PaymentIntent was successful!')
    elif event.type == 'payment_method.attached':
        #payment_method = event.data.object # contains a stripe.PaymentMethod
        print('PaymentMethod was attached to a Customer!')
    # ... handle other event types
    else:
        # Unexpected event type
        return error.return_response(message='Unexpected event.', status=400)

    return success.return_response(message='Successfully Completed', status=200)

@app.route('/',methods=['GET', 'POST'])
def payment():
    #global user_id
    #global user_token
    print ("the data received is",request.is_json)
    user_id = request.get_json()
    #print (value)
    print(user_id)
    session = stripe.checkout.Session.create(
      customer_email=None,
      payment_method_types=['card'],
      line_items=[{
        'name': 'T-shirt',
        'description': 'Comfortable cotton t-shirt',
        'images': ['https://example.com/t-shirt.png'],
        'amount': 1000,
        'currency': 'myr',
        'quantity': 1,
      }],
      success_url='https://examplecom/success/?session_id={CHECKOUT_SESSION_ID}',
      cancel_url='https://www.example.com',
      billing_address_collection = 'required'
    )

    session_id = session['id']
    return render_template("web.html", data=session_id)


if __name__ == "__main__":
    app.run(debug=False)



##    from waitress import serve
##    serve(app, host="0.0.0.0", port=8080)

Add a print of method or check your access log if the other request is really the post one.

not sure what you mean by that, but my payment() method is always running twice as shown in my log file

Sorry for the confusion. Do you intend to have the same function work with both gets and posts and both carry json data? At a moment it looks like work in progress code and I was not able to get a clear picture.