mardi 28 mars 2017

Creating Key/Value JSON object with random integers and Flask

I recently was asked for homework to expand upon a Flask application so that a route is created which will roll two dice and return the outcome as a JSON object. I thought I had completed the program correctly but was disappointed to find out that what my code is producing is not a JSON object? Would anyone know how I would take the code below and return the dice roll as a key/value pair? At this point in time when I visit the rolldice route the output is Jsonified as the sum of the two dice rolls. I'm not sure how I can turn this into a key/value pair. Any help is appreciated, thanks again.

Here is my code:

from flask import Flask
from flask import jsonify
app = Flask(__name__)

import json
import random

@app.route('/')
def hello_world():
    return 'Hello World!'

# Create a route and function for rolling dice.
@app.route('/rolldice')
def dieobject():
    # Define rollcount
    rollcount = []
    # Define the number of times we will roll two dice.
    for i in range(0, 1):
        # Define rolling two dice.
        two_dieobject = random.randint(1, 6) + random.randint(1, 6)
        # Take output of our dice roll and pass it to rollcount.
        rollcount.append(two_dieobject)
    # Return the value of rollcount as JSON Data.
    # Data will be presented as one integer which is the sum of two dice rolls.
    return jsonify(rollcount)

if __name__ == '__main__':
    app.debug = True
    app.run()




Aucun commentaire:

Enregistrer un commentaire