Python Forum
SQLAlchemy query return last row only
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
SQLAlchemy query return last row only
#1
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)
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  python code (embedded in Redshift) to return result of the query Mel 0 2,408 Aug-24-2018, 06:12 PM
Last Post: Mel
  Sqlalchemy Query into tuple KirkmanJ 0 2,432 Jul-10-2018, 02:56 PM
Last Post: KirkmanJ

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020