Create a mini blog

Right, to the final part. Let’s create a mini blog.

There is some debate in the database world: SQL vs NoSql. We don’t know which one is better, so we will use a much cooler approach, one that is far more powerful……. **Drums rolling ** ………………. a list. Yes sir, a plain old fashioned Python list. Much better than all this fancy NoSql crap (just kiddin’. Please don’t quote me on this).

To start off, add this to secret.html, somewhere in the middle:

<h3>Posts:</h3>
 {% for p in posts %}
    
    <strong>Post:</strong> {{ p }} <br/>
    <br/>
 {% endfor %}

In the example above, we are using the for loop to loop through posts. Now we need to pass these posts in. Go to blog.py, and somewhere near the top of the file, add:

This is a simple list. You now need to pass it in to the html file:

Run the script, you should get:

Add posts

Now we need to be able to add posts as well:

At the top of secret.html, add:

<form action=“{{ url_for(‘add’) }}”  method=”post”>
    <p> Enter the post dude</p>
    <input type=”text”, name=”post”>
    <input type=”submit” value=”Send the post, man”>
    </form>
</form>

The key thing above is in bold: We are inserting some code into the html. url_for is the Flask command to redirect to a url. In this case, it will be /add , which we will define now. Open up blog2.py:

Most of this is the same as before. The only new line is:

We read the form on secret.html. Read the html above again: When we do a post, it calls the add url function. This blog is read to the variable blogRead, which we then append to our list posts. We then redirect back to secret.html, so it can display the post we just added.

Of course this method is not permanent- if you restart the server, you will lose all entries. This is where you need a database. However, this tutorial was just to give you a flavour of flask.

Here is the source code: Flask blog.zip