使用SQLAlChemy的sql.func注册自定义函数

Register a custom function with SQLAlchemy#39;s sql.func(使用SQLAlChemy的sql.func注册自定义函数)

本文介绍了使用SQLAlChemy的sql.func注册自定义函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在sqlalChemical中应用自定义过滤?我已经尝试了@HIXED_PROPERTY和@HIXED_Method。然而,他们正在给出错误。以下是我的代码:

class Product(db.Model):
    __tablename__ = 'products'
    id = db.Column(db.Integer, primary_key=True)
    owner_id = db.Column(db.Integer, db.ForeignKey('users.id'), nullable=False)
    keywords  = db.Column(db.String(64)) # keywords for ease of browsing
    details = db.Column(db.Text)
    removed = db.Column(db.Boolean, default=False)
    @hybrid_method
    def toKeywordLevenshteinDistance(self, keywords):
        """
        :param user input product keywords
        :return Levenshtein(user_input_keywords, product_keywords)
        """
        return fuzz.partial_ratio(self.keywords, keywords)
    
    @toKeywordLevenshteinDistance.expression
    def toKeywordLevenshteinDistance(cls, keywords):
        return func.fuzz.partial_ratio(cls.keywords, keywords)

>>> p=similarProducts('jrjk')

以下是输出:

File "C:UsersAllWattAppflaskmyStoreEnvlibsite-packagessqlalchemyenginedefault.py", 
line 608, in do_execute
cursor.execute(statement, parameters)
sqlalchemy.exc.OperationalError: (sqlite3.OperationalError) no such function: levenshtein
    [SQL: SELECT products.id AS products_id, products.owner_id AS products_owner_id, 
    products.keywords AS products_keywords, products.details AS products_details,
    products.removed AS products_removed, products."when" AS products_when FROM products
    WHERE levenshtein(products.keywords, ?) > ?] [parameters: ('jrjk', 20)]
(Background on this error at: http://sqlalche.me/e/13/e3q8)

推荐答案

您可以使用事件侦听器在连接时向SQLite注册自定义函数。这里有一个简单的示例:

from flask import Flask
from flask_sqlalchemy import SQLAlchemy
import sqlalchemy as sa

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite://'

db = SQLAlchemy(app)


def doubleit(word):
    return word * 2


@sa.event.listens_for(db.engine, 'connect')
def on_connect(dbapi_connection, connection_record):
    dbapi_connection.create_function('doubleit', 1, doubleit)


@app.route('/<word>')
def word_doubler(word):
    result = db.session.query(sa.func.doubleit(word))
    return result.scalar()


if __name__ == '__main__':
    app.run(debug=True)

相关单据:

  • SQLAlchemy connection pool connect event
  • Python sqlite3 create function

这篇关于使用SQLAlChemy的sql.func注册自定义函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:使用SQLAlChemy的sql.func注册自定义函数

基础教程推荐