Home > Enterprise >  Sending random data to API using Python Flask
Sending random data to API using Python Flask

Time:09-22

I am trying to send random data to API using python flask with intervals of 1 second. But it only shows the last array of data. I am using the following code:

import time
import random
import datetime
from flask import Flask

mylist = []
ct = datetime.datetime.now()

app = Flask(__name__)

@app.route('/')

def index():
    mylist = []
    ct = datetime.datetime.now()
    for i in range(0, 61):
        x = random.randint(1, 100)
        mylist.append(x)

        if len(mylist) == 11:
            right_in_left_out = mylist.pop(0)
        else:
            right_in_left_out = None

        time.sleep(1)
        print(mylist)
    return mylist

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

OUTPUT:

WARNING: This is a development server. Do not use it in a production deployment. Use a production WSGI server instead. * Running on enter image description here

I am looking to send data the same way as it is being displayed in the IDE with 1 sec intervals.

CodePudding user response:

The problem lies here

if len(mylist) == 11:
        right_in_left_out = mylist.pop(0)

Once this code executes for the first time, your list size is back to 10 , further iterations everytime it becomes 11 and then back to 10!

CodePudding user response:

Your code is returning a list, and that is logical. If you want to return all the lists like the ones you displayed, you have to store them in a list of lists. I mean by that:

    all_lists = []
    mylist = []
    ct = datetime.datetime.now()
    for i in range(0, 61):
        x = random.randint(1, 100)
        mylist.append(x)

        if len(mylist) == 11:
            right_in_left_out = mylist.pop(0)
            all_lists.append(mylist)
        else:
            right_in_left_out = None

        time.sleep(1)
        print(mylist)
    return all_lists

There is also no need to use right_in_left_out variable in your code.

  • Related