stale association proxy, parent object has gone out of scope with Flask-SQLAlchemy

2024/9/27 15:32:16

I've actually never encountered this error before:

sqlalchemy.exc.InvalidRequestError: stale association proxy, parent object has gone out of scope

After doing some research, it looks like its because the parent object is being garbage collected while the association proxy is working. Fantastic.

However, I'm not sure where it's happening.

Relevant code:

# models.pyclass Artist(db.Model):# ...tags = association_proxy('_tags', 'tag', creator=lambda t: ArtistTag(tag=t))# ...class Tag(db.Model):# ...artist = association_proxy('_artists', 'artist', creator=lambda a: ArtistTag(artist=a))# ...class ArtistTag(db.Model):# ...artist_id = db.Column(db.Integer, ForeignKey('artists.id'))artist = db.relationship('Artist', backref='_tags')tag_id = db.Column(db.Integer, ForeignKey('tags.id'))tag = db.relationship('Tag', backref='_artists')# api/tag.py
from flask.ext.restful import Resource
from ..
class ListArtistTag(Resource):def get(self, id):# much safer in actual appreturn TagSchema(many=True).dump(Artist.query.get(id).tags).data
Answer

I know it's an old question, but I haven't found a clear solution to a similar problem anywhere on the web, so I've decided to reply here.

The key here is to assign the object that holds the association proxy to a variable before performing any further operations on them. Association proxies aren't regular object properties which would force the GC to hold the reference to the parent object. Actually, the call in form of:

tags = association_proxy('_tags', 'tag', creator=lambda t: ArtistTag(tag=t))

will result in creation of a new AssociationProxy class object, with a weak reference to the target's collection. In low memory conditions, GC may try to collect Artist.query.get(id) result, leaving just the result's tags collection (being a AssociationProxy class object), but it's required that the object having a association proxy to be present, due to SQLAlchemy's implementation (lazy loading mechanism precisely, I believe).

To fix this situation, we need to make sure that the Artist object returned from Artist.query.get(id) call is assigned to a variable, so that the reference count to that object is explicitly of non-zero value. So this:

class ListArtistTag(Resource):def get(self, id):# much safer in actual appreturn TagSchema(many=True).dump(Artist.query.get(id).tags).data

becomes this:

class ListArtistTag(Resource):def get(self, id):artist = Artist.query.get(id)return TagSchema(many=True).dump(artist.tags).data

And it will work as expected. Simple, right?

https://en.xdnf.cn/q/71444.html

Related Q&A

Automatic dictionary key resolution with nested schemas using Marshmallow

I have a Marshmallow schema where an objects use a key to refer to an object that is defined in a dictionary in another part of the structure. I want to have the key automatically resolved when deseria…

Type hinting for Django Model subclass

I have helper function for Django views that looks like this (code below). It returns None or single object that matches given query (e.g. pk=1). from typing import Type, Optionalfrom django.db.models …

How to diff the two files using Python Generator

I have one file of 100GB having 1 to 1000000000000 separated by new line. In this some lines are missing like 5, 11, 19919 etc. My Ram size is 8GB.How to find the missing elements.My idea take another …

How to resolve: attempted relative import with no known parent package [duplicate]

This question already has answers here:Attempted relative import with no known parent package [duplicate](4 answers)Closed 2 years ago.I have a bare bones project structure with mostly empty python fil…

How to create a figure of subplots of grouped bar charts in python

I want to combine multiple grouped bar charts into one figure, as the image below shows. grouped bar charts in a single figure import matplotlib import matplotlib.pyplot as plt import numpy as nplabels…

Python Pillow: Make image progressive before sending to 3rd party server

I have an image that I am uploading using Django Forms, and its available in the variable as InMemoryFile What I want to do is to make it progressive.Code to make an image a progressiveimg = Image.open…

Python - Should one start a new project directly in Python 3.x?

What Python version can you please recommend for a long-term (years) project? Should one use 2.6+ or 3.x is already stable? (only standard libraries are required)UPDATE: according to the answers belo…

Produce random wavefunction

I need to produce a random curve in matplotlib.My x values are from say 1 to 1000 for example. I dont want to generate scattered random y values, I need a smooth curve. Like some kind of very distorted…

How to reference groupby index when using apply, transform, agg - Python Pandas?

To be concrete, say we have two DataFrames:df1:date A 0 12/1/14 3 1 12/1/14 1 2 12/3/14 2 3 12/3/14 3 4 12/3/14 4 5 12/6/14 5df2:B 12/1/14 10 12/2/14 20 12/3/14 10 12/4/14 30 12/5/14 10 …

Google AppEngine Endpoints Error: Fetching service config failed (status code 404)

I am implementing the steps in the Quickstart.I did notice another question on this. I double checked that env_variables section in app.yaml has the right values for ENDPOINTS_SERVICE_NAME and ENDPOIN…