1

I have a simple python/flask api that I am unable to match an input in the api to mysql select results:

mycursor = mydb.cursor()
mycursor.execute('SELECT code FROM users')
codes = mycursor.fetchall()

codes prints like so '[('0000',), ('0001',), ('0003',)]'

Here is the api route and lookup code:

# API route for when a code is passed
@app.route('/api/v1/codes', methods=['GET'])
def checkcode():
    # Check if a code was provided as part of the URL.
    # If code is provided, assign it to a variable.
    # If no code is provided, display an error in the browser.
    if 'id' in request.args:
        code = request.args['id']
        print(id)
    else:
        return "Error: No id field provided. Please specify an id."

    # Check if code matches
    if code in codes:
        #unlock(),
        pushMessage("Message from PiAPI", "Building Door Unlocked.")
    else:
        wrong = 'Wrong Code was sent ' + (code)
        pushMessage('Message from PiAPI', wrong)

I've tried getting the code to match in every way I can conceive like so:

code = "('" + request.args['id'] + "',)"
code = "'" + request.args['id'] + "',"
code = "'" + request.args['id'] + "'"

Nothing has matched so far so even though it looks correct it and gets sent correctly in the else: pushmessage. In the api I'm entering 0000 (/api/v1/codes?id=0000)

I'm 42 and brand new to coding so please forgive any stupidity. :)

1
  • Flatten your code list like this: codes = [record[0] for record in codes], and the rest of the route should work as you expect. Commented May 27, 2020 at 3:55

1 Answer 1

1

Basing this answer of off @mechanical_meat code in the comment above.

Currently you have

codes = [('0000',), ('0001',), ('0003',)]

which is a list with tuples inside it.

Thus what you end up comparing when id=0000

if 0000 == ('0000',):

Which as you have pointed out is always false

codes = [record[0] for record in codes]

will change it to look like this:

codes = ['0000', '0001', '0003']

i.e flatten it

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.