Stage 4: adding comments to your website

Introduction to networks

The Internet is a network of computers. Here are a few important words to remember:

Making the Internet work for you

A few reminders and new concepts for URLs:

A few reminders/new concepts for HTTP:

Servers: their purpose is to respond to and HTTP request. Their response can be static (pre-written file, image...) or dynamic (file generated dynamically by a program called a web application). In the case of user entering data through a form, the servers will first present the form through a GET request then send the data through a POST request with a possible redirect.

Forms

There is a tag called <form>. It has a closing tag as well and is used to create forms through which the isers can enter data. Inside a form we can have:

Break Modulus and Dictionaries

The Modulus is the remainder of a division: 13 % 11 = 2,

Dictionaries: they use curly brackets and associate keys with values: d = {"hydrogen": 1, "helium": 2}. In this case print d["hydrogen"] would return 1. Note that we still use the square brackets to access the elements. Like lists, dictionaries are mutable (strings aren't). You can check if an element is in a dictionary by using in: print 'lithium' in elements. In the case above this would evaluate to False. You can also add elements by using the following form: dictionary['newKey'] = value. Note that when using this code, if the key already exist, it will just update the value. What makes dictionaries interesting is that the value of a key can be anything, like strings and numbers, but also other dictionnaries.

Google App Engine and GET/POST methods

From the Google developper console we can create and manage projects which have a unique ID. This ID can be overrriden as long as it is unique. We can then download some starter code. The starter code imports webapp2 which has been downloaded at the same time as the app engine. In every starting folder there should be two files: a main.py file and a app.yaml file. The yaml file points the app engine to the Google project and therefore tells it where to deploy the code. Can be overriden if necessary.

There is also a main.pyc file after the code has been compiled a first time. The Python intepreter creates it to not have to recompile .py files unless necessary.

To use the app engine properly, it is important to understand the differences between GET requests (default requests) and POST requests (specified method).

GET methods:

POST methods:

It is nice to redirect after a form subimission because this way reloading the page doesn't resubmit the form and because it also enables us to have distinct pages for forms and success pages.

Validation

String formating

String formating will become very handy when implementing templates. There are three types of substitution:

  1. Simple substitution, where %s can be replaced by a string or a variable just once: "Hello %s" % "John" or "Hello %s" % name
  2. More complicated substitution where multiple %s can be replace by several unique strings or variables: "Hello %s %s" % ("John", "Smith") or "Hello %s %s" % (name, surname)
  3. Complex substitution using a dictionary where some strings can be used more than once: '%(last)s, %(first)s %(last)s' % {'first': "James", 'last': "Bond"}

HTML Templates

Templates are extremely useful for various reasons. One of the main ones is that by offering inheritance and code handling, they limit the data that has to be created more than once, i.e.code duplication, which is an important source of errors and bugs. They also offer escaping, which is a significant security feature.

Variable substitution in Jinja2: use double curly braces: {{variable}}. These double curly braces basically mean "print" and the "variable" can be any piece of Python code. For example: <h2>Hello, {{name}}</h2>

Statement syntax in Jinja2:
{%statement%}
output
{%end statement%}

example:
{% if n == 1 %}
n equals 1
{% else %}
n does NOT equal 1
{% endif %}

For loop synthax:
{% for statement %}
body
{% endfor %}


example:
{% for x in range(1,n+1) %}
<li>{{x ** 2}}</li>
{% endfor %}

In Jinja2 (and other templated languages, there are two was of ecaping fields. One at template level when setting up the template: jinja_env = jinja2.Environment(loader = jinja2.FileSystemLoader(template_dir), autoescape = True) and one at field level with the pipe symbol acting as a filter: <li>{{ item | escape }}</li>. If you used the autoescape symbol, you can use the safe filter to opt the field out: <li>{{ item | safe }}</li>

A few tips:

Template inheritance: Jinja makes it really easy to maintian html pages by using inheritance. In between the <body> tags, yop can use the following syntax to include a block of content:

{% block content%}
{% endblock %} You will have to use the two same tags on your actual template at the top of which you will have to inclue the "extends" line: {% extends "file.html" %}

In a nutshell, templates have several advantages:

You can find out more about jinja here.

Databases

Database are used to store and retrieve large amounts of organised data. The word database can refer to the software used, the machine that actually runs the software or the group of machines that performs the tasks. Databases use tables that contain the data. Querying them with Python is very hard and tedious(named tuples,lambda, .sort(), dictionaries). There are different types of databases:

SQL stands for Structured Query Language and was invented in the 1970's. It has the following format: SELECT * FROM links WHERE id = 5

Python does have a module called sqlite3 that can be imported. See query_exercise_1.py to query_exercise_5.py

Joins: we don't really use them

Indexes: theu increase the speed of databases reads (but not inserts...) as there is no need to scan all data. If we have a function to build the index table once, then we don't need to scan through all thedata every time with the other funtions:


def build_link_index():
 my_index = {}
  for l in links:
  my_index[l.id] = l
 return my_index

Hash tables are not sorted but tree data structures are. They are also slower as the size of the tree increases

ACID: Atomicity, Consistency, Isolation and Durability:

The Google App Engine Datastore: