Jinja2: A Medium Between Python and Front End

Jinja2: A Medium Between Python and Front End

I first looked at Flask and Django because people said that if I want to use Python on a webpage I’d need a web framework. Turns out, the simpler thing to learn is not a web framework but a template engine.

What is a template engine? Who the hell knows? Do you think I knew as a beginner? Why do all these tutorials call it that? Tutorials for beginners, no less. And if you want to even learn one, Jinja2 in my case, you can barely find a tutorial that focuses on it. Most Jinja2 tutorials involve a great deal of Flask.

So here’s the thing, Jinja2 is the medium that weaves between Python and a webpage on the front end. It allows us to show results from a Python function in the back end on a web page. It can’t do everything but, sometimes, it’s more than enough for us.

As far as I know, Jinja2 remains an integral part of the Holy Trinity of Flask-Jinja2-Werkzeug. Pip install Flask would get you the entire Trinity. However, you don’t need to learn all of Flask to put Python functions on the web. You do still need to import flask in your script and learn the basics of where to put your files and how to name your folders the way Flask likes it, but after that, it can be simple. Here’s an example.

In your index.html file, which must be placed in the templates folder according to Flask’s preferences, you can have a string like, say:

I like {{type_of_jam}}.

In your server script, you can do:

@app.route(‘/’)
def mainIndex():
list = [‘butter’, ‘apple jam’, ‘orange marmalade’, ‘crude oil’]
jam = random.choice(list)
return render_template(‘index.html’, type_of_jam=jam)

And that’s it. Your string on the webpage randomly displays a type of jam.

You can do other things with it, of course, and you’ll need some more knowledge to better appreciate what it can do. But my point is, for beginners to get to here, we first need to tunnel through mountains of other stuff, a lot of which is unnecessary (even if nice) simply because the current ecology of pedagogical resources don’t design for noobs.

+1 to Digital Literacy

+1 to Digital Literacy

I stumbled into an idle moment and used it to ponder digital literacy. I’ll summarise the Wikipedia link’s summary as the abilities to:

  • “Deduce information from visuals”
  • Create remixes
  • Navigate the non-linearity of the web
  • Find info online and be critical about it
  • Not be an asshole online

I know my summary is not perfect, but neither is the original. I think mine’s more precise. I mean, “don’t be an asshole”. That’s pretty damn clear, right?

Anyway, I think we should add one more. Admittedly, it’s a high-hanging fruit, but I think it’s increasingly important:

  • Find solutions to coding problems even if they are someone else’s script on Stack Overflow that you don’t fully understand.
Programmers Protest Broken Interview Process

Programmers Protest Broken Interview Process

Someone responded to “whiteboard algorithm hazing” and a lot of other programmers followed suit. The term refers to when interviewers make you write code on a whiteboard.

It’s a great piece. Check it out. Not extensive, but super important to let beginners like us know we don’t have to be so fucking intimidated, and scared out of wits, and anxious to death all the time just because we think we aren’t good enough. That’s no way to live.

I don’t think I’d ever be able to pass a whiteboard test simply because coding is a different embodied experience from writing. I’m pretty brilliant at writing, and I can write really well on the whiteboard, but it’s not the exact same animal as coding.

Both writing and coding are thinking processes. We don’t use just our brains to think. Writing helps us to articulate and develop our ideas. At least for me, if I don’t write, I’d be stuck at or near the inception point of an idea. If I start writing it out, even if I have no idea where I’m going with it at all, not even the next step, I develop it into a stronger concept and at a much faster pace too.

Usually, I use both pen and keyboard to do it. I think some studies show that there’s a link between exercising the pen and brain activity, or something. Idk, forgot the details. But anyway, that’s why I call it “embodied”. I think other people have called it “embodied” before me.

Coding is the same, but also different. It has its own fluidity that works under certain conditions. Whiteboard hazing separates the coder from the environment that helps him best, like taking a fish out of water and asking it to swim. Maybe some fish can do it, but it’s not usually helpful. Tabbing between Google, Stack Overflow, Quora, YouTube, Coursera, documentation, and whatever else resource you have is part of the flow.

Plus, community is important to coding. Once you’re in the flow, you access other people’s work, read other people’s solutions, and ask others for help. Inevitably, you contribute too, even if it’s reminding a friend that he/she missed a semi-colon somewhere. IRC channels, forums, Facebook groups, hackerspaces, and friends are super important for that.

Ironically, the geek so stereotyped to be awkward in social circumstances really knows how to build communities and relationships that are vital to problem-solving.

I’m not an experienced coder, but I’d say it’s ok not to have everything at the tip of your fingers.

Path of Least Resistance: From Knowing Nothing to Python to Flask

Path of Least Resistance: From Knowing Nothing to Python to Flask

I have to work on urgent stuff so I can’t go on with Flask for the moment. 😦 But I want to quickly pen down what I think might be the relatively easiest way to go from knowing nada to learning to make a web app, based on my experience.

Code Academy

Easy stuff. Dip your feet in shallow waters with its Python course. Also do its HTML, CSS, and Javascript stuff.

Learn Python the Hard Way (LPTHW)

First half was good, second half got too hard, partly because the way things were explained did not agree with me. I quit this site in its last third, I think.

PythonProgramming.net

I think I did Python basics on this site in the same period I did LPTHW. I may have done one or two other basic tutorials too because I wanted strong enough fundamentals to make learning the harder stuff easier later.

I don’t think my fundamentals are strong even now though. For instance, I’ve never written a class and I’m not sure I know how to.

Web Design for Everybody (Basics of Web Development and Coding), with Colleen van Lent

Lent is very clear on most things. I also did a Bootstrap course somewhere online but I can’t remember what it was. Learning front end stuff helps me understand which code comes from what programming language and where it should go when doing Flask. Learning Flask will involve Python, SQL, HTML, CSS, and JS, at some point or other.

I didn’t do the Capstone for this or any other Coursera course I did, because it costs money.

Python for Everybody, with Charles Severance

The first couple of Python courses in this specialisation are pretty all right. But I feel beginners require a lot more hands-on/embodied experience before we know to use Stack Overflow and other resources as vital supplements to understanding the things instructors miss out, and to troubleshoot all kinds of problems course instructors could not predict might affect their students. This is why it’s a good idea to go through Code Academy and LPTHW before doing this Coursera specialisation.

Severance is the clearest instructor I’ve come across on the things he goes through in the “Using Python to Access Web Data” and “Using Databases with Python” courses. I gave up working on a couple of the more complicated projects towards the end, in part because the instructions grew less and less and I kind of still needed them. But most of the courses are really pretty damn great.

Templating With Jinja2 in Flask

I didn’t finish even midway through part 3 of this series but the first two parts gave me a pretty ok beginner grasp of Flask with respect to Jinja2.

CS350 Flask tutorials on YouTube

For me, the clearest instructor and content so far when it comes to Flask. I’m slightly less than halfway through at the moment, though, I think.

UPDATE 19 April 2017: Model-View-Controller (MVC) Paradigm

At this point, I feel, it’s time to focus on two things: security, and the MVC paradigm. I am presently trying to figure out flask-security, but haven’t found good enough teaching/learning material for it. Please message me if you know some.

For MVC, this is a good introduction:

It helped me a lot, made me realise I could reduce my code by around 90%.

Others

Throughout this journey, Stack Overflow has been absolutely vital for finding solutions to miscellaneous problems. But usually, I google my problems and it finds solutions on Quora and a lot of other great websites too. I tried duckduckgo but its results were dismal for research.

UPDATE 2 April 2017: Yes, CS350 is good, but slightly more than halfway through it, I found myself building my own web apps, and that meant that I began seeking solutions from everywhere. It was a sudden and significant decentralisation of sources. A bit more detail in Part 3 of my experience learning Flask.

Attempting to Learn Flask, Part 2

Attempting to Learn Flask, Part 2

23 Feb 2017

I thought I’d break up the holy trinity of Flask to make it easier to learn: Flask, Jinja2, and Werkzeug. As it turns out, separating Flask from Jinja2 might be impossible. I don’t know for sure yet. Anyway, I used Shalabh Aggarwal’s tutorial, which is thankfully focused on templating, which means a bit more Jinja2 than usual.

I am still trying to get the hang of Flask spreading code over many files, and involving code from Flask, Jinja2, HTML, and even JS and CSS. But I feel like maybe I am progressing, even if just a tiny bit. It’s hard to tell since progress is incremental. I’ll know soon, I hope.

I couldn’t do part 3 of Aggarwal’s tutorial. Something is wrong somewhere and I have no clue what it is. In part 2, I couldn’t import render_field from _help.html as _help.jinja. So I googled it and found a solution, which was to import the whole _help.html and call render_field normally, like form.render_field(). I have no idea why Aggarwal’s method didn’t work for me.

25 Feb 2017

So, after slightly more than a full week floundering, I might have found a good tutorial. I don’t know whom he is, but this CS350 chap seems pretty ok so far, although admittedly, we haven’t reached any of the difficult stuff yet.

In spite of that, I do like that he introduced me to Cloud9 and Gitlab. Cloud9, especially, might solve some issues for me. For instance, the Werkzeug site uses Redis for its tutorials, and it doesn’t quite run on Windows, and I couldn’t figure out how to use the version ported to Windows to work alongside the code the Werkzeug tutorial provided. Cloud9 allows me to run Linux, amongst other things, which means I can use Redis if I want to. CS350 doesn’t use Redis though.

I know I could have used VirtualBox, but I find it a bit of a pain to use, for reasons I no longer remember. Haven’t used it in a while.

And yes, after I tried out Aggarwal’s Jinja2 templating tutorial, I decided to try a Werkzeug one, using the official site’s tutorial. It was horrible. I gave up midway because I couldn’t figure out the Redis bit.

26 Feb 2017, Part A

Following CS350 into PostgreSQL on Cloud9. It’s unfamiliar, because I don’t see the SQL database file anywhere in Cloud9. The method of interface makes it a bit hard to grok. The data is rendered in text on the command line. Is that ASCII? I don’t know. Anyway, I do understand it a little because a month or so ago I did Charles Severance’s excellent Using Databases with Python. It uses SQLite. So, I kind of get some of the commands. I wish I could continue with SQLite though and the DB Browser for SQLite within the CS350 tutorial though. It would make the learning experience a lot smoother.

It might be possible if I had more knowledge, but in that scenario, jumping between the YouTube channel, Cloud9, Gitlab, and whatever other resources I might leverage to use SQLite would make things more complicated.

26 Feb 2017, Part B

Ran into seemingly insurmountable problems when CS350 decided to use psycopg2 in its tutorial. Various forums had different solutions and some of it coincided with my own suspicions. Generally, these were:

  • The right dependencies hadn’t been installed.
  • I didn’t know to use sudo to install/upgrade it.
  • I didn’t know apt-get and pip well enough to use them properly.

It was super confusing. At first, I used apt-get and pip, and sudo apt-get and sudo pip, to install it. I ran pip freeze and found it wasn’t in the list of installed packages. I tried various things after that and at one point, pip freeze said I had the latest version of psycopg2, but I checked Pypi, and I definitely had the wrong one. I ran sudo apt-get update but it still gave me the wrong version.

I basically ran through permutations of solutions for all three of the above possible problems and finally,  got the right version of psycopg2. It took about two hours and every minute grew more and more despondent until that final moment it suddenly worked.

This is how I solve this kind of Python problem(s). I had to do this with NLTK too. It always drains me. Now I need to take a break.

Anyway, this problem prompted me to find out what the differences are between apt-get and pip. Now I know.

26 Feb 2017, Part C

On a tram to friend’s for dinner. Put two and two together and figured out that I can use <input type=’submit’ name=’placeholder’>request.form[‘placeholder’] and cur.execute(“””SQL COMMAND”””) to mediate between front end users and database.

Am I right? Is this the standard way to do it? Can’t wait to go on with the tutorials and/or figure it out another way.

Attempting to Learn Flask, Part 1

Attempting to Learn Flask, Part 1

I think this might be a series on how I learn Flask. I don’t know if I’ll succeed or fail yet at learning it. I’ll try and track my progress or the lack of it, and hope I don’t run out of steam.

So, I’ve been trying to learn the framework for a while now. The first time I tried was two or three years ago when I first started Python. As you might guess, it was totally the wrong time to start. Now I have a better handle on Python, and I thought about a week or so ago that I’d try again.

Deciding on Flask and Not Django or Bottle or Whatever Else

As it happened with the first time, googling turned up a lot of “should I learn Flask or Django” results and I wavered between the two, and installed both, and then once again decided to focus on Flask.

The decision isn’t that simple to make because lots of people say different things, but I’ll boil them down to two main factions.

One faction says to learn Django because it is sort of standardised. It’s like a set meal. You get burger, fries, soft drink, all together in a sensible, familiar package. As a result, it is also complicated and has a steep learning curve. But, community support is waaaaaaaaaaaaaaaay better than Flask’s! That counts for a lot.

The other faction says to learn Flask because it’s flexible and easier to learn. That means, though, that it’s not like a set meal at all. What it looks like is someone giving you all the raw ingredients of the meal and you have to put it all together yourself. So, you have to learn how to build a burger, and then how to make fries just the way you like, and then the soft drink. People say it’s not that hard, but the people who say that seem to mainly be experts, or those with computing backgrounds, or those with money for boot camps and advisors and teachers. Obviously, it’s not hard for them. Plus, community support is very thin compared to Django’s.

There are other factions, but these are generally the two loudest voices. After a lot of going back-and-forth, deciding, re-deciding, indecision, paralysis, doubt, existential crisis, I settled on Flask because a few people said it’ll be easier to learn Django after Flask. And more importantly, I needed to focus somewhere, and it might be easier to start with what other people claim is easier.

Easy?

Once beginners start asking questions like, how do we use Python on the web, the answer is bound to be: learn a framework. Remember, at this point, beginners haven’t much of an inkling what Flask is, or even what a web framework is. Everything we read about frameworks online seems to make sense, but only in a sort of hazy, somewhat figurative manner. In other words, it’s likely that experts think they’ve explained it clearly, and beginners think they sort of understand, but there’s a massive gap between the two, and few people see it. Nonetheless, the only way is forward, right?

But the jump from basic/intermediate Python to learning a framework like Flask is HUGE. This will become very apparent when beginners start on the tutorial everyone suggests: Miguel Grinberg’s Mega Flask Tutorial.

This tutorial is spectacularly bad for beginners.

The tutorial doesn’t explain a lot of things, including precisely where Python code connects with its equivalents in the HTML templates. You might say that should be obvious. But it’s obvious for people with a much larger store of knowledge than beginners.

At the same time, the tutorial involves a lot of code connected to each other across many files, in ways that we cannot understand at a glance. Some functions require ostensibly unrelated code inserted into views.py, models.py, config.py, and one or two others. That’s super confusing for beginners.

By the time we reach the part where we write the login page, we give up. Especially because at that point, we have to decide between the chapter from the older tutorial, and the newer one on OAuth that isn’t very clearly connected to the older tutorial. And if we screw either up, we don’t know how to continue with the rest of the mega tutorial.

It Gets Cloudier

At that point, we start looking for other tutorials. A bunch of these want us to start on Droplet (we have to pay for it), Heroku, or other similar services. Only here do we usually get the first mentions of Flask being problematic on Windows, and we’re not sure what that means.

So, we’re stuck. We don’t want to pay for Droplet. And we are scared that if we go with Heroku, we might go off on another difficult tangent with more difficult stuff to learn. We begin to wonder if there’s another tutorial, or if there are ways to work around this.

What do we do next? I don’t quite know yet.

How to Learn Flask

Evidently, there is a big portion of knowledge missing between basic/intermediate Python and Flask. But I don’t know what it is and nobody seems to proffer good estimates. So, I’m going to try two methods people have intimated in the usual overly optimistic terms. “Just do it!” doesn’t cut it, guys.

The first is the project-based method: I know I want to build a chat website, and I have a rough design for it. I know I want to have some development for ecommerce under my belt so I can build a career from it. So it makes sense to start with these two.

The second is to try and break up Flask into small and manageable parts and learn those parts. This is somewhat problematic. People say you can do anything with Flask. That means we don’t know where to begin. It’s like saying, you can do anything you want, so what do you want to do? Well, I want to solve poverty. Maybe I want world peace too. But what are the small tiny manageable parts to those problems? It might be impossible to see. We might get there by iterating through lots and lots of smaller and smaller problems though.

You see how unhelpful it is as a pedagogical guide to tell beginners you can do anything with Flask and then send them to difficult tutorials?

In part 2, if there is a part 2, I will talk about how I got on with this.

Autodidacts and Accreditation

Autodidacts and Accreditation

This bit of news about someone who learnt dentistry skills on YouTube has been making the rounds:

uckjrgq

I’ve traced it only to Kementarian Kesihatan and Sim Bak Heng report quite a bit on Terengganu. Provenance seems ok. You can mail Sim and ask about it if you like. I can’t be arsed.

Provenance aside, the article raises an extremely timely question. That is, where do we learn best these days? For me, it’s been the internet. For the social sciences, Sci-hub is indispensable. There are also a lot of lectures and other material on YouTube from Stanford, Cornell, the National University of Singapore, etc.

For programming, a combination of MOOC’s, Stack Overflow, and an assortment of other sites googled up as and when specific problems pop up has been the perfect cocktail.

I’d love nothing more than to go to school to learn programming, and anthropology, and all the rest, but I don’t have the money to. And it’s unwise to do so anyway because job and other issues from daily life mean few of us can keep to schedules properly. Online resources bear flexibility that fits our needs.

But that raises another question: what about accreditation?

I don’t know. A lot has been written, but I don’t think anyone knows yet. I don’t think companies, institutions, and the state are willing to accept what has become true, that is, many of us don’t learn as effectively in school as we do online. School is imprisonment, and the subjects we take there are forced on us. We have to wait till school ends so that we can learn what suits our passions best. And then we have work and family and other things that stand in the way. Sometimes, we need the experience of life to figure things out on our own, before we can start learning what we need and want. Late-bloomers aren’t rewarded by conventional society, but they should be.

The internet helps a lot. Along with all the people making resources online and free, it’s potentially life-changing. I wish formalised entities would catch up with the times and create structures that would make acceptance of autodidacts easier.