So I am successfully storing a complex object (non-model) in my session in development. I've tried every session engine and cache type and they are all working in development (Pycharm). However, when I move the code to production, while no error are thrown, the session losses the object.
Here is the method I use to set the session object:
def instantiate_command_object(request):
try:
ssc = request.session['specimen_search_criteria']
logger.debug('found ssc session variable')
except KeyError:
logger.debug('failed to find ssc session variable')
ssc = SpecimenSearchCommand()
return ssc
Then in a method that runs asynchronously via an ajax call I start making changes to the object in the session:
def ajax_add_collection_to_search(request):
ssc = instantiate_command_object(request)
collection_id = request.GET.get('collection')
collection = Collection.objects.get(pk=collection_id)
if collection and collection not in ssc.collections:
ssc.collections.append(collection)
# save change to session
request.session['specimen_search_criteria'] = ssc
# refresh search results
ssc.search()
return render(request, '_search.html')
All this works as far as it goes. However, if I then refresh the browser, the session is lost. Here is a snippet from the template:
{% with criteria=request.session.specimen_search_criteria %}
<div class="search-criteria" id="search-criteria">
<div class="row">
Sesssion:
{{ request.session }}<br/>
Search:
{{ request.session.specimen_search_criteria }}<br/>
Created:
{{ request.session.specimen_search_criteria.key }}<br/>
Collections:
{{ request.session.specimen_search_criteria.collections }}<br/>
Again, in development I can refresh all day and the same object will be returned. In production, it will either create a new object or occasionally will return a previously created copy.
A few relevant items:
The production server is running Apache httpd with mod_wsgi.
I've tried memcached, databasecache, etc. the behavior remains the same. Always works in development, never in production.
I've tried it with
SESSION_SERIALIZER = 'django.contrib.sessions.serializers.PickleSerializer'
and without. I can see the session info in the database and when I unpickle it it just seems to be pointing to a location in memory for the complex object.
I'm guessing this might have something to do with running in a multi-user environment, but again, I'm not using locmem and I've tried all of the caching approaches to no effect.
To be clear, the session itself seems to be fine, I can store a string or other simple item in it and it will stick. It's the complex object within the session that seems to be getting lost.
Edit: I might also point out that if I refresh the browser immediately following the return of the search criteria it will actually return successfully. Anything more than about a second and it will disappear.
Edit (adding code of SpecimenSearchCommand):
class SpecimenSearchCommand:
def __init__(self):
pass
created = datetime.datetime.now()
key = ''.join(random.SystemRandom().choice(string.ascii_uppercase + string.digits) for _ in range(6))
jurisdictions = []
taxa = []
strata = []
collections = []
chrons = []
has_images = False
query = None # The active SQL query, not the actual result records
page_size = 50
current_page = 1
sort_order = 'number'
results = [] # Page of results from paginator
def is_empty(self):
if len(self.jurisdictions) == 0 and len(self.taxa) == 0 and len(self.strata) == 0 and \
len(self.collections) == 0 and len(self.chrons) == 0 and self.has_images is False:
return True
else:
return False
def get_results(self):
paginator = Paginator(self.query, self.page_size)
try:
self.results = paginator.page(self.current_page)
except PageNotAnInteger:
self.results = paginator.page(1)
except TypeError:
return []
except EmptyPage:
self.results = paginator.page(paginator.num_pages)
return self.results
def get_results_json(self):
points = []
for s in self.results:
if s.locality.latitude and s.locality.longitude:
points.append({"type": "Feature",
"geometry": {"type": "Point",
"coordinates": [s.locality.longitude, s.locality.latitude]},
"properties": {"specimen_id": s.id,
"sci_name": s.taxon.scientific_name(),
"cat_num": s.specimen_number(),
"jurisdiction": s.locality.jurisdiction.full_name()}
})
return json.dumps({"type": "FeatureCollection", "features": points})
def search(self):
if self.is_empty():
self.query = None
return
query = Specimen.objects.filter().distinct().order_by(self.sort_order)
if len(self.taxa) > 0:
query = query.filter(taxon__in=get_hierarchical_search_elements(self.taxa))
if len(self.jurisdictions) > 0:
query = query.filter(locality__jurisdiction__in=get_hierarchical_search_elements(self.jurisdictions))
if len(self.strata) > 0:
query = query.filter(stratum__in=get_hierarchical_search_elements(self.strata))
if len(self.chrons) > 0:
query = query.filter(chron__in=get_hierarchical_search_elements(self.chrons))
if len(self.collections) > 0:
query = query.filter(collection__in=get_hierarchical_search_elements(self.collections))
if self.has_images:
query = query.filter(images__isnull=False)
self.query = query
return
def get_hierarchical_search_elements(elements):
search_elements = []
for element in elements:
search_elements = set().union(search_elements, element.get_descendants(True))
return search_elements
OK, so as Daniel pointed out, the attributes of the SSC class were class-level instead of instance level. The correct version looks like this now:
self.created = datetime.datetime.now()
self.key = ''.join(random.SystemRandom().choice(string.ascii_uppercase + string.digits) for _ in range(6))
self.jurisdictions = []
self.taxa = []
self.strata = []
self.collections = []
self.chrons = []
self.has_images = False
self.query = None # The active SQL query, not the actual result records
self.page_size = 50
self.current_page = 1
self.sort_order = 'number'
self.results = [] # Page of results from paginator
I translated TreeView gtk2 tooltip in Gtk3
It's almost running but I have problem to manage coordinate of tooltip window.
I Would like the tooltip window locate near the mouse et follow it near. Instead of my project where the tooltip window is located in the corner of screen
my code is
#!/usr/bin/env python
# coding: utf-8
'''
warning data not update !!!!!!!!!!!!!
TreeViewTooltips.py
Provides TreeViewTooltips, a class which presents tooltips for cells,
columns and rows in a Gtk.TreeView.
------------------------------------------------------------
This file includes a demo. Just execute the file:
python TreeViewTooltips.py
------------------------------------------------------------
To use, first subclass TreeViewTooltips and implement the get_tooltip()
method; see below. Then add any number of Gtk.TreeVew widgets to a
TreeViewTooltips instance by calling the add_view() method. Overview
of the steps:
# 1. subclass TreeViewTooltips
class MyTooltips(TreeViewTooltips):
# 2. overriding get_tooltip()
def get_tooltip(...):
...
# 3. create an instance
mytips = MyTooltips()
# 4. Build up your Gtk.TreeView.
myview = Gtk.TreeView()
...# create columns, set the model, etc.
# 5. Add the view to the tooltips
mytips.add_view(myview)
How it works: the add_view() method connects the TreeView to the
"motion-notify" event with the callback set to a private method.
Whenever the mouse moves across the TreeView the callback will call
get_tooltip() with the following arguments:
get_tooltip(view, column, path)
where,
view: the Gtk.TreeView instance.
column: the Gtk.TreeViewColumn instance that the mouse is
currently over.
path: the path to the row that the mouse is currently over.
Based on whether or not column and path are checked for specific
values, get_tooltip can return tooltips for a cell, column, row or the
whole view:
Column Checked Path Checked Tooltip For...
Y Y cell
Y N column
N Y row
N N view
get_tooltip() should return None if no tooltip should be displayed.
Otherwise the return value will be coerced to a string (with the str()
builtin) and stripped; if non-empty, the result will be displayed as
the tooltip. By default, the tooltip popup window will be displayed
centered and just below the pointer and will remain shown until the
pointer leaves the cell (or column, or row, or view, depending on how
get_tooltip() is implemented).
'''
from gi.repository import Gtk
class TreeViewTooltips_gtk3:
"""tooltip atttach to Treeview in Gtk3
this window is moving to follow row of Treeview"""
def __init__(self):
self.win = Gtk.Window()
self.win.set_decorated(False)
self.win.set_default_size(-1, -1)
self.label = Gtk.Label()
self.win.add(self.label)
# by default, the tooltip is enabled
self.__enabled = True
def __show(self, tooltip, x, y):
"""in order to move the tooltip near row of Treeview"""
self.label.set_markup(tooltip)
w,h = self.win.get_preferred_width()
# move the window
self.win.move(*self.location(x,y,w,h))
# show it
self.win.show_all()
return self.win
def __leave_handler(self, view, event):
"""when the pointer leaves the view, hide the tooltip"""
self.win.hide()
def enable(self):
'Enable the tooltip'
self.__enabled = True
def disable(self):
'Disable the tooltip'
self.__enabled = False
def location(self, x, y, w, h):
'''Given the x,y coordinates of the pointer and the width and
height (w,h) demensions of the tooltip window, return the x, y
coordinates of the tooltip window.
The default location is to center the window on the pointer
and 4 pixels below it.
# en clair c'est un décalage de position de la fenetre qui s'ouvre qui donne l'info
'''
return x - w/2, y + 4
def tooltip_callback(self,treeview, x, y, keyboard_mode, tooltip):
""" in order to collect miscellaneous elemnt to build data with row of treeview"""
"""3eme règle implementer ça pour afficher un tooltip customisé en fonction des data du tree view"""
x, y = treeview.convert_widget_to_bin_window_coords(x, y)
if not self.__enabled :
"""if you don't want tooltip display just return False !!!!"""
return False
try:
path, column, cell_x, cell_y = treeview.get_path_at_pos(x, y)
iter = model.get_iter(path)
#print 'tooltip=',self.get_tooltip(column, self.cust_col,path)
treeview.set_tooltip_window(self.__show(self.get_tooltip(column, self.cust_col,path),x,y))
# necessary to return True in order to display window tooltip
print "path is valid :-)"
return True
except:
# to prevent case when path it's not valid
print "perhaps path it's not valid ????"
# not possible to display something
return False
def add_view(self, view):
"""add a Gtk.TreeView to the tooltip
check if view is instance of Gtk.TreeView
and build connector and tooltip enable"""
assert isinstance(view, Gtk.TreeView), \
('This handler should only be connected to '
'instances of Gtk.TreeView')
# first condition in gtk3
# set True the property "has-tooltip"
view.set_property("has-tooltip", True)
# second condition in gtk3
view.connect('query-tooltip',self.tooltip_callback)
# hide tooltip when mouse out of widget
view.connect("leave-notify-event", self.__leave_handler)
def get_tooltip(self, view, column, path):
"""in order to secure customized implementation in your projet"""
'See the module doc string for a description of this method'
raise NotImplemented, 'Subclass must implement get_tooltip()'
if __name__ == '__main__':
class DemoTips_Gtk3(TreeViewTooltips_gtk3):
"""demo play how to """
def __init__(self, customer_column):
"""
init class
customer_column is an instance of Gtk.TreeViewColumn and
is being used in the Gtk.TreeView to show customer names."""
self.cust_col = customer_column
# call base class init
TreeViewTooltips_gtk3.__init__(self)
def get_tooltip(self, column,cust_col,path):
"""By checking both column and path we have a cell-based tooltip"""
model = view.get_model()
customer = model[path][2]
if column is cust_col:
"""here there is lot of information on row"""
return '<big>%s %s</big>\n<i>%s</i>' % (customer.fname,
customer.lname,
customer.notes)
else:
"""here basic data only !!!!"""
return ('<big><u>Generic Column Tooltip</u></big>\n'
'Unless otherwise noted, all\n phone number is %s ') % customer.phone
# Here's our customer
class Customer:
def __init__(self, fname, lname, phone, notes):
self.fname = fname
self.lname = lname
self.phone = phone
self.notes = notes
# create a bunch of customers
customers = []
for fname, lname, phone, notes in [
('Joe', 'Schmoe', '555-1212', 'Likes to Morris dance.'),
('Jane', 'Doe', '555-2323',
'Wonders what the hell\nMorris dancing is.'),
('Phred', 'Phantastic', '900-555-1212', 'Dreams of Betty.'),
('Betty', 'Boop', '555-3434', 'Dreams in b&w.'),
('Red Sox', 'Fan', '555-4545',
"Still livin' 2004!\nEspecially after 2006.")]:
customers.append(Customer(fname, lname, phone, notes))
# Build our model and view
model = Gtk.ListStore(str, str, object)
for c in customers:
model.append(['%s %s' % (c.fname, c.lname), c.phone, c])
view = Gtk.TreeView(model)
# two columns, name and phone
cell = Gtk.CellRendererText()
cell.set_property('xpad', 20)
namecol = Gtk.TreeViewColumn('Customer Name', cell, text=0)
namecol.set_min_width(200)
view.append_column(namecol)
cell = Gtk.CellRendererText()
phonecol = Gtk.TreeViewColumn('Phone', cell, text=1)
view.append_column(phonecol)
# finally, connect the tooltip, specifying the name column as the
# column we want the tooltip to popup over.
tips = DemoTips_Gtk3(namecol)
tips.add_view(view)
# We're going to demonstrate enable/disable. First we need a
# callback function to connect to the toggled signal.
def toggle(button):
if button.get_active():
tips.disable()
else:
tips.enable()
# create a checkbutton and connect our handler
check = Gtk.CheckButton('Check to disable view tooltips')
check.connect('toggled', toggle)
check.set_tooltip_markup('This is a standard Gtk tooltip.\n'
'Compare me to the tooltips above.')
# create a VBox to pack the view and checkbutton
vbox = Gtk.VBox()
vbox.pack_start(view,False,False,2)
vbox.pack_start(check,False,False,2)
vbox.show_all()
# pack the vbox into a simple dialog and run it
dialog = Gtk.Dialog('TreeViewTooltips Demo')
close = dialog.add_button(Gtk.STOCK_CLOSE,Gtk.ResponseType.NONE)
# add a tooltip for the close button
close.set_tooltip_markup('Click to end the demo.')
dialog.set_default_size(400,400)
dialog.vbox.pack_start(vbox,False,False,2)
dialog.run()
Who could give me elemnt in order to put tooltip with relative coordinate with TreeView ?
thank by advance
I'am sorry for my bad english
You are working with local coordinates, so you need to refer to the dialog position to get the root coordinates. Another issue with your script is that the main window is a dialog, therefore in the foreground, the tooltips appear below it (I have fixed that but then deleted the code (oops). It works, just change your dialog for a normal window). As a general note, it is good for all widget to know its parent to refer to it when the root coordinates are required.
Please see modified (but not cleaned up) code below:
#!/usr/bin/env python
# coding: utf-8
from gi.repository import Gtk
class TreeViewTooltips_gtk3:
"""tooltip atttach to Treeview in Gtk3
this window is moving to follow row of Treeview"""
def __init__(self):
self.win = Gtk.Window()
self.win.set_decorated(False)
self.win.set_default_size(-1, -1)
self.label = Gtk.Label()
self.win.add(self.label)
# by default, the tooltip is enabled
self.__enabled = True
def __show(self, tooltip, x, y):
"""in order to move the tooltip near row of Treeview"""
self.label.set_markup(tooltip)
w,h = self.win.get_preferred_width()
# move the window
self.win.move(*self.location(x,y,w,h))
# show it
self.win.show_all()
return self.win
def __leave_handler(self, view, event):
"""when the pointer leaves the view, hide the tooltip"""
self.win.hide()
def enable(self):
'Enable the tooltip'
self.__enabled = True
def disable(self):
'Disable the tooltip'
self.__enabled = False
def location(self, x, y, w, h):
'''Given the x,y coordinates of the pointer and the width and
height (w,h) demensions of the tooltip window, return the x, y
coordinates of the tooltip window.
The default location is to center the window on the pointer
and 4 pixels below it.
# en clair c'est un décalage de position de la fenetre qui s'ouvre qui donne l'info
'''
return x - w/2, y + 4
def tooltip_callback(self,treeview, x, y, keyboard_mode, tooltip):
""" in order to collect miscellaneous elemnt to build data with row of treeview"""
"""3eme règle implementer ça pour afficher un tooltip customisé en fonction des data du tree view"""
root_x, root_y = self.dialog.get_position() #get the root coordinates
x, y = treeview.convert_widget_to_bin_window_coords(x, y)
if not self.__enabled :
"""if you don't want tooltip display just return False !!!!"""
return False
try:
path, column, cell_x, cell_y = treeview.get_path_at_pos(x, y)
iter = model.get_iter(path)
#print 'tooltip=',self.get_tooltip(column, self.cust_col,path)
#add the root coordinates to local coordinates
treeview.set_tooltip_window(self.__show(self.get_tooltip(column, self.cust_col,path),root_x+x,root_y+y))
# necessary to return True in order to display window tooltip
print("path is valid :-)")
return True
except:
# to prevent case when path it's not valid
print("perhaps path it's not valid ????")
# not possible to display something
return False
def add_view(self, view):
"""add a Gtk.TreeView to the tooltip
check if view is instance of Gtk.TreeView
and build connector and tooltip enable"""
assert isinstance(view, Gtk.TreeView), \
('This handler should only be connected to '
'instances of Gtk.TreeView')
# first condition in gtk3
# set True the property "has-tooltip"
view.set_property("has-tooltip", True)
# second condition in gtk3
view.connect('query-tooltip',self.tooltip_callback)
# hide tooltip when mouse out of widget
view.connect("leave-notify-event", self.__leave_handler)
def get_tooltip(self, view, column, path):
"""in order to secure customized implementation in your projet"""
'See the module doc string for a description of this method'
raise NotImplemented('Subclass must implement get_tooltip()')
if __name__ == '__main__':
class DemoTips_Gtk3(TreeViewTooltips_gtk3):
"""demo play how to """
def __init__(self, customer_column):
"""
init class
customer_column is an instance of Gtk.TreeViewColumn and
is being used in the Gtk.TreeView to show customer names."""
self.cust_col = customer_column
# call base class init
TreeViewTooltips_gtk3.__init__(self)
def get_tooltip(self, column,cust_col,path):
"""By checking both column and path we have a cell-based tooltip"""
model = view.get_model()
customer = model[path][2]
if column is cust_col:
"""here there is lot of information on row"""
return '<big>%s %s</big>\n<i>%s</i>' % (customer.fname,
customer.lname,
customer.notes)
else:
"""here basic data only !!!!"""
return ('<big><u>Generic Column Tooltip</u></big>\n'
'Unless otherwise noted, all\n phone number is %s ') % customer.phone
# Here's our customer
class Customer:
def __init__(self, fname, lname, phone, notes):
self.fname = fname
self.lname = lname
self.phone = phone
self.notes = notes
# create a bunch of customers
customers = []
for fname, lname, phone, notes in [
('Joe', 'Schmoe', '555-1212', 'Likes to Morris dance.'),
('Jane', 'Doe', '555-2323',
'Wonders what the hell\nMorris dancing is.'),
('Phred', 'Phantastic', '900-555-1212', 'Dreams of Betty.'),
('Betty', 'Boop', '555-3434', 'Dreams in b&w.'),
('Red Sox', 'Fan', '555-4545',
"Still livin' 2004!\nEspecially after 2006.")]:
customers.append(Customer(fname, lname, phone, notes))
# Build our model and view
model = Gtk.ListStore(str, str, object)
for c in customers:
model.append(['%s %s' % (c.fname, c.lname), c.phone, c])
view = Gtk.TreeView(model)
# two columns, name and phone
cell = Gtk.CellRendererText()
cell.set_property('xpad', 20)
namecol = Gtk.TreeViewColumn('Customer Name', cell, text=0)
namecol.set_min_width(200)
view.append_column(namecol)
cell = Gtk.CellRendererText()
phonecol = Gtk.TreeViewColumn('Phone', cell, text=1)
view.append_column(phonecol)
# finally, connect the tooltip, specifying the name column as the
# column we want the tooltip to popup over.
tips = DemoTips_Gtk3(namecol)
tips.add_view(view)
# We're going to demonstrate enable/disable. First we need a
# callback function to connect to the toggled signal.
def toggle(button):
if button.get_active():
tips.disable()
else:
tips.enable()
# create a checkbutton and connect our handler
check = Gtk.CheckButton('Check to disable view tooltips')
check.connect('toggled', toggle)
check.set_tooltip_markup('This is a standard Gtk tooltip.\n'
'Compare me to the tooltips above.')
# create a VBox to pack the view and checkbutton
vbox = Gtk.VBox()
vbox.pack_start(view,False,False,2)
vbox.pack_start(check,False,False,2)
vbox.show_all()
# pack the vbox into a simple dialog and run it
dialog = Gtk.Dialog('TreeViewTooltips Demo')
tips.dialog = dialog #give tips the main window reference
close = dialog.add_button(Gtk.STOCK_CLOSE,Gtk.ResponseType.NONE)
# add a tooltip for the close button
close.set_tooltip_markup('Click to end the demo.')
dialog.set_default_size(400,400)
dialog.vbox.pack_start(vbox,False,False,2)
dialog.run()
So I have 2 views: the first one generates the html on request, the second view generates the chart to display for the first view.
HTML View
def activation_signupcount(request):
if 'datestart' not in request.GET:
return render_to_response('activation/activation_signupcount.html', {'datestart':''})
else:
datestart = request.GET['datestart']
dateend = request.GET['dateend']
return render_to_response('activation/activation_signupcount.html', {'datestart':datestart, 'dateend':dateend})#
CHART VIEW
def activation_signupcount_graph(request):
datestart = request.GET['datestart'] #this doesnt work
dateend = request.GET['dateend'] #this doesnt work
print datestart,dateend
# open sql connection
cursor = connection.cursor()
# execute query
cursor.execute("SELECT COUNT(1), JoinDate FROM users WHERE JoinDate BETWEEN '"+ datestart +"' AND '"+ dateend +"' GROUP BY JoinDate;")
# close connection
data = cursor.fetchall()
cursor.close()
connection.close()
fig = Figure()
ax = fig.add_subplot(111)
x = []
y = []
x = [k[1] for k in data]
y = [k[0] for k in data]
ax.plot_date(x, y, '-')
ax.xaxis.set_major_formatter(DateFormatter('%Y-%m-%d'))
fig.autofmt_xdate()
canvas = FigureCanvas(fig)
response = HttpResponse(content_type='image/png')
canvas.print_png(response)
return response
So on the page activation/activation_signupcount.html, I have 2 date fields, start and end, which submits a GET request. So my question is, how can I parse these 2 date variables to my function activation_signupcount_graph to get the start/end dates to generate the chart?
I hope that was clear!
You can access your chart view in your template using the url-templatetag with the appropiate parameters.
So it should look like:
<img src="{% url yourapp.chart_view start_date end_date %}" />
Or, as you are using get-parameters:
<img src="{% url yourapp.chart_view %}?datestart={{ datestart }}" />
have been doing this for years (works with pySVG generated SVG graphs as well btw) , however recently I encountered many problems with installing matplotlib in virtualenvs.
I resorted to adding the system wide matplotlib libraries (from the ubuntu repositories) to the virtualenvs instead of the usual pip install .... anthem