sqllite read/write queue concern with django - django

I'm building a website where college students can order delivery food. One special attribute about our site is that customers have to choose a preset delivery time. For example we have a drop at 7pm, 10pm, and at midnight.
All the information about the food is static (ie price, description, name), except the quantity remaining for that specific drop time.
Obviously i didn't want to hardcode the HTML for all the food items on my menu page, so i wrote a forloop in the html template. So i need to store the quantity remaining for the specific time somewhere in my model. the only problem is that I'm scared that if i use the same variable to transport the quantity remaining number to my template, i'll give out wrong information if alot of people are accessing the menu page at the same time.
For example, lets say the 7pm drop has 10 burritos remaining. And the 10pm drop has 40 burritos. Is there a chance that if someone has faster internet than the other customer, the wrong quantity remaining will display?
how would you guys go around to solve this problem?
i basically need a way to tell my template the quantity remaining for that specific time. and using the solution i have now, doesn't make me feel at ease. Esp if many people are going to be accessing the site at the same time.
view.py
orders = OrderItem.objects.filter(date__range=[now - timedelta(hours=20), now]).filter(time=hour)
steak_and_egg = 0
queso = 0
for food in orders:
if food.product.name == "Steak and Egg Burrito":
steak_and_egg = steak_and_egg + food.quantity
elif food.product.name == "Queso Burrito":
queso = queso + food.quantity
#if burritos are sold out, then tell template not to display "buy" link
quantity_steak_and_egg = max_cotixan_steak_and_egg - steak_and_egg
quantity_queso = max_cotixan_queso - queso
#psuedocode
steakandegg.quantity_remaining = quantity_steak_and_egg
queso.quantity_remaining = quantity_queso
HTML:
{% for item in food %}
<div id="food_set">
<img src="{{item.photo_menu.url}}" alt="" id="thumbnail photo" />
<div style='overflow:hidden'>
<p id="food_name">{{item.name}}</p>
<p id="price">${{item.price}}</p>
</div>
<p id="food_restaurant">By {{item.restaurant}}</p>
<div id="food_footer">
<img src="{{MEDIA_URL}}/images/order_dots.png" alt="" id="order_dots" />
<a id ="order_button" href="{{item.slug}}"></a>
<p id="quantity_remaining">{{item.quantity_remaining}} left</p>
</div><!-- end food_footer-->
</div><!-- end food_set-->

I don't understand what "faster Internet" or "using the same variable" have to do with anything here (or, indeed, what it has to do with sqlite particularly).
This question is about a fundamental property of web apps: that they are request/response based. That is, the client makes a request, and the server replies with a response, which represents the status of the data at that time. There's simply no getting around that: you can make it more dynamic, by using Ajax to update the page after the initial load, which is what StackOverflow does to show update messages while you're on the page. But even then, there's still a delay.
(I should note that there are ways of doing real-time updates, but they're complicated, and almost certainly overkill for a college food-ordering website.)
Now the issue is, why does this matter? It shouldn't. The user sees a page saying there is 1 burrito left - perhaps with a red warning saying "order quickly! almost gone!" - and they press the order button. On submission of that order, your code presumably checks for the actual status at that time. And, guess what, in the meantime you've processed another order and the burrito has already gone. So what? You simply show a message to the user, "sorry, it's gone, try something else". Anyone with any experience ordering things on the web - say, concert tickets - will understand what's happened.

Related

Need user to pick from a list to connect two users in YESOD

I need general guidance on how to structure a YESOD app. I would like to keep the app as "RESTful" in design as possible.
The user searches all the other users to find one to connect with. I show the possible connections using Hamlet:
$forall (pid, person, mEmail, mPhone) <- displayPeopleRecs
<p>
<a href=#{CreateFundR pid}>#{personNickName person}
$maybe email <- mEmail
#{emailEmail email}
$maybe phone <- mPhone
#{phoneNumber phone}
However, now when a user clicks on a link they go to the /createfund/ page as a GET request which is not what I want, I want to use POST or something else.
Can anyone explain what the correct solution is here? Do I make a form for each person what the search produces and have a submit button for each possible person? That seems silly. Is it better to use Julius and change the onclick handler for the link to submit a POST instead of a GET to /createfund ?
Here is the relevant line from my config/routes:
/createfund/#PersonId CreateFundR POST
By the way, I can see how to make this work by using a form and a submit button:
$forall (pid, person, mEmail, mPhone) <- displayPeopleRecs
<p>
<form method="post" action="#{CreateFundR pid}">
<table>
<tr>
<td>
#{personNickName person}
$maybe email <- mEmail
<br>
#{emailEmail email}
$maybe phone <- mPhone
<br>
#{phoneNumber phone}
<td>
<input type="submit" value="Create Fund">
That will work for my needs, but I'd really like to allow the user to just click the link. Is this poor design? Or just a matter of taste?
If you use an AForm / MForm, the form will be automatically generated for you (using Tables or Divs). That should simplify things for you.
If you want to manually style it, you can do something like this when using a form: How to make button look like a link?. Most people end up creating styled buttons for such actions anyways (think of your standard CRUD app with Edit, Delete buttons, etc.).
If you go down the path of trapping link clicks and do ajax Post, it will not degrade nicely if javascript is disabled so something you need to watch out for.
HTH

How to display a post registration welcome message when using both django-registration and django-socialauth?

This is a pretty trivial question but I must be missing something because I can't come up with a solution I'm happy with.
I'm using two libraries to handle registration, django-registration for the email based registration and django-socialauth for the social based registration, and want to display a welcome message when the user registers for the first time.
My current approach is to have a context processor that checks if the user has registered within the past 2 minutes and if so, updates the request object. This seems inefficient since I'm checking every time when it's only used once.
I tried implementing it using signals but the issue I ran into was that I needed some way to hook into the request but only django-registration passes the request along.
An option I'm contemplating is using the signals to update a record in the database but that seems like overkill for something this simple. Am I missing something obvious?
context_processors.py:
def just_registered(request):
just_registered = False
if request.user.is_authenticated() and request.user.email:
if request.user.date_joined < datetime.today() + timedelta(minutes=2):
if 'just_registered' not in request.session:
just_registered = True
request.session['just_registered'] = just_registered
return { 'just_registered' : just_registered }
you can use django messages and implement it in your template
{% if messages %}
{% for message in messages %}
{{message}}
{% endfor %}
{% endif %}
.
def just_registered(request):
if request.user.is_authenticated():
if request.user.date_joined < datetime.today() + timedelta(minutes=2):
messages.info(request, "Welcome")
return ''
user is authenticated is already understood, you don't have to put user email because when you register, the email is required
Just to be clear, you want to display a welcome message when the user successfully logs in for the first time (it says register for the first time in your question)? Do they follow an activation link from an email? You could have that emailed link go to a new user version of your landing page.
Otherwise, if you want to use the same page for normal users and people logging in the for the first time, I don't see how you can avoid checking if this is the user's first time logging in. To do that, it seems like using a boolean attrib on the user (or fk'ed to them) that keeps track of whether they have logged in before would be the way to go, instead of looking at how long ago they activated the account (what if they activated 2 days ago but didn't log in?)
Following from your comment on princesses answer your best bet would be to save some kind of data when the user logs in for the first time.
I would suggest write a simple middleware which detects first login and saves that in a persistent form
Have a look at this:
http://blog.elcodo.pl/post/926902087/django-detect-users-first-login
You can also checkout the middleware in django tracking
https://github.com/codekoala/django-tracking/blob/master/tracking/middleware.py
It is slightly inefficient , however I don't see any other way given the statelessness of HTTP

Django: use POST or links, which is better practice?

A noobish question to be sure.
<a href="{% url 'stuff.views.SomeView' %}/somethingnew">
<button>See something new on this page</button>
</a>
<form action="" method="post">{% csrf_token %}
<button name="somethingnew" type="submit" value=True>See something new on this page</button>
</form>
With either choice, I update some boolean variable, perform the appropriate calculations, call the page view and render a page with something new on this page. Part of the reason I use either method is to save the state of a collection of boolean variables. What is the best way 1) change a boolean variable 2) save its state 3) perform the necessary updates when the button is clicked and finally 4) render page after the underlying data has been updated?
Right now, I am using forms rather than links so that I don't need to code a url for each boolean variable. Which method is better? Will one method improve the time it takes to reload the page (assuming many boolean variables)?
1) Following the REST mindset, a POST request is in order to transmit the user input, since you are altering database objects.
2) I'd save it in the Session object if the input is not needed forever (session duration). Otherwise in the database as you are doing now.
3/4) I'd gather all the necessary info in a form. When the user commits the form in a POST request, I'd compute the data and respond with the rendered page containing the computed result. If the input variables are gathered step by step with intermittent computation, I'd just update the input form accordingly (display different choices in a combo box or something like that). Of course the transmitting could be done in an AJAXy way, too.

Like Button (SEND) Shows the og:metadata info and not the href content (sometimes)

The site is: http://grantdeb.com
I want to be able to dynamically add meta properties to the Recommend(s) and Send(s). Right now, it's using the meta og: properties and that is totally NOT what I want.
The LIKE count is also showing incorrectly for each like even though I've pushed the data-href to it like:
<div class="fb-like" data-href="http://grantdeb.com/wedding-photographers-hampton-roads/[dynamic id]/Wedding-Photography" data-send="false" data-width="450" data-show-faces="false" data-action="recommend" ></div>
BUT - for some reason, once in a while the LIKE / SEND does NOT use the meta properties and correctly shows the correct count AND the correct picture / title I want for the Send.
If you go to our site at http://grantdeb.com look specifically at the "Jasmine Plantation Wedding Photography" (like the 5th post down) you'll see the number of Recommendations is correct, and if you hit the "Send" button at right bottom, it actually uses the correct title and picture we want.
That post is the way we want the Recommend / Send to display.
Why is that happening to some of them and to others it shows our og: metadata?
I can’t exactly see on your site what the problem is (or match your problem description with your site’s content) – but looking at the URL for the post you mentioned in Facebook debug tool, it seems that you have
<meta property="og:url" content="http://grantdeb.com" />
set for all of your detail pages – so that is what Facebook considers the “real” URL for all of your actual posts marked with this tag.
(Can’t tell if this is what you explicitly wanted or not, because your problem description is kinda fuzzy to me.)

Prevent XSS in HTML forms from third party site

The basics:
I have a contact form that uses
php to validate the
forms. (in addition to client side) This could be done in any server side language though.
The server side only allows
A-z 0-9 for certain fields (it is
acceptable to validate this field to
English only with that extremely limited range)
If the form contains errors, I repopulate the fields so the user doesn't have to retype before submitting again
I am willing to not let other sites post to my form, even if legitimate use could be found there.
I can easily make a form on a different web site that posts a dirty word to a field. Certain dirty words are perfectly legit according to the validation rules, but my employeer obviously wouldn't like that to happen.
I am under the impression that dedicated hackers can affect cookies, php sessions and of course hidden fields are easy to spoof along with referrers and such. How can I block third party sites from posting to my page?
Please feel free to help me Google for this too. My search terms are weak and bringing up methods I know will fail.
What if somebody submits "d03boy eats cats" via a form on their site and gets people to click a link that submits it to my form? (Admit it is possible, and my company cannot accept any risk) Then when a user clicks the link they see inside the "name" field "d03boy eats cats" and gets super offended and contacts PETA about our site's content. We just cannot explain to the user what happened. True, nothing happened, but upsetting a single users isn't acceptable to my employer.
Our current solution is to not report any user input, which in my opinion is a big usability issue.
This sounds like you need a moderation system in place for user generated content, not a technical solution. Obviously you can check the referrer field, content scrub and attempt to filter the profane, but enumerating badness never works. (It can be an acceptable "first pass", but humans are infinitely resourceful in avoiding such filters).
Put the user submitted content into a queue and have moderators review and approve content. To lighten the load, you can set trusted users to "pre approved", but you have said your client can't accept any risk.
Frankly, I find that impossible: even with moderators there is the risk that a moderator will subvert your system. If that is actually true (that they have zero risk tolerance) then I suggest they not accept any user input, don't trust moderators and in fact eliminate the site itself (because an insider could go rogue and put something improper up). Clearly every act has risk; you need to find out how much they can accept, such as a moderator based approval queue.
I'm not sure I entirely understand your question but I'll do my best to give you a basic answer.
Cross Site Scripting (XSS) happens generally when someone else puts in HTML into your forms. Your website allows this to happen because it isn't escaping the HTML properly. If you use PHP you probably want to make use of the htmlentities($str, ENT_QUOTES) function.
htmlentities($str, ENT_QUOTES)
PHP htmlentities
My attempt
...
<?
$form_token = "";
$token = "";
$encoded_token = "";
$salt = "ThiséèÞ....$ÖyiìeéèÞ"; //it is 70 characters long
...
...
$blnGoodToken = false;
...
...
//Check for the encoded token
session_start();
$encoded_token = GetSuper('POST', 'TOKEN');
if (isset($_SESSION['TOKEN'])) {
if (sha1($_SESSION['TOKEN'] + $salt) === $encoded_token) {
$blnGoodToken = true;
//echo "Good Token";
}
else {
//echo "Bad Token";
$blnGoodToken = false;
unset($_SESSION);
session_unset();
session_destroy();
session_start();
}
}
else {
$blnDoit = false;
echo "No Token, possible no session";
}
$token = uniqid(rand(), TRUE);
$_SESSION['TOKEN'] = $token;
$form_token = sha1($token + $salt);
...
...
?>
...
...
<form action="request.php?doit=y" method="post">
<input type="text" name="TOKEN" id="TOKEN" value="<?=$form_token?>" />
<!--
form stuff
-->
<input type="reset" value="Clear" />
<input type="submit" value="Submit" />
</form>
Since I don't use sessions anywhere else on the site, I don't think we are exposed much to session hijacking. The token changes each load, and to get the token to match the session you would have to know
I am using SHA. An easy guess to
make on my php code
I keep it in the session. I suppose
the session is gettable
My salt. I think this is a good
secret. If they know my salt they already
owned my server