【问题标题】:sqlalchemy cache results in wrong response in a Flask REST API [duplicate]sqlalchemy 缓存导致 Flask REST API 中的错误响应 [重复]
【发布时间】:2021-12-10 04:16:40
【问题描述】:

我正在使用 Flask 和 SQLAlchemy 构建一个 REST API。

我遇到了一个问题:如果我使用内部调用 SQLAlchemy 删除的 HTTP DELETE 删除资源,如果我从数据库中重新创建该元素并尝试使用 GET 访问该资源,我将收到 404 Not Found .

日志显示: 2021-10-24 11:37:21,736 INFO sqlalchemy.engine.Engine [cached since [..]s ago] {'isbn_1': '12312', 'param_1': 1}.

看起来从数据库中提取的方法由于某种原因停留在资源不存在的状态,即使我在 HTTP 删除后使用相同的详细信息重新创建它。

这肯定和缓存有关,我不知道如何处理这种情况。

模型 - sqlalchemy

from books import Book
from db import Session, engine

local_session = Session(bind=engine)


def get_book_by_isbn(isbn):
    """
    Wrapper for an ORM call that is retrieving a book by its ISBN.

    :param isbn: isbn code of the book that is to be retrieved
    """
    response = OperationResponseWrapper()
    try:
        response.payload = local_session.query(Book).filter(Book.isbn == isbn).first()
        if not response.payload:
            response.completed_operation = False
        else:
            response.completed_operation = True
    except Exception as e:
        response.erorr = e
        response.completed_operation = False

    return response


def delete_book_by_isbn(isbn):
    """
    Wrapper for an ORM call that is deleting a book by its ISBN.

    :param isbn: isbn code of the book that is to be deleted
    """
    response = OperationResponseWrapper()

    try:
        book_to_delete = local_session.query(Book).filter(Book.isbn == isbn).first()

        if book_to_delete:
            local_session.delete(book_to_delete)
            local_session.commit()
        else:
            response.completed_operation = False

    except Exception as e:
        response.completed_operation = False
        response.erorr = e

    return response

控制器 - 烧瓶


from model import get_book_by_isbn, delete_book_by_isbn

[..]
@app.route('/api/bookcollection/books/<isbn>', methods=['GET'])
def get_book(isbn):
    """
    Method that handles a GET request for a book by the ISBN code.

    :param isbn: isbn code of the book that is to be retrieved
    """
    db_response = get_book_by_isbn(str(isbn))
    body = ''
    status = 200
    if db_response.erorr:
        status = 404
        body = ErrorDto(404, str(db_response.erorr), 'EXCEPTION')
    elif not db_response.completed_operation:
        status = 404
        body = ErrorDto(404, 'Requested book does not exist.', 'INVALID_OPERATION')
    else:
        status = 200
        links = LinkDto(request.path, 'books', request.method)
        body = BookDto(db_response.payload, links)

    return jsonify(body.__dict__), status


@app.route('/api/bookcollection/books/<isbn>', methods=['DELETE'])
def delete_book(isbn):
    """
    Method that handles a DELETE request for a book by the ISBN code.

    :param isbn: isbn code of the book that is to be deleted
    """
    db_response = delete_book_by_isbn(isbn)
    body = ''
    status = 200
    if db_response.erorr:
        status = 404
        body = ErrorDto(404, str(db_response.erorr), 'EXCEPTION')
    elif not db_response.completed_operation:
        status = 404
        body = ErrorDto(404, 'Requested book does not exist.', 'INVALID_OPERATION')
    else:
        status = 200
        links = LinkDto(request.path, 'books', request.method)
        body = StatusDto(200, 'Operation was completed successfully.', links)

    return jsonify(body.__dict__), status

【问题讨论】:

    标签: python sqlalchemy


    【解决方案1】:

    好的,我似乎在这个帖子中找到了一些解决方案:How to disable SQLAlchemy caching?

    engine = create_engine(connection_string, echo=True, isolation_level="READ UNCOMMITTED")
    

    添加 isolation_level="READ UNCOMMITTED" 似乎有所帮助,但我不确定此操作还有什么其他影响。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-10-03
      • 1970-01-01
      • 2015-08-20
      • 1970-01-01
      • 2017-09-03
      • 2018-12-08
      • 2018-09-12
      • 2018-06-12
      相关资源
      最近更新 更多