Beginning Django E Commerce
398 pág.

Beginning Django E Commerce

DisciplinaProgramação I24.723 materiais281.549 seguidores
Pré-visualização50 páginas
Cart IDs across 
multiple records, for a couple of reasons. First, the Cart IDs are going to be a big blob of character data from 
the session cookie that is not going to change. The only thing that can happen is the customer clears their 
cookies, or switches computers or browsers, in which case we\u2019ll just assign them a new Cart ID. 
But second, and much more importantly, when you pull your model information in your views to 
show the user, two separate tables with the cart information would do one of two things. It would either 
require you to do a query for the Cart ID, and then do a second query for the associated items in the cart, 
in which case you\u2019ve performed an extra query, or you would have to perform a join on the two tables in 
order to get the information you need in one shot. Queries are expensive, and joins on tables to query 
data from more than one table are also quite expensive.1 And after all, in our case, there isn\u2019t any 
additional information that a second table would contain, other than the Cart ID. 
The last method, augment_quantity(), will be used by our site just in case someone adds an item to 
their cart and, by some weird coincidence, finds their way back to that product page and adds the exact 
same item to their cart a second time. Instead of adding it again, we\u2019ll just adjust the quantity. 
1 With the proper use of indexes in your database tables, however, joins might be less expensive than tables with 
several columns. See Chapter 13 for more about indexes.
Django Sessions Overview 
So how long do Django cookies last? Once you identify a user and they start adding items to their cart, 
how long does that cart persist in their browser? The best answer I can give you to these questions is to 
point you directly to where the answer lies: in the Django global configuration file. We saw this file in the 
last chapter. It\u2019s called, and it resides in your Django installation folder on your 
development machine. 
Open this file and navigate down to the section labeled SESSIONS surrounded by lots of pound (#) 
signs. You should see about 10 configuration settings related to cookies, which have self-describing 
names and comments that should help you understand the purpose of each one. In case you don\u2019t feel 
like opening the file yourself, here are the most important ones: 
# Cookie name. This can be whatever you want. 
SESSION_COOKIE_NAME = 'sessionid' 
# The module to store sessions data. 
SESSION_ENGINE = 'django.contrib.sessions.backends.db' 
# Age of cookie, in seconds (default: 2 weeks). 
SESSION_COOKIE_AGE = 60 * 60 * 24 * 7 * 2 
# Whether a user's session cookie expires when the Web browser is closed 
# Whether the session cookie should be secure (https:// only). 
As you can see, cookies last two weeks before they expire in the user\u2019s browser. At these two weeks 
of idle activity, if the user returns to your site, their shopping cart will appear to be empty, even if they 
had previously filled it up with 10 different kinds of jaw harps and banjo strings. 
That last value is the most important one to examine, because it makes a very important point: 
cookies are not secure. Cookies are only as secure as the transmission protocol they\u2019re sent over, and 
plain ol\u2019 HTTP is not secure. We discussed not storing large amounts of complex information in cookies, 
but you certainly don\u2019t want to start storing any sensitive information in them. As a way-too-obvious 
example, don\u2019t store customer credit card information in cookies. 
\u25a0 Note Setting your SESSION_COOKIE_SECURE value to True does not in any way secure your cookies. That just 
means they won\u2019t work in your web project unless the user is browsing your site over SSL. (I\u2019ll discuss SSL in 
more detail in Chapter 5.) 
Lastly, notice that, while the database is used to store session information by default, you can 
change this configuration to use one of the other options. Your project can use a file in your project\u2019s 
directory to track user session information. Because performance is superior with the database 
approach, we\u2019re not going to use the file approach in this book, but you do have the option, in case your 
project isn\u2019t using a database. 
If you feel the need to change any of these default settings, my advice to you is not to edit this global 
settings configuration file. As a matter of fact, as far as changes go, leave the Django source code alone. 
Like any computer code, a change in one area of the source code might inadvertently break things in 
other places. This shouldn\u2019t be a problem for you, since you can override any of the settings in the global 
settings file by adding the same configuration setting to your project\u2019s file.
For example, if you want to set cookies so that they last 90 days instead of 2 weeks, you can add this 
line of code to your file: 
SESSION_COOKIE_AGE = 60 * 60 * 24 * 90 
Or, if you want to make it unreadable to anyone that doesn\u2019t have a calculator at hand: 
SESSION_COOKIE_AGE = 7776000 # the number of seconds in 90 days 
The two are functionally equivalent. However long you would like your carts to last is entirely up to 
you and your own needs. I\u2019m going to set my cookie to last for 90 days, to give my users enough time to 
think about their buying decisions. If you want to test this setting, set it to some ridiculously low, like 
three seconds, add an item to your cart, and watch how quickly it disappears after you start refreshing 
the cart page. 
Enabling and Using Sessions 
The good news is that you already have sessions enabled. Back in Chapter 3, when you uncommented 
out this line of code in your file under the INSTALLED_APPS section: 
the tables that your database needed to track sessions were created as soon as you ran the syncdb 
command in your shell. In addition, your project came equipped with another batch of code in the 
The request.session object is an instance of a special SessionStore class, which is similar in 
concept to a Python dictionary object that you can use in your Django code to store and retrieve session 
information with each request. So, when a user adds an item to their cart on the product page, and you 
want to set the value of their Cart ID, you can use the following code: 
request.session['cart_id'] = 'cart_id_value_here' 
Later, when you want to retrieve it, you can just as easily get at it with this: 
The syntax is simple, but things get a little sticky when you try to access a user\u2019s Cart ID before 
you\u2019ve set it, and you can\u2019t set the value each time it\u2019s accessed, because you\u2019d just be overwriting the 
value that was already there. To solve this problem, we\u2019re going to check for the existence of the Cart ID, 
set it if it doesn\u2019t exist, and then return that value. 
Here is the function for the Cart ID for our cart module (we haven\u2019t created the cart module yet): 
def _cart_id(request): 
 if 'cart_id' in request.session: 
 request.session['cart_id'] = _generate_cart_id() 
 return request.session['cart_id'] 
As you can see, we use the Python dictionary\u2019s get() method to check for the Cart ID, and if the key 
cart_id is not found, an empty string is returned and our _generate_cart_id() method is called to create 
one for us. 
So what is our Cart ID going to look like? In our project, we\u2019re going to generate a random string of 
fifty letters, numbers, and other non-alphanumeric characters. Here is the implementation of our 
function to generate random