如何使用 SQLAlchemy 获取一条记录? [英] How to get one record with SQLAlchemy?

查看:94
本文介绍了如何使用 SQLAlchemy 获取一条记录?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 flasksqlite 开发 Web api.为了与数据库通信,我使用 sqlalchemy.

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

在我在下面发布的代码中,我创建了一个 GET 方法来将特定表中的所有数据检索到数据库中:

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)

我想创建一个 GET 方法来检索具有特定值的特定记录,如下例所示:

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?

推荐答案

这应该有助于获得 falesie 的单一结果:

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

哪里session 得到如下:

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

请参阅 SQLAlchemy 文档了解更多详情.

See SQLAlchemy documentation for more details.

这篇关于如何使用 SQLAlchemy 获取一条记录?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆