English 中文(简体)
• 如何获得一个记录。
原标题:How to get one record with SQLAlchemy?

I m试图利用flasksqlite开发一个网页。 使用<代码>sqlalchemy与db I m通信。

在我下面的《守则》中,我制定了全球教育体系方法,将所有数据检索到一个具体表格中,以便:

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)

我愿建立<代码>GET方法,以检索具有特定价值的具体记录,例如:

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

我不知道如何检索单一记录。 任何帮助?

问题回答

这将有助于取得<代码>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

session 具体如下:

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()

rel=“noreferer”>SQLAlchemy

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()

问题很老,但另一种技术可以帮助有问题的其他人。

def load_user(id):
    falesie.query.get(int(id))

For those now here looking for a way with SQLAlchemy 2.0--you can use this method (get_one()):

from sqlalchemy.orm import Session
from sqlalchemy.orm.exc import NoResultFound

# create your session

try:
    obj = session.get_one(YourDbModel, pk_id)
except NoResultFound:
    # handle




相关问题
Can Django models use MySQL functions?

Is there a way to force Django models to pass a field to a MySQL function every time the model data is read or loaded? To clarify what I mean in SQL, I want the Django model to produce something like ...

An enterprise scheduler for python (like quartz)

I am looking for an enterprise tasks scheduler for python, like quartz is for Java. Requirements: Persistent: if the process restarts or the machine restarts, then all the jobs must stay there and ...

How to remove unique, then duplicate dictionaries in a list?

Given the following list that contains some duplicate and some unique dictionaries, what is the best method to remove unique dictionaries first, then reduce the duplicate dictionaries to single ...

What is suggested seed value to use with random.seed()?

Simple enough question: I m using python random module to generate random integers. I want to know what is the suggested value to use with the random.seed() function? Currently I am letting this ...

How can I make the PyDev editor selectively ignore errors?

I m using PyDev under Eclipse to write some Jython code. I ve got numerous instances where I need to do something like this: import com.work.project.component.client.Interface.ISubInterface as ...

How do I profile `paster serve` s startup time?

Python s paster serve app.ini is taking longer than I would like to be ready for the first request. I know how to profile requests with middleware, but how do I profile the initialization time? I ...

Pragmatically adding give-aways/freebies to an online store

Our business currently has an online store and recently we ve been offering free specials to our customers. Right now, we simply display the special and give the buyer a notice stating we will add the ...

Converting Dictionary to List? [duplicate]

I m trying to convert a Python dictionary into a Python list, in order to perform some calculations. #My dictionary dict = {} dict[ Capital ]="London" dict[ Food ]="Fish&Chips" dict[ 2012 ]="...

热门标签