Say I wanted to print the response time on my pages like Google do.
How would I go about doing this?
Call start = time.time() as the very first operation in your handling scripts, and, when you're just about done with everything, as the very last thing you output use (a properly formatted version of) time.time() - start.
If you're using templates for your output (e.g., the Django templates that come with app engine -- 0.96 by default, though you can explicitly ask for newer and better ones;-), or jinja2, mako, ...), it's important to be able to use in those templates a tag or filter to request and format such an expression. (You don't want to compute it at the time you call the template's render method, and pass it as part of that method's context, or else you'll fail to account for all the template rendering time in your estimate of "response time"!-). You may have to code and inject such a tag or filter into the "templating language" if your chosen templating language and version doesn't already supply one but is at least minimally extensible;-).
`
Related
I'm working on a web application on Google App Engine with Python as my backend language. Now, I need to calculate a particular value based on the user input and display it on my web page. Here's the concerned code sample:
<h4>Total Amount:{{disp.actual_price}}*{{quantity}}</h4>
Now I'm using Jinja 2 template for rendering my HTML pages. In the above example, 'disp.actual_price' is the value of the 'actual_price' attribute in my 'disp' entity of my Google App Engine datastore, while 'quantity' is a value passed on by the user. So basically, I'm unable to figure out a way to multiply these two variable values and displaying them on the webpage. If the actual_price is 300, and the value of 'quantity' is 2, then here's what gets displayed with my above code:
Total Amount:300*2
You should write it this way:
<h4>Total Amount:{{disp.actual_price * quantity}}</h4>
The correct answer to the question is don't do it. I'll explain why in a moment.
The correct syntax to do what you are attempting to do is:
<h4>Total Amount:{{disp.actual_price*quantity}}</h4>
From the documentation
There are two kinds of delimiters. {% ... %} and {{ ... }}. The first one is used to execute statements such as for-loops or assign values, the latter prints the result of the expression to the template.
In this particular case, either delimter would work fine. But you'd really want to use the second one. Your code didn't work because anything outside of the delimiter is treated as plain HTML. It has to be inside the delimiter to be treated as an expression.
But why is this wrong? You are mixing business logic with interface. Doing this means that the day you want to change the design of the page, or the workflow, you'll be juggling around business variables in the page. If the calculation got a little more complex, then your template does too. But worst of all, if you move to a different templating engine, then your entire application is screwed because all your business logic is stuffed inside the template.
To do this correctly you need to have a file that just does the calculations by itself. In your file where you have the template being called, you should import this logic file and call on the methods inside it. Thus, the method inside the file responding to the HTTP requests, might look like this:
#initialize template variable
totalAmount = importedLogicModule.calculateTotalAmount(disp.actual_price, quantity)
return template.render(totalAmount = totalAmount)
and the template would now be
<h4>Total Amount:{{totalAmount}}</h4>
In php files, this task may be a simple include of another file but I wondered if it was similar practice in Django? like described here: https://docs.djangoproject.com/en/dev/ref/templates/builtins/?from=olddocs#include
Short answer: No, Python doesn't perform that way.
Here's a long one:
A little bit about difference between PHP and Python web development
First of all, include and require are parts of PHP language itself. It means that before processing source code PHP interpreter includes source code from files given as arguments to those functions and then makes interpreting. That's the inheritance of the main purpose of PHP design (HTML, or, generally, text preprocessing).
Web development in Python is a bit different. Language itself was designed as general purpose programming language, so it doesn't assume text-processing by default. Code is just executed. That's why web development is usually done using frameworks (or wsgi modules if you prefer doing everything from scratch.
All that above means that all text manipulations (all output you generate, you generally do manually by creating result text string (or strings list when used with buffering) and giving the output result yourself.
Template languages
That's kinda messy point from which template languages were born, becoming essential part of every (or almost every) web application written in Python (you can assume something simalar to Smarty in PHP world). There are a lot of them: jinja, jinja2, mako, chameleon ... and many others. All of them are different but serve the same purpose (easyfying text generation via providing templates with placeholders for data of basic representation logic).
And here comes the main feature of Python web frameworks: application logic and representation are strictly splitted.
Here we came to the substance of your question:
As all of those template libraries providing text templating facilities are different, there's no common way to make PHP-like includes that we can say they are general for Python. Each of those tools provide different ways and philosophy of handling, in particular, includes, mainly divided into two mainstream ways:
macros- and slots-based (Chameleon)
template inheritance-based (Jinja2, Django template language)
All you need is to take one that best fits your needs (whether you like/unlike their syntax, some of them are faster, some are more readable, and so on..) and work with it combining with other tools that provide logic for your application.
Getting closer: About Django
It's common to use include template tag when you want to include some re-used part of application (e.g. pagination widget), for which you've adapted your view context.
But when you have common header for all pages, or another common part, it's better to use inheritance, that's achieved in two steps:
Basic template is created (containing general header and footer)
Specific templates are created via template inheritance feature, in particular, extends template tag in Django
Python is not PHP!
Django doesn't allow you to write arbitrary scripts(code) in templates. You should do all the computations/business tasks in views.py (controller) and pass results into template. In template usually you iterate over your result set and display data. In django 1.4 a new assignment tag was added , so you can do
{% get_movie_tickets_for_theater movie theater as tickets %}
but your get_movie_tickets_for_theater will be defined in templatetags python file.
I have an Django application where the URL's to be handled shall have a specific pattern like /servername/alpha/beta/2/delta/10/pie/1
Now i will be be needing these parameters contained in the URL and will persist them to the database when a URL beginning from /servername/ is being called.So i have 2 ways of doing it
Pass parameters along with request to the relevant view.In this case my regex would ensure that i have param1 through param7 having values alpha,beta,2,delta,10,pie and 1 respectively.
Pass only the request without passing the parameters.I will either parse using regex the request.path_info or split request.path_info on a "/" and obtain relevant entries
Which of these two methods shall be preferred in order to have better performance in terms of CPU and memory or maybe other factors i am not aware of.
I believe that one can compare the two using time functions but i believe it won't present an accurate picture.Theoretically which approach shall be preferred and why?
Option two is inherently slower as your view would need to do this parsing each time, whereas Django's standard URL parser works off of compiled regular expressions. (The urlpatterns in urls.py is compiled once on first run.)
However, the speed difference in either approach is pretty negligible. This will never be the bottleneck of your application; focus on things like your database and queries thereof and any I/O operations in your app (anything that writes or reads extensively from the hard drive). Those are where apps get slowed down. Otherwise, you're talking in terms of saving a millisecond here or there, which is fruitlessly pointless.
I'm trying to setup my Routes and enable an optional 'format' extension to specify whether the page should load as a standard HTML page or within a lightbox.
Following this http://routes.groovie.org/setting_up.html#format-extensions, I've come up with:
map.connect('/info/test{.format:lightbox}', controller='front', action='test')
class FrontController(BaseController):
def test(self, format='html'):
print format
This fails. My route gets screwed up and the URL appears as /front/test rather than /info/test. It's falling back to the /{controller}/{action}.
How do I allow for the format extension? :/
Generally:
http://pylonsbook.com/en/1.1/urls-routing-and-dispatch.html#pylons-routing-in-detail
Routes then searches each of the routes in the route map from top to bottom until it finds a route that matches the URL. Because matching is done from top to bottom, you are always advised to put your custom routes below the ones that Pylons provides to ensure you don’t accidentally interfere with the default behavior of Pylons. More generally speaking, you should always put your most general routes at the bottom of the route map so that they don’t accidentally get matched before a more specific route lower down in the route map.
The first thing I'd check is that you're using routes 1.12. Several distros are still on 1.11, which doesn't support format extensions.
Second, check the order in which your routes are defined. It matters.
I have some custom logic that needs to be executed every single time a URL is reversed, even for third-party apps. My project is a multitenant web app, and the tenant is identified based on the URL. There isn't a single valid URL that doesn't include a tenant identifier.
I already have a wrapper function around reverse, but now I need a way to tell every installed app to use it. The wrapper around reverse uses a thread-local to inject the identifier into the resulting URL. I could write this function as a decorator on reverse, but I don't know where to do the actual decoration.
Moderately Firm Constraint: I'm already using 3 3rd-party apps, and I'll probably add more. A solution should not require me to modify the source code of all these third-party apps. I don't relish the idea of maintaining patches on top of multiple 3rd-party source trees if there is an easier way. I can make the documentation abundantly clear that reverse has been decorated.
The Original Question: Where could I make such a change that guarantees it would apply to every invocation of reverse?
Possible Alternate Question: What's a better way of making sure that every URL—including those generated by 3rd-party apps—gets the tenant identifier?
BTW, I'm open to a better way to handle any of this except the embedding of the tenant-id in the URL; that decision is pretty set in stone right now. Thanks.
Thanks.
only way so that django reverse is replaced by ur_reverse is
django.core.urlresolvers.reverse = ur_reverse
or if you like decorator syntactic sugar
django.core.urlresolvers.reverse = ur_reverse_decorator(django.core.urlresolvers.reverse )
which i would not advice(and many will shout), unless you are not willing to change every usage of reverse with ur_reverse