How to time response time in Django - django

I am creating a testing app in django. I want to be able to store the start time (when the page loads) and the end time (when the student hits submit) on every question. I realize that I could do something in the view function, however I am afraid that the latency between server and client would make any calculation meaningless. I would ideally like to calculate the start and end times on the client and send them back to the server using django's tag system.

I am not sure the server-client latency is really meaningful for your app, but you could shoot two calls, initiated by the client in Javascript, one when the document is ready and one when the user submits the answer. You would send the current timestamp in those calls.
You would then analyse those calls on the server's side with django views.

You can use hidden form fields. Just initialize start time on page load and end time before page submit using javascript.
in a django view it will be accesable under request.POST

Related

Using Django with the Facebook API for a polling app

I randomly pick two friends of the user and ask him/her to pick who is the better friend. Now all I have is the friend ID which I then have to use to create a poll and store in the database accordingly. Using the Facebook graph API, I have the ID. All I need to do now is to pass it to Django.
I'm new to this so how exactly would I do that? Pass a javascript variable to Django?
I see two options.
At client side using Javascript SDK,
Fetch the friends' profile details along with ID.
Convert them to JSON.
Do a POST request to a django url/view which stores the data in database.
In this way, you don't need to do any graph API queries further from server side. But this won't help you updating the data at realtime. Consider, if one of the friends changing his name in FB, now what is stored in your database becomes obsolete. So, you need to make sure that some thing from client side implemented to do real time update posts to server side.
At server side using any django facebook graph API apps,
Get the IDs from client side.
Use the fb graph app to fetch the details at server side.
Store them in database.
In this way, you could be able to schedule a callback for real time updates. I prefer the second approach as it's always better to burden the server rather than client. And I found this app simple and do what you need. https://pypi.python.org/pypi/django-facebook-api/0.1.10

How do I authenticate remotely in Django?

Basically what I'm doing is building a desktop application that needs to connect to a web server, perform some calculations, and then have the resulting values sent back to it. The calculations change over time, and also need to stay somewhat secure, which is why I'm not just coding them into the desktop application.
The issue is that only authenticated users should be allowed to access the server. So what I'm looking for is a way to log-in to Django from my desktop application (i.e. the desktop application will pop up a window asking for a username and password, which will then be sent to the Django site, used to authenticate the user, and if valid, will return the results of the computation. It also needs to work as a session (the user enters their password at the beginning and then doesn't need to log-in again until they close the desktop application, even if multiple computations are performed).
I think I need to use session keys for this, and perhaps the RemoteUserMiddleware described here but I really have no idea where to start as far as coding this. Any suggestions or pointers in the right direction would be hugely appreciated.
Thanks,
-Morag
P.S. If this is important, the desktop application is written in VB.NET.
Interesting. I've never done anything like this, but here is, what I assume, is the basic idea:
1) Get a good view of Django sessions; the basic idea is:
One logs in using the django auth framework login service
Django will create a session for you and handle all the difficult stuff
Django returns a HttpResponse with a sessionid cookie. You will need to send this back with any request following to identify yourself and 'operate within the session'.
One logs out using the django auth logout service and the session is destroyed by Django.
2) Now, the rest is relatively easy.
Setup django urls.py with the appropriate urls for login/logout + computation service
Execute a post request to the login service with the appropriate parameters set
Catch the response, extract the 'sessionid' cookie and save it somewhere
On each subsequent request, include the sessionid
This should get you started. Good luck!

Process a query without changing the page

We have a page which is dynamically generated after a few queries in the database. There are some links that when they are clicked by the user, update some information on the database but they change nothing on the webpage (or the display a discrete message).
How could we stay on the same page without re-rendering it?
Ideally, the corresponding view.py would process the queries and update the database but not the webpage.
You can send and receive your own XMLHttpRequest, but it is too much of works to do and IE will create a lot of problems.
Have you ever heard about jQuery? I strongly recommend you take a look at it and learn how to send and receive Ajax request using it.
You need to make an AJAX call back to the server with the user's actions, and process it on the server. You probably want a different view to process the AJAX request -- you could do it with the same view, but it would be somewhat silly to. The response from that view contains data (probably as JSON) or HTML, which you display on the page with javascript. Check out jquery -- it's great for the client side.
You could accomplish this with plain Javascript and AJAX. When the user clicks on a link, use XMLHttpRequest to call view.py to process the queries.
eg. For the link: <a href="#" onclick=submitdb(); >Click me!</a>
For a tutorial on implementing AJAX (XMLHttpRequest) with Javascript, have a look here:
http://www.quirksmode.org/js/xmlhttp.html

Track page time spent with cookie

I have an asp.net web app that has Session state stored in sql server. I need to keep track of the time spent by a user on each page. How can i do that using cookies?
Couldn't you use a cookie to store the time when the user navigated to the page and then when they navigate to another page calculate the time spent on the previous page, enter that into the database or something and then repeat the process?
If you can get away with tracking time for all users collectively rather than individual users, I would install Google Analytics.
http://www.google.com/analytics/
Tracking user time across a site isn't ideally done in the cookies, which are more for providng things back to the user.
That said, you'd need to store the intermediate data in the cookie if you're going to store the true 'time per page' per user rather than faking it at the server by counting the gap between page requests per session. You could do this by setting the load time at the page load, then comparing that to the current time in the onUnload event hander. Save that to the cookie and it should be available to the server in the request body of the next page it sends.

Web Dev - Where to store state of a shopping-cart-like object?

You're building a web application. You need to store the state for a shopping cart like object during a user's session.
Some notes:
This is not exactly a shopping cart, but more like an itinerary that the user is building... but we'll use the word cart for now b/c ppl relate to it.
You do not care about "abandoned" carts
Once a cart is completed we will persist it to some server-side data store for later retrieval.
Where do you store that stateful object? And how?
server (session, db, etc?)
client (cookie key-vals, cookie JSON object, hidden form-field, etc?)
other...
Update: It was suggested that I list the platform we're targeting - tho I'm not sure its totally necessary... but lets say the front-end is built w/ASP.NET MVC.
It's been my experience with the Commerce Starter Kit and MVC Storefront (and other sites I've built) that no matter what you think now, information about user interactions with your "products" is paramount to the business guys. There's so many metrics to capture - it's nuts.
I'll save you all the stuff I've been through - what's by far been the most successful for me is just creating an Order object with "NotCheckedOut" status and then adding items to it and the user adds items. This lets users have more than one cart and allows you to mine the tar out of the Orders table. It also is quite easy to transact the order - just change the status.
Persisting "as they go" also allows the user to come back and finish the cart off if they can't, for some reason. Forgiveness is massive with eCommerce.
Cookies suck, session sucks, Profile is attached to the notion of a user and it hits the DB so you might as well use the DB.
You might think you don't want to do this - but you need to trust me and know that you WILL indeed need to feed the stats wonks some data later. I promise you.
I have considered what you are suggesting but have not had a client project yet to try it. The closest actually is a shopping list that you can find here...
http://www.scottcommonsense.com/toolbox.aspx
Click on Grocery Checklist to open the window. It does use ASPX, but only to manage the JS references placed on the page. The rest is done via AJAX using web services.
Previously I built an ASP.NET 2.0 site for a commerce site which used anon/auth cookies automatically. Each provides you with a GUID value which you can use to identify a user which is then associated with data in your database. I wanted the auth cookies so a user could move to different computers; work, home, etc. I avoided using the Profile fields to hold onto a complex ShoppingBasket object which was popular during the time in all the ASP.NET 2.0 books. I did not want to deal with "magic" serialization issues as the data structure changed over time. I prefer to manage db schema changes with update/alter scripts synced with software changes.
With the anon/auth cookies identifying the user on the client you can use the ASP.NET AJAX client-side to call the authentication web services using the JS proxies that are provided for you as a part of ASP.NET. You need to implement the Membership API to at least authenticate the user. The rest of the provider implementation can throw a NotImplementedException safely. You can then use your own custom ASMX web services via AJAX (see ScriptReference attribute) and update the pages with server-side data. You can completely do away with ASPX pages and just use static HTML/CSS/JS if you like.
The one big caveat is memory leaks in JS. Staying on the same page a long time increases your potential issue with memory leaks. It is a risk you can minimize by testing for long sessions and using tools like Firebug and others to look for memory leaks. Use the JS Lint tool as well as it will help identify major problems as you go.
I'd be inclined to store it as a session object. This is because you're not concerned with abandoned carts, and can therefore remove the overhead of storing it in the database as it's not necessary (not to mention that you'd also need some kind of cleanup routine to remove abandoned carts from the database).
However, if you'd like users to be able to persist their carts, then the database option is better. This way, a user who is logged in will have their cart saved across sessions (so when they come back to the site and login, their cart will be restored).
You could also use a combination of the two. Users who come to the site use the session-based cart by default. When they log in, all items are moved from the session-based cart to a database-based cart, and any subsequent cart activity is applied directly to the database.
In the DB tied to whatever you're using for sessions (db/memcache sessions, signed cookies) or to an authenticated user.
Store it in the database.
Do you envision folks needing to be able to start on one machine (e.g. their work PC) but continue/finsih from a different machine (e.g. home PC)? If so, the answer is obvious.
If you don't care about abandoned carts and have things in place for someone messing with the data on the client side... I think a cookie would be good -- especially if it's just a cookie of JSON data.
I'd use an (encrypted) cookie on the client which holds the ID of the users basket. Unless it's a really busy site then abandoned baskets won't fill up the database by too much, and you can run a regular admin task to clear the abandoned orders down if you care that much. Also doing it this way the user will keep their order if they close their browser and go away, a basket in the session would be cleared at this point..
Finally this means that you don't have to worry about writing code to deal with de/serialising the data from a client-side cookie, while later worrying about actually putting that data into the database when it gets converted into an order (too many points of failure for my liking)..
Without knowing the platform I can't give a direct answer. However, since you don't care about abandoned carts, then I would differ from my colleagues here and suggest storing it on the client. Why store it in the database if you don't care if it's abandoned?
Then again, it does depend on the size of the object you're storing -- cookies have their limits after all.
Edit: Ahh, asp.net MVC? Why not use the profile system? You can enable an anonymous profile if you don't want to bother making them log in
I'd say store the state somewhere on the server and correlate it to the user's session. While a cookie could ostensibly be an equal place to store things, if you consider security and data size, keeping as much data on the server as possible becomes a good thing.
For example, in a public terminal setting, would it be OK for someone to look at the contents of the cookie and see the list? If so, cookie's fine; if not, you'll just want an ID that links the user to the data. Doing that would also allow you to ensure the user is authenticated to the site in order to get to that data rather than storing everything on the machine - they'd need some form of credentials as well as the session identifier.
From a size perspective, sure, you're not going to be too concerned about a 4K cookie or something for a browser/broadband user, but if one of your targets is to allow a mobile phone or BlackBerry (not on 3G) to connect and have a snappy experience (and not get billed for the data), minimizing the amount of data getting passed to the client will be key.
The server storage also gives you some flexibility mentioned in some of the other answers - the user can save their cart on one machine and resume working with it on another; you can tie the cart to some form of credentials (rather than a transient session) and persist the cart long after the user has cleared their cookies; you get a little more in the way of fault tolerance - if the user's browser crashes, the site still has the data safe and sound.
If fault tolerance is important, you'll need some sort of persistent store like a database. If not, in application memory is probably fine, but you'll lose data if the app restarts. If you're in a farm environment, the store has to be centrally accessible, so you're again looking at a database.
Whether you choose to key by transient session or by credentials is going to depend on whether the users can save their data and come back later to get it. Transient session will eventually get cleaned up as "abandoned," and maybe that's OK. Tying to a user profile will let the user keep their data and explicitly abandon it. Either way, I'd make use of some sort of backing store like a database for fault tolerance and central accessibility. (Or maybe I'm overengineering the solution?)
If you care about supporting users without Javascript enabled, then the server side sessions will let you use URL rewriting.
If a relatively short time-out (around 2 hours, depending on your server config) is OK for the cart, then I'd say the server-side session. It's faster and more efficient than accessing the DB.
If you need a longer persistence (say some users like to leave and come back the next day), then store it in a cookie that is tamper-evident (use encryption or hashes).