12.28.2013

Flash Messages in Ember (or how to use a proxy object to update Controllers outside of the normal route based approach)

In many different frameworks there is the concept of a flash; a short message to alert a user that something happened on the server backend. This is usually display in the form of a visual alert ala http://getbootstrap.com/components/#alerts

The way I wanted to accomplish this was to pass an additional object in the JSON result of any request. In the form

However, because I want this functionality available anywhere in the App, not just in a flash route, I had to get a bit creative. The route (no pun intended) that worked the best is to use a proxy object set on the App and then bound to the controllers content property.

In the model definition I used the didLoad event to have the model place it's self into the proxy

Finally I created a route subclass that will add the controller to every route

Thats it, I hope it helps you out.

11.18.2011

Decorating every view at the url.py level

I think of authentication and authorization usually in entire sections of a site/url tree. So it always annoyed me that there was no mechanism in django to decorate entire sections of a site at the urls.py level.

So, I came up with the following code that does just that.

5.18.2011

Ext4 MVC example reader.read is not a function

in your store
Ext.define('ID.store.Users', {
extend: 'Ext.data.Store',
model: 'User',

fully qualify the model

Ext.define('ID.store.Users', {
extend: 'Ext.data.Store',
model: 'ID.model.User',

[ERROR] Ext is not defined, please verify that the library is loaded properly on the application's page

I've started playing in earnest with Ext4 and I'm going to list out errors that I hit and fix as I hit them.

When running the sencha command in Ubuntu Linux (from the Deployment section. 3 of the getting started guide)

> sencha create jsb -a index.html -p app.jsb3
[ERROR] Ext is not defined, please verify that the library is loaded properly on the application's page
undefined:0 ReferenceError: Can't find variable: Ext

use fully qualified paths

> sencha create jsb -a /home/stephen/repo/ext-id/index_dev.html -p /home/stephen/repo/ext-id/app2.jsb3
file:///home/stephen/repo/ext-id/app/controller/Users.js?_dc=1305753075380:40 The panel was rendered
file:///home/stephen/repo/ext-id/app.js:13 Launch

cheers,
Stephen

4.21.2011

Vim for Django... a hell of a good start

http://agiliq.com/blog/2010/11/seven-reasons-why-you-should-switch-to-vim-for-dja/

12.30.2010

django-user-registery

I needed to build an auditing system in django and it got me to thinking... What is a graceful way of being to see and get an authenticated user in the context of a model or signal?

I didn't immediately see one so I wrote django-user-registry


I have since deprecated this for function that looks through the stack to find the request signature.
If it finds the request it uses the user from there.

---- Deprecated (Does't work on multithreaded (read all) servers :P ----

The concept is simple create a small middleware class that registers an authenticated user with with a registry class on request and unregisters the user on result.

Then in your model/signal code you can check for and access a user if one exists in the current context.

This code is little naive... it definitely would fall down in a multithreaded environment. Any ideas? The only other way that I can think of implementing it is to walk back up the stack looking for a request...

Example
(in settings.py)

MIDDLEWARE_CLASSES = (
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',

# 3rd party
# allow access to authenticated users in models and signals
'user_registry.middleware.UserRegistryMiddleware',
)

(in foo/signals.py)

from django.db.models.signals import post_save, post_delete, m2m_changed
from django.dispatch import receiver

from user_registry import UserRegistry

def alert_on_user():
print "alert_on_user"
if UserRegistry.has_user():
user = UserRegistry.get_user()
print user

@receiver(post_save)
def post_save_audit(sender,**kwargs):
alert_on_user()

@receiver(post_delete)
def post_delete_audit(sender,**kwargs):
alert_on_user()

@receiver(m2m_changed)
def m2m_changed_audit(sender,**kwargs):
alert_on_user()

12.28.2010

Update dj_jsurls is now django-jsurls

In order to follow the established plugin naming convention dj_urls is now django-jsurls. Also I got sick of typing dj_jsurls so the js root is now jsurls.

There is templatetags/jsurls - get_jsurls_static_prefix and urls.jsurls_urlpatterns to work around the fact that django.contrib.staticfiles.staticfiles_urlpatterns eats all /static/ paths

Lastly, there is a manage.py generate_static_jsurls to build the static production version of the jsurls.js file.

12.17.2010

DRY out your urls (in JS)

(update: changed url repository)

When it come to xhr heavy JS code, I hate hard coding in urls. This isn't good practice on the Django side and it is not good practice on the JS side. While I was working in ROR for a spell, I found a plugin on github toretore/javascript_routes that built off of ROR routes system. Upon moving back to Django I wanted the same functionality, so I built a pluggable app at sjzabel/django-jsurls.

Right now it is view designed for development use but I'll have management tool to statically generate it for productions here soon.

12.03.2010

Great Gitosis Article

http://scie.nti.st/2007/11/14/hosting-git-repositories-the-easy-and-secure-way

Django, login required mixin, mixed into all class based generic views

Django, aaaaaaaah...

After a two year stint using Ruby on Rails, I am back in the loving arms of Django.

I've been quite pleased to see that it is growing up but still keeping all the things that I loved about it (the intuitiveness, the flexibility, the ease of hacking, the spectacular documentation, etc...)

So a link Eric Olscher : Large Problems (mostly solved)

In this series of blog posts Eric talks about a number of issues that we had to hand roll solutions to when I was beginning with Django

9.09.2009

Pomodoro + Adium + Applescript = Fun!

Two useful little scripts for changing your Adium status at the beginning and end of a Pomodoro session. (I got sick of doing this by hand after my first session :P)

- @Start

tell application "Adium"
go away with message "back at " &(time string of ((current date) + 25 * minutes))
end tell

- @Finish

tell application "Adium"
go available
end tell

12.31.2008

Look Ma... my first ubiquity script

I have been tracking my calories
A friend has a nice tracking site
A well known site has a lot of nutritional data
I do not do data entry
+I have enough morals not to spider the site :P
--------------------------------------------------
I now know how to write ubiquity scripts :)


CmdUtils.CreateCommand({
name: "king-to-trainer",
author: {name: "Stephen Zabel", homepage: "http://pinkfuzzymud.com/"},
license: "bsd",
calorie_trainer_authenticity_token: "get your own :)",
calorie_trainer_post_uri: "http://caloriescount.stochasticbytes.com/ingredients",
preview: function(previewBlock) {
previewHTML = "posts new ingredient info from the current calorie k*** page
this is just a convience function... you will still likely have to edit the ingredient"
previewBlock.innerHTML = previewHTML;
},

execute: function(statusText) {
var doc = Application.activeWindow.activeTab.document;
var uri = Utils.url(doc.documentURI);

if(this.isCalorieK***(uri)){
this.postToCalorieTrainer(this.parseCurrentPage(doc));
}
else displayMessage('boo! not caloriek***');
},
isCalorieK***: function(uri){
return uri.host.indexOf("caloriek***") != -1
},
parseCurrentPage: function(doc){
var params = {"authenticity_token": this.calorie_trainer_authenticity_token} ;

jQuery(doc.body)
.find(".site_content h1:not(:contains(Guide))")
.filter(':first')
.each(function(i){
params["ingredient[name]"] = jQuery(this)
.find('span')
.remove()
.end().text();
});

params["ingredient[mass_quantity]"] = jQuery('#amount',doc.body).val();
//for poc I'm just going to hard code
params["ingredient[mass_unit]"] = '2';

params["ingredient[calories]"] = jQuery('#calories',doc.body).text();
params["ingredient[total_fat]"] = jQuery('#total_fat',doc.body).text();
params["ingredient[saturated_fat]"] = jQuery('#saturated_fatty_acids',doc.body).text();
params["ingredient[cholesterol]"] = jQuery('#cholesterol',doc.body).text();
params["ingredient[sodium]"] = jQuery('#sodium',doc.body).text();
params["ingredient[carbohydrates]"] = jQuery('#total_carbohydrate',doc.body).text();
params["ingredient[fiber]"] = jQuery('#fiber',doc.body).text();
params["ingredient[sugar]"] = jQuery('#sugars',doc.body).text();
params["ingredient[protein]"] = jQuery('#protein',doc.body).text();

params["ingredient[brand]"] = 'whole paychex';
params["ingredient[description]"] = '';

return params
},
postToCalorieTrainer: function(params){
jQuery.post(this.calorie_trainer_post_uri,params,function(){alert('finished');});
}
});