Home > Net >  flask - unable to run a variable to a list in for loop to store the sql database
flask - unable to run a variable to a list in for loop to store the sql database

Time:11-13

I'm unable to loop through the "query" variable with the items list and push the code to database. but it is throughing an error ""ValueError: not enough values to unpack (expected 2, got 1)"", can someone check the code please?

@app.route('/', methods=['POST'])
def test():
    if request.method == 'POST':
        try:
            query = request.form['url']
            r = requests.get(query)
            output = r.json()
            items = output['result']

            # # items = ['abc','bcd','cde','def'] # here items will be in list

            for i in items:
                user = User(listOfItems=items[i], query=query)
                db.session.add(user)
                db.session.commit()

            responseBody = {'message': items}
            return make_response(jsonify(responseBody))
        except Exception, e:
            return ('Oops!', e.__class__, 'occurred.')
    else:
        responseBody = {'message': 'failed'}
        return make_response(jsonify(responseBody))

desired output in database:

listOfItems     query           time_stamp
abc            example.com      -date-
bcd            example.com      -date-
cde            example.com      -date-
def            example.com      -date-
xyz            example1.com      -datetime.now-
yza            example1.com      -datetime.now-
zab            example1.com      -datetime.now-

here, query1: example.com returns ['abc','bcd','cde','def'] list items query2: example1.com returns ['xyz','yza','zab'] list items

CodePudding user response:

I found some problems:

  • you do not need the if request.method == 'POST' statement, you've already declared method in the route decorator.
  • for i in items returns each element from items, the i variable is not an index; so, user = User(listOfItems=items[i], query=query) is incorrect.

I'm not sure these will solve your problem or not; but if not, please show the output of items and output.

CodePudding user response:

This part of the code has an issue. for i in items means the value at that index, not the index itself. So the first iteration will return 'abc' and so on.

  for i in items:
      user = User(listOfItems=items[i], query=query)
      db.session.add(user)
      db.session.commit()

Assuming that you want to have the values of the list and insert them, change the line to

      user = User(listOfItems=i, query=query)
  • Related