Python Forum

Full Version: SQLAlchemy query return last row only
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi,
Bit stuck with this one, I am trying my code out in shell. I am following this tutorial and this tutorialto make the gpio of pi operate from a web page, storing the pin state in a database. I have been advised to use SQLAlchemy to make querying easier. Here is my code.
from homeHeating.models import User, Pins
from homeHeating import db
import RPi.GPIO as GPIO
GPIO.setmode(GPIO.BCM)
from homeHeating import create_app
app = create_app()
app.app_context().push()
GPIO.setwarnings(False)

pins = Pins.query.all()
for pin in pins:
    GPIO.setup(pin.pin, GPIO.OUT)
    GPIO.output(pin.pin, GPIO.HIGH)
    pin.state = GPIO.input(pin.pin)
    db.session.commit()
    print(pin.state)
Output:
... 1 1 1 1
this works fine and sets me up for the next phase which is:
def action(changePin, action):
    pins = Pins.query.all()
    for pin in pins:
        changePin = int(pin.pin)
        if action == "on":
            GPIO.output(changePin, GPIO.HIGH)
        if action =="off":
            GPIO.output(changePin, GPIO.LOW)
        pin.state = GPIO.input(pin.pin)
        db.session.commit()
    print(changePin, action)
there is no error code but the wrong pin is being altered, the following shows the pins in the database:
Output:
>>> for pin in pins: ... print(pin.pin) ... 18 23 25 5
but when I try the function I get:
Output:
>>> action(18, "on") 5 on
or
Output:
>>> for pin in pins: ... action(18, "on") ... 18 on 23 on 25 on 5 on
The sate of the pins is changed but not the one I want on its own.
Any ideas? Smile


I have solved it the changePin code should be
def action(changePin, action):
    pins = Pins.query.all()
    for pin in pins:
        changePin = int(changePin)# this was the problem!
        if action == "on":
            GPIO.output(changePin, GPIO.HIGH)
        if action =="off":
            GPIO.output(changePin, GPIO.LOW)
        pin.state = GPIO.input(pin.pin)
        db.session.commit()
    print(changePin, action)