Why should JavaScript files be localised differently in Django? - python

When localising Django application the makemessages command simply parses all the TXT, HTML and PY files and generates PO files for them but when localising JS files, you need to run the djangojs command. I haven't delved into the Django source to figure out why this done differently. Could someone explain?
I've read that in production environments, Apache is used to serve the application files while a simple proxy like Nginx is used to serve static files as this greatly reduces the load on the application server. With this scenario, I guess it works like this: when rendering a template, Django checks the requested locale, loads the appropriate localisation file and serves the template but JS on the other hand being served as static media doesn't get parsed by Django. Is this it?
(Its my first foray in to the world of localisation with Django and I'm packed full of question, many of who's answers I can't seem to find and therefore this post.)
Thanks

The reason why it's handled differently is in the docs.
Adding translations to JavaScript poses some problems:
JavaScript code doesn't have access to a gettext implementation.
JavaScript code doesn't have access to .po or .mo files; they need to be delivered by the server.
The translation catalogs for JavaScript should be kept as small as possible.
So essentially, the internal Python translation is done on the server. But for JS, there's another file served by the server, which contains all the required translations for user's language. And the translation is done on the user's side. So as you can see, it's a completely different strategy. Django helps by adding similar interface for JS files, even though they're handled in a completely different way.
I guess it works like this: when rendering a template, Django checks
the requested locale, loads the appropriate localisation file and
serves the template but JS on the other hand being served as static
media doesn't get parsed by Django. Is this it?
You are right in the first part, about handling templates. Handling JS works as I've explained above.
Note that Django JS translation mechanism, doesn't treat JS translations as static files. It uses a Django view to generate the JS file everytime (javascript_catalog mentioned in the docs linked in the first line).
That is one of the problems I've encountered. Such files don't need to be generated on every request. There are some projects that actually let you pack those JS translations as static files and enable you to cache them properly (like django-mediagenerator).

Related

Django & React with django-webpack-loader vs Decoupled App structure linked to Rest API?

I am reading through the following tutorial:
http://v1k45.com/blog/modern-django-part-1-setting-up-django-and-react/
I can't quite grasp what the added value is of using something like django-webpack-loader to fully integrate react.js and django when you can completely decouple django from react, running a separate frontend which links to a DRF rest api.
I may be comparing apples to oranges here, but I am not sure. Any help ?
From the django-webpack-loader tutorial:
Now that we’ve handed off the build process webpack, only thing we need on the django side is to know which bundle to include in our html pages. This is where django-webpack-loader comes in. It’ll also raise exceptions when webpack fails to build a bundle and will show some useful information to help debug the problem. During development, webpack loader will also block requests while a new bundle is being generated so that only the latest bundles are loaded.
This is the core functionality of that loader. It tells django which are the current bundles to be served. It does not server side render your react app nor does it replace an API that the app needs to consume.
When developing a react app you usually use some kind of bundler that transpiles your javascript code to es5, uglyfies and minifies it. So every time your code changes a new bundle will be created containing your new javascript. A lot of people are using webpack for this task.
Now when a request arrives in django it needs to serve the basic html along with the css and js to be loaded by the client that contains the react app. So django needs to know the path to the files to link. But the path may constantly change when webpack rebuilds them. django-webpack-loader helps you to keep track of these changes and includes the correct paths to the current bundles for your react app to be fetched.
It is not a replacement for an API. Its sole task is to resolve the correct paths to your react app files.
EDIT
So the primary purpose of django-webpack-loader is to ensure that the paths to the most recent build are resolved correctly and in turn can be served. What is the reason these paths will change ?
Weppack appends a random hash to a new bundle like bundle.4j2a032fg.js. This way django can tell the client to cache the script so that it does not have to be re-request it every time. The client will only request a new bundle if the url/path changed. But this also requires that django knows the newest bundle with the correct hash.
does server side rendering occur with the use of Django templates ?
Server Side Rendering (SSR) in the context of react means that a nodejs server actually runs the react application once on the server to produce the initial markup of the app. This can then be statically served with the app. It reduces the perceived loading time for the user because the initial state of the app will immediately be shown and it allows for search engines to statically analyse the page which is good for SEO.
While django does render templates it is only the static html around the react app which it will render by default. Django does not render the react app itself. The react app still needs to initially render itself on the client. So to enable django do do true server side rendering you would have to run a nodejs process next to django that does the static rendering of the react app for django to serve.
In the tutorial they are using templates. Templates are loaded in the backend. So user gets fully rendered page.
With django rest framework you need to write seperate fronend. More about this: https://nickjanetakis.com/blog/server-side-templates-vs-rest-api-and-javascript-front-end

Is it possible to generate static html from Django Cms?

Hi I'm working on a project based on Django Cms
DJango Cms
Most of the templates ara generated via an APi call in ajax.. I wondered if is possible to generate an HTML static file from the original template file in order to avoid dynamic calls.
Short answer: Yes.
Long answer: It depends.
There's little stopping you from just creating static HTML pages (you could for example just use wget to crawl you website. However note that this only works if your content is not dynamic, as in, it doesn't depend on whether a user is logged in or not etc. If you only use plugins that always have the same output, regardless of the request, then it'll work.
Since Django CMS gives you a lot of power to write highly dynamic plugins, there's no built-in way of generating these static pages (the chances of someone using it without realizing the drawbacks are high).

Django - Privatizing Code - Which files are served to a user?

I am using Django to develop an API using an algorithm I wrote.
When someone requests a url, my urls.py calls a function in views.py which serves
page that returns a JSON string.
If my algorithm is in my views.py file, or in another file on my server, would it be possible for a user to view the contents of this file, and then see my algorithm?
In other words, when using Django, which files will never be served to a user, and which files will be?
Is there any way I can stop someone from viewing my algorithm if it's in a .py file? Other than Chmodding the file or encrypting the code?
Thank you for your time.
Django only serves the responses that you explicitly create and return from your views. There is no general ability to request files from it.
Make sure your source code isn't in a directory that your web server is configured to serve from, and make sure your settings.py value for DEBUG is False, and you should be fine. Oh, and just in case - don't try to use the Django development server in production.
As long as nobody has shell access to your server, people will never see more than the actual HTML output of your page. .py files are not shown to the user that has requested an url in the browser.

django dynamic file serving optimization

I am working on a django project that provides an API to generate thumbnails of images, and the basic logic is like the following:
when the source image URL comes for the first time, the django would do some sort of image manipulation, and return the thumbnail image
when the same image URL comes again, django would simply serve the previous thumbnail image (stored as static media) again.
basically, case 2 happened much often than case 1. Now I used django to serve the images all the time, which I believe is a bad practice.
I wonder if it's possible to do a better way of image serving for case 2? For example, is there some sort of way to ask django to send proxy requests to apache and ask apache to serve the file?
I know I could use HTTP redirect to do that, but that seems to generate too much redirect requests on the client side (one HTML page would contain a lot of links to this API).
thx.
The simplest solution of the top of my head would be to use an Apache rewrite rule with a condition.
RewriteCond %(REQUEST_URI) ^media
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule #Some rewrite rule to redirect from '/media/filename' to '/image_generator/filename'
This basically just checks to see whether the file exists in the media directory, and if it doesn't it sends the user to the image generator, which can then generate and save the file to /media where it can be found for the next request.
NB: I've never actually tried this sort of redirection with Django, so it may need some measure of tweaking..
For example, is there some sort of way to ask django to send proxy requests to apache and ask apache to serve the file?
You have that exactly backwards.
Read the Django deployment guide. https://docs.djangoproject.com/en/1.3/howto/deployment/modwsgi/#serving-files
Apache should be serving all static files (images, for example) all the time. Always.
Django should never, ever serve an image file (or a .css or .js or anything other than .html).
See later part of this section in documentation:
http://code.google.com/p/modwsgi/wiki/ConfigurationGuidelines#The_Apache_Alias_Directive
Using Alias/AddHandler/mod_rewrite allows Django to overlay static files in filesystem. In other words, static files take precedence.

What to do after starting simple_server?

For some quick background, I'm an XHTML/CSS guy with some basic PHP knowledge. I'm trying to dip my feet into the Python pool, and so far understand how to start simple_server and access a simple Hello World return in the same .py file. This is the extent of what I understand though, heh.
How do I integrate the simple_server and your basic XHTML/CSS files? I want to start the server and automagically call, for instance, index.py (does it need to be .py?). Obviously within the index file I would have my markup and stylesheet and I would operate it like a normal site at that point.
My eventual goal is to get a basic message board going (post, edit, delete, user sessions). I realize I'll need access to a database, and I know my way around MySQL enough to not have to worry about those portions.
Thanks for the help.
EDIT: Allow me to clarify my goal, as I have been told Python does a LOT more than PHP. My goal is to begin building simple web applications into my pre-existing static XHTML pages. Obviously with PHP, you simply make sure its installed on your server and you start writing the code. I'd like to know how different Python is in that sense, and what I have to do to, say, write a basic message board in Python.
The other answers give good recommendations for what you probably want to do towards your "eventual goal", but, if you first want to persist with wsgiref.simple_server for an instructive while, you can do that too. WSGI is the crucial "glue" between web servers (not just the simple one in wsgiref of course -- real ones, too, such as Apache or Nginx [both with respective modules called mod_wsgi] as well as, for example, Google App Engine -- that one offers WSGI, too, as its fundamental API) and web applications (and frameworks that make it easier to write such applications).
Everybody's recommending various frameworks to you, but understanding WSGI can't hurt (since it will underlie whatever framework you eventually choose). And for the purpose of such understanding wsgiref.simple_server will serve you for a while longer, if you wish.
Essentially, what you want to do is write a WSGI app -- a function or class that takes two parameters (an "enviroment" dictionary, and a "start response" callable that it must call back with status and headers before returning the response's body). Your "WSGI app" can open your index.py or whatever else it wants to prep the status, headers and body it returns.
There's much more to WSGI (the middleware concept is particularly powerful), though of course you don't have to understand it very deeply -- only as deeply as you care to! See wsgi.org for tutorials &c. Gardner's two-part article, I think, is especially interesting.
Once (and if that's your choice) you understand WSGI, you can better decide whether you want it all hidden in a higher level framework such as Django (so you can focus on application-level issues instead) or use a very light and modular toolbox of WSGI utilities such as Werkzeug -- or anything in-between!-)
I would recommend Django.
"Obviously with PHP, you simply make sure its installed on your server and you start writing the code."
Not true with Python. Python is just a language, not an Apache plug-in like PHP.
Generally, you can use something like mod_wsgi to create a Python plug-in for Apache. What you find is that web page processing involves a lot of steps, none of which are part of the Python language.
You must use either extension libraries or a framework to process web requests in Python. [At this point, some PHP folks ask why Python is so popular. And the reason is because you have choices of which library or framework to use.]
PHP parses the request and allows you to embed code in the resulting page.
Python frameworks -- generally -- do not work this way. Most Python frameworks break the operation down into several steps.
Parsing the URL and locating an appropriate piece of code.
Running the code to get a result data objects.
Interpolating the resulting data objects into HTML templates.
"My goal is to begin building simple web applications into my pre-existing static XHTML pages."
Let's look at how you'd do this in Django.
Create a Django project.
Create a Django app.
Transform your XTHML pages into Django templates. Pull out the dynamic content and put in {{ somevariable }} markers. Depending on what the dynamic content is, this can be simple or rather complex.
Define URL to View function mappings in your urls.py file.
Define view functions in your views.py file. These view functions create the dynamic content that goes in the template, and which template to render.
At that point, you should be able to start the server, start a browser, pick a URL and see your template rendered.
"write a basic message board in Python."
Let's look at how you'd do this in Django.
Create a Django project.
Create a Django app.
Define your data model in models.py
Write unit tests in tests.py. Test your model's methods to be sure they all work properly.
Play with the built-in admin pages.
Create Django templates.
Define URL to View function mappings in your urls.py file.
Define view functions in your views.py file. These view functions create the dynamic content that goes in the template, and which template to render.
Take a look at CherryPy. It's a nice http framework.
It depends on what you want to achieve,
a) do you want to just write a web application without worrying too much abt what goes in the background, how request are being handled, or templates being rendered than go for a goo webframework, there are many choices simple http server is NOT one of them. e.g. use django, turbogears, webpy, cheerpy, pylons etc etc
see http://wiki.python.org/moin/WebFrameworks for full list
b) if you want to develope a simple web framework from start so that you understand internals and improve you knowledge of python, then I will suggest use simple http server
see
how can you create a URL scheme so that URLs are dispatched to correct python function,
see how can you render a html
template e.g. containing place
holder variables $title etc which
you can convert to string using
string.Template
b) would be difficult but interesting exercise to do, a) will get you started and you may be writing web apps in couple of days

Categories