Inject constant (e.g., API-keys) when serving javascript files with Flask - python

I have a web application using Flask and Jinja2. I would like to inject different API-keys depending on if I'm serving the site in production or testing.
I could inject them using the Jinja templating engine and use inline <script>-tags to then access them from my other JS. But preferably I would like to have some kind of really simple template-string in my .js-files, like this:
_ready: Keen.ready(function() {
var client = new Keen({
projectId: $KEEN_PROJECT_ID$,
writeKey: $KEEN_WRITE_KEY$
});
and then replace those keywords when Flask serve the file. Of course changing the value of the constant depending on which environment the server is running.
Are there any good ways of doing this?

A good way to do this is by adding a global to jinja. See this answer
You can then inject the api key wherever you need and keep your template code clean by having the lookup logic somewhere else

Related

Good Implementation : Isomorphic react app + Python backend

What is the best way to implement isomorphic react app using webpack with python as backend to serve
Following features are required to be implemented
1. React router
2. Redux store
By Isomorphic, I understand you mean both rendered on the server & on the client - so the first access of the site will return static HTML and a javascript bundle which then replaces the static HTML with the react-rendered version.
Usually this would mean running javascript on the server too with Node.js. This means you can render your JSX / React templates / components on the server and send them as static HTML to the user. If you're working with Python on the server, you cannot use your JSX / Javascript templating & logic on the server, so you'll need to duplicate it in Python.
So since you have to do it all twice - you first need to work out which one you want to do first. Either in Python first, or Javascript.
You can either start by building the whole application server-side-rendered, and then have javascript take over, or build a fully javascript application, and render the first views with Python.
Personally, for content-driven sites, I prefer building a server-side rendered application with Django (the most used Python Web Framework), and then adding Javascript on top once it's all fully working as a javascriptless site. This has the advantage of working even when javascript is disabled, and ensures you have good URLs, etc.
Of course, if it's a really complex application in terms of user interaction, you'll need to do it the other way.
I recomend looking into Django first, Here is a great tutorial from django-girls. However, if you want to go the mainly-JS route, here's some ideas:
Javascript First
Probably the best way is to first design your data structure(s), and make a REST api for your data. (e.g. /api/1.0/cars/rustbucket_94 which sends JSON data.)
Next, figure out your user-facing URL schema, and work out which REST endpoints need to be pulled in to get those pages. (How the URLs should look to the end users. e.g. /cars/rustbucket_94.html)
Design your React app as normal, using those REST / JSON endpoints, and the react router to show it correctly.
Once you have your whole react app working, you can now build a server-side rendered version of the whole thing, which you'll need to re-implement from scratch, and can either access the data through the JSON endpoints (slow) or by making the queries itself inside the pages.
The Python side
Which Python Framework to use on the backend?
I'd recommend Django to start with. It's very capable and can do ANYTHING you want it too. You probably need the Django REST framework too. There are other options available, but this will be the quickest way to get something secure and sane running.
Getting Django to work nicely with your webpack / react workflow is not too complex. There are projects like Django-Webpack-Loader and various tutorials about it online showing how to use it.
Good luck.

Cache busting with Django

I'm working on a website built with Django.
When I'm doing updates on the static files, the users have to hard refresh the website to get the latest version.
I'm using a CDN server to deliver my static files so using the built-in static storage from Django.
I don't know about the best practices but my idea is to generate a random string when I redeploy the website and have something like style.css?my_random_string.
I don't know how to handle such a global variable through the project (Using Gunicorn in production).
I have a RedisDB running, I can store the random string in it and clear it on redeployment.
I was thinking to have this variable globally available in templates with a context_processors.
What are your thoughts on this ?
Django's built-in contrib.staticfiles app already does this for you; see ManifestStaticFilesStorage and CachedStaticFilesStorage.
Here's my work around :
On deployment (from a bash script), I get the shasum of my css style.
I put this variable inside the environment.
I have a context processor for the template engine that will read from the environment.

Which Python template engine is safe to be used by untrusted users?

I'm looking for a good standalone Python template engine that is safe, against code injecting, to be used in an application that allows untrusted users to write and edit templates. Could someone recommend such an engine?
starcom referenced jinja.
The jinja website says, under "features":
Sandboxed execution mode. Every aspect of the template execution is
monitored and explicitly whitelisted or blacklisted, whatever is
preferred. This makes it possible to execute untrusted templates.

Django templating engine and external js files

I'm writing a Google app engine app and obviously the default web app framework is a subset of Django. As such I'm using it's templating engine.
My question is if I have say the following code:
template_values = {
'first':first,
'second':second,
}
path = os.path.join(os.path.dirname(__file__), 'index.html')
self.response.out.write(template.render(path, template_values))
And I want to reference the template value first in an externally included javascript file from index.html, do I just continue with the {{ first }} usage I'd go with in index.html itself or do I need to tell the framework about example.js somehow too so that it knows to replace the reference there?
Inserting the value into the javascript is probably a bad idea; wouldn't it make more sense for the script to be static and to have it grab the data either out of the DOM (assuming it's part of the HTML page you're rendering) or get the necessary data from the server using an AJAX call?
Disclaimer: my knowledge of app engine is limited so this answer may not serve your purpose.
In Django if you need to be able to pass variables from a view to a JS file you will have to ensure that the file is parsed by the template engine. In other words the file has to be served by Django. This means for e.g. that if you have a JS file in a media directory that is served by say, Nginx, you will not be able to use template variables in it.
I would expect the same to apply for app engine. But then see the disclaimer. I might be totally wrong :P

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