Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get one record with SQLAlchemy?

I'm trying to develop a web api using flask and sqlite. For communication with db I'm using sqlalchemy.

In the code that I post below I have create a GET method to retrieve all data into a specific table into db:

from flask import Flask, g, Response, request, jsonify, abort
from flask_restful import Resource, Api
from sqlalchemy import create_engine
from flask.ext.restless import APIManager
from flask.ext.sqlalchemy import SQLAlchemy
from json import dumps
import sqlite3
import json


app = Flask(__name__)
app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:///climb.db"
db = SQLAlchemy(app)

class falesie(db.Model):
    __tablename__ = 'falesie'
    id = db.Column(db.Integer, primary_key=True)
    regione = db.Column(db.String(20))
    citta = db.Column(db.String(20))
    n_settori = db.Column(db.Integer)
    lat = db.Column(db.Float)
    lon = db.Column(db.Float)

    def __init__(self, regione, citta, n_settori, lat, lon):
      self.regione = regione
      self.citta = citta
      self.n_settori= n_settori
      self.lat = lat
      self.lon = lon

@app.route('/dev', methods = ['GET'])
def get_falesie():
    Falesie = falesie.query.all()
    formatted_falesie = []
    for f in Falesie:
        formatted_falesie.append({
        'id': f.id,
        'regione': f.regione,
        'citta': f.citta,
        'n_settori': f.n_settori,
        'lat': f.lat,
        'lon': f.lon})
    return json.dumps({'Falesie': formatted_falesie}), 200, {'Content-  Type': 'application/json'}


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

I would like to create a GET method to retrieve a specific record with a specific value, as in this example:

@app.route('dev/<string:name>')
def get_data(name):

I don't know how to retrieve a single record. Any help please?

like image 392
dev_ Avatar asked Mar 03 '16 14:03

dev_


People also ask

How to get result of a single column query using SQLAlchemy?

So, when we run a single column query using SQLAlchemy we get a result. The result object will contain tuples of values of that single column query. This is how the basic functionality works. Let us fetch all the names using SQLAlchemy and see the result obtained. The SQL query will look like this:

How SQLAlchemy Orm works?

The following image shows the result − All SELECT statements generated by SQLAlchemy ORM are constructed by Query object. It provides a generative interface, hence successive calls return a new Query object, a copy of the former with additional criteria and options associated with it.

What is query from self method in SQLAlchemy?

methodsqlalchemy.orm.Query.from_self(*entities)¶ return a Query that selects from this Query’s SELECT statement. Deprecated since version 1.4: The Query.from_self()method is considered legacy as of the 1.x series of SQLAlchemy and will be removed in 2.0.

What is the difference between SQL and SQLAlchemy?

The SQL Expression Language constructs its expressions against table columns. SQLAlchemy Column object represents a column in a database table which is in turn represented by a Tableobject. Metadata contains definitions of tables and associated objects such as index, view, triggers, etc.


3 Answers

Question is very old but one more technique can help to others having problem.

def load_user(id):
    falesie.query.get(int(id))
like image 71
Abhishek Avatar answered Oct 06 '22 20:10

Abhishek


This should help with getting a single result of falesie:

try:
    user = session.query(falesie).filter(name=name).one()  # filter on name
except MultipleResultsFound, e:
    print e
    # Deal with it
except NoResultFound, e:
    print e
    # Deal with that as well

Where session is obtained as following:

from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker

# an Engine, which the Session will use for connection resources
engine = create_engine('sqlite:///climb.db')

# create a configured "Session" class
Session = sessionmaker(bind=engine)

# create a Session
session = Session()

See SQLAlchemy documentation for more details.

like image 44
Forge Avatar answered Oct 06 '22 19:10

Forge


If you read the tutorial, you'll see that you can filter your query. Something like this should be what you want:

falesie.query().filter_by(id=name).first()
like image 20
Wayne Werner Avatar answered Oct 06 '22 19:10

Wayne Werner