Statistics logging for Django - part 2

brad's picture

In part 1 I explained how to build middleware and an associated model to capture page accesses, and tie them to a user session. Now that we have all this useful info logged we need to do something with it, like, display it. Unfortunately Django doesn't have a facility for using GROUP BY with mysql, so you have two major choices (there are more but we can ignore them): implement a custom request in a custom Manager (see snippet and snippet, or tagged snippets), or exploit a mysql view and model it in Django. Now for me I prefer the latter because it means my custom sql becomes a mysql customisation and as far as Django is concerned it is dealing with a normal table (but don't tell Django that it is read only), and thus the model code works, so subsequent queries and manipulations can exploit the ORM easily. My subjective and non-scientific experience is that using views is a lot more efficient/quick than using custom queries in the manager (it probably has to do with whatever optimisations exist with views, and the fact that you only fetch items when Django decides you need to fetch a row). So, how the hell do we do it?

First I created a model that describes what information I want to deal with (something which maps neatly on to our other model):

class UserActivity(models.Model):
        session = models.OneToOneField(Session,
                                        db_index=True, 
                                        null=True,blank=True,
                                        primary_key=True)
        user = models.ForeignKey(User,null=True,blank=True)
        date = models.DateTimeField(
                       help_text="Date Request started processing",
                       auto_now_add=True,
                       db_index=True)
        processing_time = models.IntegerField(
                       help_text="Total time spent on this user")
        requests = models.IntegerField(
                       help_text="Total Requests in this session")
        stats = UserActivityManager()
        def __str__(self):
                return '%s: %s %s - %s - %s' % (self.user,self.session,self.date,self.processing_time,self.requests)
        class Admin:
                list_display= ('user','session','date','processing_time','requests')

The nice thing about this set up is when we aggregate our activity logs we can pull out random stuff like total processing time for requests for a user/session, along with number of requests/user/session (and thus average request time)

But that is just our model, we still need the magic. To implement the magic nicely I put some custom initial SQL into the sql directory of my application (in my case the housing application for this is called accounts, so I make a file called accounts/sql/useractivity.sql), you can read more about initial data here, Django fixtures).My SQL looks like this:

DROP TABLE accounts_useractivity;
CREATE OR REPLACE VIEW accounts_useractivity AS 
SELECT i.session_id,
       i.user_id,
       MAX(i.date) as date,
       sum(i.request_time) AS processing_time, 
       count(*) AS requests 
FROM accounts_activitylog i 
GROUP BY 1 
ORDER BY NULL;

So first I tell mysql to drop the table that django just created (accounts_useractivity), and create a view in it's place. The view is very simple, in that it just GROUP BY the session_id. The real hair puller for me was figuring out that I needed to use the MAX(i.date) (see more about aggregate functions) to get the most recent access to float to the top when it normalises the data (otherwise the GROUP BY normally ORDER BY the session_id, which helps no one), the ORDER BY NULL is an optimisation to tell GROUP BY not to ORDER BY. I am hoping that because date is an INDEX (from our logging model) it shouldn't cost too much to do a MAX. (I would like someone with Much MYSQL-fu to point out any further optimisations to this, or even alternative approaches to the whole thing).

So now we have an aggregating VIEW which Django maps using it's ORM, so that to figure out sessions which have been active in the last x minutes (where x is a datetime.timedelta object) we simply do a:

UserActivity.objects.get_query_set().filter(date__gte=datetime.now()-x)

I wrote a custom manager for getting recent sessions etc., but that is an exercise for the reader. What I did include in my model is something which returns a stepped "request_weight" i.e. session requests / largest session request x steps, which in my case defaults to 6. This means I can style my users like one would a "tag cloud", so very active sessions will grow bigger than less active sessions. I needed to implement a helper function in the custom manager to return the session with the most requests.

The final tip is to use a context processor to make the information available to all your templates, although you could do it with middleware (maybe middleware is the proper way to do it?).

Trackback URL for this post:

http://www.whijo.net/trackback/110

'request.session' is no longer a Session object, it's a SessionStore object that is different based on whether you use DB, file or cache sessions. I switched the 'session' part of the model to just be a charfield that is populated with the session id. I really only cared about which 'activity's were grouped as part of a session.
Essay AND Custom Research Paper AND Term Papers

Your article is great and there is no solution to this issue most of the companies are making money and wiping of their people. Its funny to real the article relation with real estate lolzzz. I have been looking for rent Apartment in Dubai since I move to Dubai . Properties for rent in dubai are expensive for me but one of my friend wants to Sell villa in Arabian ranches which might be a better option in this down market what do you think guys ?

Great post!

Djongo made the process of creating middleware very easy and now I can easily create addresses for datacall. Discount Sunglasses

You will surprise to find the high quality tiffany jewelry in much.Everyone will focus on the shinning of
tiffany co jewelry without awareness of
rovide 100% sterling silver Tiffany jewelry,you can buy discount Tiffany & Co jewelry here.Tiffany And Co Jewelry is the best jewellry.
discount tiffany jewelry, Tiffany Jewelry, Tiffany Jewellery, Tiffany Silver, Tiffany, Tiffanys, Tiffany's Jewelry.We Provide a wide range of fashionable
tiffany co jewelry, including
Links London
In 1950 Tiffany's had its biggest boost in popularity as Truman Capote's Breakfast at Tiffany's was published. Tiffany's was shot to worldwide fame in 1961 when the film adaptation staring Audrey Hepburn was released. This film and its star became icons, as did Tiffany's
Tiffany Bracelets
Tiffany Rings
cheap tiffany with.Discounted Tiffany & Co silver jewelries are provided in our Tiffany’s online outlet store
Links Of London

Thanks for sharing.

Some great info on here, why did i not find this site sooner! Many thanks and keep posting. how to get 6 pack abs | how to get six pack abs | how to get a 6 pack quick | how to get 6 pack abs fast

Thank you for sharing beautiful articles. I will recommend my friends to follow this website.

free music download sites

It is my great pleasure to visit your website and to enjoy your excellent post here. I like that very much. I can feel that you paid much attention for those articles, as all of them make sense and are very useful. Thank you for sharing with us static caravan insurance

A free sex video of sweet natural hairy Swamy Nithyananda’ having sex with a top tamil actress and other nude girls was broadcast on TV live and has shocked people across India. Naked girls were typed on video by anonumous author. Since a Swamy is supposed to be a spiritual person- this revelation has followers questioning hairy bush Nithyananda's faith. Originally this xxx video was posted on youtube but then moved to other sex tube portals.
ABB728019384 порно видео

Great post dude, your blog rocks!

auberge de jeunesse berlin

Thanks for sharing your views on the topic. It makes one think and look the other side of the story.

Thanks for posting this useful information. This was just what I was on looking for. I’ll come back to this blog for sure! I bookmarked this blog a while ago because of the useful content.

Nicely presented information in this post, I prefer to read this kind of stuff. The quality of content is fine and the conclusion is good. Thanks for the post.
UAE real estate
Dubai apartments for sale
rent apartment Dubai

Laughter and tears are both responses to frustration and exhaustion. I myself prefer to laugh, since there is less cleaning up to do afterward. 2012 calendar with holidays

Comparability and replica Longines watches distinction essay is Replica A.Lange Sohne without fake handbags doubt one of fake Jaeger Le Coultre Watches the replica Breitling watches commonest assignments in American replica Rado watches excessive colleges and Replica TAG Heuer Watches universities. designer handbags In the sort fake Balenciaga handbags of replica watches an essay the Replica Versace scholars have to compare two (in some essays replica Jaeger LeCoultre watches a number of) issues, problems, occasions or ideas- replica watches replica tag heuer and consider their resemblances and differences. This type of an essay advances and develops your crucial replica Piaget watches considering in addition to an essay your argumentation and understanding of the importance of the Replica IWC Watches occasions fake Marni handbags and issues that you simply compare.
There s an instance of Replica Loewe the headings of among the compare/contrast assignments.
Compare and fake TAG Heuer Watches contrast the weather situations for the growing of the cotton between Texas and California.
Examine fake watches the strategy to the Soviet Union of F.D. Roosevelt and H. Truman. Replica Tissot What are the cheap clothing similarities/the variations of their Replica Cartier coverage?
Compare and the essays contrast the flicks God Replica Thomas Wylde handbags Farther replica louis vuitton and Once fake A. Lange and Sohne Watches upon a time inAmerica. />
Generally, fake chanel chances replica watches are you ll be asked to check, replica Jaeger Le Coultre sometimes you may be replica IWC watches requested to contrast, and on a number of events Replica Omega each actions mentioned ought to be performed.
But, on the similar fake Jaeger Le Coultre Watches time comparison/contrast might replica IWC watches be a part of nike shoes some essay as w

Yes, I agree completely.
inground pool covers

I built some middleware/models for a django application to log visitor/user activity on the site. The intention is to be able to do better user tracking, and build more comprehensive statistics stored in the mysql db obviously I am also logging everything with apache. The current set up still needs some periodical scripts. Thanks.
Regards,
Child Behavior Problems

Be sure to use a postcard printer that is experienced with printing full-color photo quality images. Many postcard printers produce sub-standard images that will not do justice to your postcards or your message.

I really enjoyed taking a look at the photos. Must have taken a lot of time to make them look this elegant. kostenlose spiele

Searching good blog is not an easy task because number of blogs with exaggeration is available but the information on this blog is completely based on research. It will help you in getting information and gaining knowledge.
Regards,
auto insurance quotes

This is one of the highly attractive, informatics, well-written and highly crisp blog that has been explained in fabulous manner to help out reader and visitors. All information found here is genuine and realistic.
Regards,
sex toys

This is good site to spent time on. I just stumbled upon your informative blog and wanted to say that I have really enjoyed reading your very well written blog posts. I will be your frequent visitor, that’s for sure.
Regards,
michigan car insurance

I just have to say, I enjoy reading your post. Maybe you could let me know how I can bookmark this? I feel I should let you know I found your page through yahoo.banner design

The only limit to our realization of tomorrow will be our doubts of today. Let us move forward with strong and active faith.
Sheer curtain
Scaffold boards
Homemade pregnancy test

Very significant article for us ,I think the representation of this article is actually superb one. This is my first visit to your site. Keep blogging and thanks.
Regards,
texas car insurance
pennsylvania car insurance

It seems that you have placed a good amount of effort into your article and we require a lot more of these on the net these days. We genuinely enjoyed your point of view. I do not really have a bunch to to say in response.
Regards,
Income Protection

Nice information, many thanks to the author. It is incomprehensible to me now, but in general, the usefulness and significance is overwhelming. Thanks again and good luck!
Regards,
vizag web designing

I just came across your blog and reading your beautiful words. I thought I would leave my first comment but I don't know what to say except that I have enjoyed reading. Nice blog. I will keep visiting this blog very often.
Regards,
Box Trailer

The content is great and perfect for what you're trying to say. Awesome web site. Waiting for more posts on this article to read more. Keep up your excellency and efficiency in this same levels.

spiral binding

Thanks for the good post. I hope you can still see this comment. I want to know about lord and taylor coupons but I don't know exactly why. Thanks anyway

Loved to read your blog. I would like to suggest you that traffic show most people read blogs on Mondays. So it should encourage blogger to write new write ups over the weekend primarily.
detox tea recipe cheap liability insurance makeup for aging skin acne laser surgery jewish speed thread post heritage wsum

I will aslo try this code into my site. halloween contacts

Nice site and the article are posting are very nice. Hi, good luck man and thanks for sharing this post with us.
free boxing pay-per-view | international boxing news | coverage of boxing | deals on Boxing tickets

Extremely thankful for your service Tablet Android Honeycomb Terbaik Murah and as well, trust you are aware of a powerful job your are doing teaching many people via a web site.

I was looking at the comments on this page and to me they look very strange. It's like no one has even bothered to read the post, what's up with that? Maybe it's some sort of computer program that's posting them?

This feeling made him feel that all is getting out of control, pink ysl shoes the most appalling is that at first sight made Zhou Ya, yves saint laurent facotgy outlet he totally did not see any point in the oppressive, ysl shoes tribute outlet or sense of crisis. So, Mr Yip Kam had unilaterally to the risk of a stall trip Josh call a "card", yves saint laurent platform sandals he made the decision the first time in this life: to escape. Apart from that idiot man, ysl pumps quickly ran, not weeks buy ysl shoes , to breathe the air there is sub-statement. Hastily given a ticket, because the trip was too sudden, ysl pumps outlet he had to find his father's secretary for help. Dad got wind in his beard to stare back, ysl sandals before Mr Yip Kam immediate concern in the airport directly. Arrival airport,ysl sandals outlet when it began to rain outside. Coffee shop in the airport waiting for check in time, ysl shoes 2011 Mr Yip Kam years of looking at gray skies, rain that when the thin dense, ysl shoes direct emotionally delicate. Came back the same way the gray sky, but the mood was flying Dousou. And now I'm afraid facial expressions, ysl platform shoes mood, and this sky, like the cage floor were wiped not gray.

I truly enjoyed reading your weblog Mercedes-Benz Mobil Mewah Terbaik Indonesia and points that you expressed.

Post new comment

The content of this field is kept private and will not be shown publicly.
Captcha
This question is used to make sure you are a human visitor and to prevent spam submissions.
Syndicate content

Recent comments

About this website

Whijo.net is the online internets of Bradley Whittington, Amanda Joseph, and our son Finley James Whittington. "Whijo" is 29% Whittington, 33% Joseph, and 37% Internet. Quite Web 2.0 of us.