BogoToBogo
  • Home
  • About
  • Big Data
  • Machine Learning
  • AngularJS
  • Python
  • C++
  • go
  • DevOps
  • Kubernetes
  • Algorithms
  • More...
    • Qt 5
    • Linux
    • FFmpeg
    • Matlab
    • Django 1.8
    • Ruby On Rails
    • HTML5 & CSS

Flask blog app tutorial 3 : Adding blog item

Python-Flask.png




Bookmark and Share





bogotobogo.com site search:



Note

In the previous part of this series, we implemented the sign-in and sign-out.

In this part of the series, we'll let user add a blog post.

Here are the files we'll be using in this tutorial part-3:

tree-p3.png

They are available from FlaskApp/p3







Adding blog post

We'll start by creating an interface for the logged-in user to add a blog post. Let's create a file addBlog.html:

<!DOCTYPE html>
<html lang="en">
  <head>
    <title>Python Flask Blog App</title>

    <link href="//getbootstrap.com/dist/css/bootstrap.min.css" rel="stylesheet">

    <link href="//getbootstrap.com/examples/jumbotron-narrow/jumbotron-narrow.css" rel="stylesheet">
    
    <script src="/static/js/jquery-3.1.1.js"></script>
    
  </head>

  <body>

    <div class="container">
      <div class="header">
        <nav>
          <ul class="nav nav-pills pull-right">
	    <li role="presentation" class="active"><a href="#">Add Item</a></li>
            <li role="presentation" ><a href="/logout">Logout</a></li>
          </ul>
        </nav>
        <img src="/static/images/Flask_Icon.png" alt="Flask_Icon.png"/ >
      </div>
     <section>
     <form class="form-horizontal" method="post" action="/addBlog">
<fieldset>

<!-- Form Name -->
<legend>Create Your Blog</legend>

<!-- Text input-->
<div class="form-group">
  <label class="col-md-4 control-label" for="txtTitle">Title</label>  
  <div class="col-md-4">
  <input id="txtTitle" name="inputTitle" type="text" placeholder="placeholder" class="form-control input-md">
  </div>
</div>

<!-- Textarea -->
<div class="form-group">
  <label class="col-md-4 control-label" for="txtPost">Post</label>
  <div class="col-md-4">                     
    <textarea class="form-control" id="txtPost" name="inputDescription" ></textarea>
  </div>
</div>

<!-- Button -->
<div class="form-group">
  <label class="col-md-4 control-label" for="singlebutton"></label>
  <div class="col-md-4">
    <input id="singlebutton" name="singlebutton" class="btn btn-primary" type="submit" value="Publish" />
  </div>
</div>

</fieldset>
</form>
      
</section>
      <footer class="footer">
        <p>©etaman.com 2017</p>
      </footer>

    </div>
  </body>
</html>

Now, we may want to add a new route and method to display the "Add Blog" page in app.py:

@app.route('/showAddBlog')
def showAddBlog():
    return render_template('addBlog.html')

We need to add a new menu item to link to the "Add Blog" page in userHome.html:

<nav>
  <ul class="nav nav-pills pull-right">
    <li role="presentation"><a href="/showAddBlog">Add Blog</a></li>
    <li role="presentation" class="active"><a href="/logout">Logout</a></li>
  </ul>
</nav>

When the user logged in successfully, the following page is presented:

UserHomeWithAddBlog.png

When the user click "Add Blog", the page below will show up:

AddingBlogCreateYourBlog.png



DB setup for adding blog

In order to add items to the blog list, we need to create a table called tbl_blog:

CREATE TABLE `tbl_blog` (
  `blog_id` int(11) NOT NULL AUTO_INCREMENT,
  `blog_title` varchar(45) DEFAULT NULL,
  `blog_description` varchar(5000) DEFAULT NULL,
  `blog_user_id` int(11) DEFAULT NULL,
  `blog_date` datetime DEFAULT NULL,
  PRIMARY KEY (`blog_id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=latin1;

Check our tables so far:

mysql> show tables;
+------------------------+
| Tables_in_FlaskBlogApp |
+------------------------+
| blog_user              |
| tbl_blog               |
+------------------------+
2 rows in set (0.00 sec)

mysql> describe tbl_blog;
+------------------+---------------+------+-----+---------+----------------+
| Field            | Type          | Null | Key | Default | Extra          |
+------------------+---------------+------+-----+---------+----------------+
| blog_id          | int(11)       | NO   | PRI | NULL    | auto_increment |
| blog_title       | varchar(45)   | YES  |     | NULL    |                |
| blog_description | varchar(5000) | YES  |     | NULL    |                |
| blog_user_id     | int(11)       | YES  |     | NULL    |                |
| blog_date        | datetime      | YES  |     | NULL    |                |
+------------------+---------------+------+-----+---------+----------------+
5 rows in set (0.02 sec)




Stored procedure for tbl_blog

Now we need to create a MySQL stored procedure to add items to the tbl_blog table:

USE `FlaskBlogApp`;
DROP procedure IF EXISTS `FlaskBlogApp`.`sp_addBlog`;
 
DELIMITER $$
USE `FlaskBlogApp`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_addBlog`(
    IN p_title varchar(45),
    IN p_description varchar(1000),
    IN p_user_id bigint
)
BEGIN
    insert into tbl_blog(
        blog_title,
        blog_description,
        blog_user_id,
        blog_date
    )
    values
    (
        p_title,
        p_description,
        p_user_id,
        NOW()
    );
END$$
 
DELIMITER ;




Calling the stored procedure for tbl_blog

Since we'll be posting data to the method called addBlog(), we have explicitly declared it in the defined route as shown below:

@app.route('/addBlog',methods=['POST'])
def addBlog():

When a call is made to the addBlog() method, we may want to validate it's an authenticity by checking if the session variable user exists:

if session.get('user'):

If it's a valid session, we'll read the posted 'title' and 'description':

if session.get('user'):
   _title = request.form['inputTitle']
   _description = request.form['inputDescription']
   _user = session.get('user')

Now that we have the required input values, we want to open a MySQL connection and call the stored procedure sp_addBlog:

conn = mysql.connect()
cursor = conn.cursor()
cursor.callproc('sp_addBlog',(_title,_description,_user))
data = cursor.fetchall()

Once the stored procedure is executed, we need to commit the changes to the database:

if len(data) is 0:
    conn.commit()
    return redirect('/userHome')
else:
    return render_template('error.html',error = 'An error occurred!')

Now we can add a blog post:

CreatingYourBlog.png

BlogAdded.png

Here are the output from the server console and we can see the process from the sign-in to post:

(venv1) k@laptop:~/MySites/etaman/FlaskApp/p3$ python app.py
 * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
"GET / HTTP/1.1" 200 -
"GET /showSignin HTTP/1.1" 200 -
"POST /validateLogin HTTP/1.1" 302 -
"GET /userHome HTTP/1.1" 200 -
"GET /showAddBlog HTTP/1.1" 200 -
"POST /addBlog HTTP/1.1" 302 -
"GET /userHome HTTP/1.1" 200 -


We can check if our blog is in the table:

mysql> select * from tbl_blog;
+---------+------------+-----------------------------+--------------+---------------------+
| blog_id | blog_title | blog_description            | blog_user_id | blog_date           |
+---------+------------+-----------------------------+--------------+---------------------+
|       3 | Spooky     | Spooky action at a distance |            1 | 2016-12-03 19:29:35 |
+---------+------------+-----------------------------+--------------+---------------------+
1 row in set (0.00 sec)




Displaying blog posts

We need to create a MySQL stored procedure to retrieve the blog created by a user. It will take the user ID as a parameter and return a data set of blogs created by the particular user ID:

USE `FlaskBlogApp`;
DROP procedure IF EXISTS `sp_GetBlogByUser`;
 
DELIMITER $$
USE `FlaskBlogApp`$$
CREATE PROCEDURE `sp_GetBlogByUser` (
IN p_user_id bigint
)
BEGIN
    select * from tbl_blog where blog_user_id = p_user_id;
END$$
 
DELIMITER ;

We can check the stored procedures created so far:

mysql> SHOW PROCEDURE STATUS WHERE db = 'FlaskBlogApp';
+--------------+------------------+-----------+----------------+---------------------+---------------------+---------------+---------+----------------------+----------------------+--------------------+
| Db           | Name             | Type      | Definer        | Modified            | Created             | Security_type | Comment | character_set_client | collation_connection | Database Collation |
+--------------+------------------+-----------+----------------+---------------------+---------------------+---------------+---------+----------------------+----------------------+--------------------+
| FlaskBlogApp | sp_addBlog       | PROCEDURE | root@localhost | 2016-12-03 17:00:03 | 2016-12-03 17:00:03 | DEFINER       |         | utf8                 | utf8_general_ci      | latin1_swedish_ci  |
| FlaskBlogApp | sp_createUser    | PROCEDURE | root@localhost | 2016-12-02 21:50:34 | 2016-12-02 21:50:34 | DEFINER       |         | utf8                 | utf8_general_ci      | latin1_swedish_ci  |
| FlaskBlogApp | sp_GetBlogByUser | PROCEDURE | root@localhost | 2016-12-03 19:58:11 | 2016-12-03 19:58:11 | DEFINER       |         | utf8                 | utf8_general_ci      | latin1_swedish_ci  |
| FlaskBlogApp | sp_validateLogin | PROCEDURE | root@localhost | 2016-12-03 11:09:38 | 2016-12-03 11:09:38 | DEFINER       |         | utf8                 | utf8_general_ci      | latin1_swedish_ci  |
+--------------+------------------+-----------+----------------+---------------------+---------------------+---------------+---------+----------------------+----------------------+--------------------+
4 rows in set (0.15 sec)




Creating a Method for Retrieving Data

Now we need to create a method which will call the sp_GetBlogByUser stored procedure to get the posts created by a user. Let's add a getBlog() method in app.py:

@app.route('/getBlog')
def getBlog():
    try:
        if session.get('user'):
            _user = session.get('user')

            con = mysql.connect()
            cursor = con.cursor()
            cursor.callproc('sp_GetBlogByUser',(_user,))
            blogs = cursor.fetchall()

            blogs_dict = []
            for blog in blogs:
                blog_dict = {
                        'Id': blog[0],
                        'Title': blog[1],
                        'Description': blog[2],
                        'Date': blog[4]}
                blogs_dict.append(blog_dict)

            return json.dumps(blogs_dict)
        else:
            return render_template('error.html', error = 'Unauthorized Access')
    except Exception as e:
	return render_template('error.html', error = str(e))

As we can see from the code, this method can only be called with valid user session:

@app.route('/getBlog')
def getBlog():
    try:
        if session.get('user'):
            ...
        else:
            ...
    except Exception as e:
        ...

If it is a valid user session, we create a connection to the MySQL database and call the stored procedure sp_GetBlogByUser:

if session.get('user'):
    _user = session.get('user')

    con = mysql.connect()
    cursor = con.cursor()
    cursor.callproc('sp_GetBlogByUser',(_user,))
    blogs = cursor.fetchall()

After fetching data from MySQL, we'll parse the data and convert it into a dictionary so that it's easy to return as JSON:

if session.get('user'):
    ...

    blogs_dict = []
    for blog in blogs:
        blog_dict = {
                'Id': blog[0],
                'Title': blog[1],
                'Description': blog[2],
                'Date': blog[4]}
        blogs_dict.append(blog_dict)

    return json.dumps(blogs_dict)

After converting the data into a dictionary we convert the data into JSON and return.





Binding JSON Data to HTML

Once the user's home page is loaded, we call the getBlog() method using jQuery AJAX and bind the received data into our HTML. Let's add the following jQuery AJAX script to userHome.html:

<script>
  $(function() {
    $.ajax({
        url: '/getBlog',
        type: 'GET',
        success: function(res) {
            console.log(res);
        },
        error: function(error) {
            console.log(error);
        }
    });
  });
</script>  

Let's restart the server:

(venv1) k@laptop:~/MySites/etaman/FlaskApp/p3$ python app.py
 * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)

Once logged in with a valid email address and password, check the browser console and we should have the blog list retrieved from the database as shown:


BlogConsoleOutput.png

Now, we may want to iterate over the JSON data and bind it into the HTML. We'll be using bootstrap list-group to display our wish list items. Here is the userHome.html:

<!DOCTYPE html>
<html lang="en">
  <head>
    <title>Python Flask Blog App</title>
   
    <link href="//getbootstrap.com/dist/css/bootstrap.min.css" rel="stylesheet">

    <link href="//getbootstrap.com/examples/jumbotron-narrow/jumbotron-narrow.css" rel="stylesheet">
    <link href="/static/css/signup.css" rel="stylesheet">
    <script src="/static/js/jquery-3.1.1.js"></script>
    <!--<script>
      $(function() {
        $.ajax({
            url: '/getBlog',
            type: 'GET',
            success: function(res) {
                console.log(res);
            },
            error: function(error) {
                console.log(error);
            }
        });
      });
    </script>  -->
    <script>
      $(function(){
        $.ajax({
          url : '/getBlog',
          type : 'GET',
          success: function(res){
            var div = $('<div>')
                .attr('class', 'list-group')
                .append($('<a>')
                .attr('class', 'list-group-item active')
                .append($('<h4>')
                .attr('class', 'list-group-item-heading'),
                $('<p>')
                .attr('class', 'list-group-item-text')));

            var blogObj = JSON.parse(res);
            var blog = '';
            
            $.each(blogObj,function(index, value){
              blog = $(div).clone();
              $(blog).find('h4').text(value.Title);
              $(blog).find('p').text(value.Description);
              $('.jumbotron').append(blog);
            });
          },
          error: function(error){
            console.log(error);
          }
        });
      });
    </script>
  </head>

  <body>

    <div class="container">
      <div class="header">
        <nav>
          <ul class="nav nav-pills pull-right">
            <li role="presentation"><a href="/showAddBlog">Add Blog</a></li>
            <li role="presentation" class="active"><a href="/logout">Logout</a></li>
          </ul>
        </nav>
        <img src="/static/images/Flask_Icon.png" alt="Flask_Icon.png"/ >
      </div>

      <div class="jumbotron">
        <h1>Welcome Home !!</h1>
       
      </div>      

      <footer class="footer">
        <p>©etaman.com 2017</p>
      </footer>

    </div>
  </body>
</html>

So, when a successful login, the user will have the following page that lists blog posts:

JSON-Blog-Output-Display.png








Ph.D. / Golden Gate Ave, San Francisco / Seoul National Univ / Carnegie Mellon / UC Berkeley / DevOps / Deep Learning / Visualization

YouTubeMy YouTube channel

Sponsor Open Source development activities and free contents for everyone.

Thank you.

- K Hong








Flask



Deploying Flask Hello World App with Apache WSGI on Ubuntu 14

Flask Micro blog "Admin App" with Postgresql

Flask "Blog App" with MongoDB - Part 1 (Local via Flask server)

Flask "Blog App" with MongoDB on Ubuntu 14 - Part 2 (Local Apache WSGI)

Flask "Blog App" with MongoDB on CentOS 7 - Part 3 (Production Apache WSGI )

Flask word count app 1 with PostgreSQL and Flask-SQLAlchemy

Flask word count app 2 via BeautifulSoup, and Natural Language Toolkit (NLTK) with Gunicorn/PM2/Apache

Flask word count app 3 with Redis task queue

Flask word count app 4 with AngularJS polling the back-end

Flask word count app 5 with AngularJS front-end updates and submit error handling

Flask word count app 0 - Errors and Fixes

Flask with Embedded Machine Learning I : Serializing with pickle and DB setup

Flask with Embedded Machine Learning II : Basic Flask App

Flask with Embedded Machine Learning III : Embedding Classifier

Flask with Embedded Machine Learning IV : Deploy

Flask with Embedded Machine Learning V : Updating the classifier

Flask AJAX with jQuery

Flask blog app with Dashboard 1 - SignUp page

Flask blog app with Dashboard 2 - Sign-In / Sign-Out

Flask blog app with Dashboard 3 - Adding blog post item

Flask blog app with Dashboard 4 - Update / Delete

Flask blog app with Dashboard 5 - Uploading an image

Flask blog app with Dashboard 6 - Dash board

Flask blog app with Dashboard 7 - Like button

Flask blog app with Dashboard 8 - Deploy

Flask blog app with Dashboard - Appendix (tables and mysql stored procedures/functions

Sponsor Open Source development activities and free contents for everyone.

Thank you.

- K Hong






Python tutorial



Python Home

Introduction

Running Python Programs (os, sys, import)

Modules and IDLE (Import, Reload, exec)

Object Types - Numbers, Strings, and None

Strings - Escape Sequence, Raw String, and Slicing

Strings - Methods

Formatting Strings - expressions and method calls

Files and os.path

Traversing directories recursively

Subprocess Module

Regular Expressions with Python

Regular Expressions Cheat Sheet

Object Types - Lists

Object Types - Dictionaries and Tuples

Functions def, *args, **kargs

Functions lambda

Built-in Functions

map, filter, and reduce

Decorators

List Comprehension

Sets (union/intersection) and itertools - Jaccard coefficient and shingling to check plagiarism

Hashing (Hash tables and hashlib)

Dictionary Comprehension with zip

The yield keyword

Generator Functions and Expressions

generator.send() method

Iterators

Classes and Instances (__init__, __call__, etc.)

if__name__ == '__main__'

argparse

Exceptions

@static method vs class method

Private attributes and private methods

bits, bytes, bitstring, and constBitStream

json.dump(s) and json.load(s)

Python Object Serialization - pickle and json

Python Object Serialization - yaml and json

Priority queue and heap queue data structure

Graph data structure

Dijkstra's shortest path algorithm

Prim's spanning tree algorithm

Closure

Functional programming in Python

Remote running a local file using ssh

SQLite 3 - A. Connecting to DB, create/drop table, and insert data into a table

SQLite 3 - B. Selecting, updating and deleting data

MongoDB with PyMongo I - Installing MongoDB ...

Python HTTP Web Services - urllib, httplib2

Web scraping with Selenium for checking domain availability

REST API : Http Requests for Humans with Flask

Blog app with Tornado

Multithreading ...

Python Network Programming I - Basic Server / Client : A Basics

Python Network Programming I - Basic Server / Client : B File Transfer

Python Network Programming II - Chat Server / Client

Python Network Programming III - Echo Server using socketserver network framework

Python Network Programming IV - Asynchronous Request Handling : ThreadingMixIn and ForkingMixIn

Python Coding Questions I

Python Coding Questions II

Python Coding Questions III

Python Coding Questions IV

Python Coding Questions V

Python Coding Questions VI

Python Coding Questions VII

Python Coding Questions VIII

Python Coding Questions IX

Python Coding Questions X

Image processing with Python image library Pillow

Python and C++ with SIP

PyDev with Eclipse

Matplotlib

Redis with Python

NumPy array basics A

NumPy Matrix and Linear Algebra

Pandas with NumPy and Matplotlib

Celluar Automata

Batch gradient descent algorithm

Longest Common Substring Algorithm

Python Unit Test - TDD using unittest.TestCase class

Simple tool - Google page ranking by keywords

Google App Hello World

Google App webapp2 and WSGI

Uploading Google App Hello World

Python 2 vs Python 3

virtualenv and virtualenvwrapper

Uploading a big file to AWS S3 using boto module

Scheduled stopping and starting an AWS instance

Cloudera CDH5 - Scheduled stopping and starting services

Removing Cloud Files - Rackspace API with curl and subprocess

Checking if a process is running/hanging and stop/run a scheduled task on Windows

Apache Spark 1.3 with PySpark (Spark Python API) Shell

Apache Spark 1.2 Streaming

bottle 0.12.7 - Fast and simple WSGI-micro framework for small web-applications ...

Flask app with Apache WSGI on Ubuntu14/CentOS7 ...

Selenium WebDriver

Fabric - streamlining the use of SSH for application deployment

Ansible Quick Preview - Setting up web servers with Nginx, configure enviroments, and deploy an App

Neural Networks with backpropagation for XOR using one hidden layer

NLP - NLTK (Natural Language Toolkit) ...

RabbitMQ(Message broker server) and Celery(Task queue) ...

OpenCV3 and Matplotlib ...

Simple tool - Concatenating slides using FFmpeg ...

iPython - Signal Processing with NumPy

iPython and Jupyter - Install Jupyter, iPython Notebook, drawing with Matplotlib, and publishing it to Github

iPython and Jupyter Notebook with Embedded D3.js

Downloading YouTube videos using youtube-dl embedded with Python

Machine Learning : scikit-learn ...

Django 1.6/1.8 Web Framework ...









Contact

BogoToBogo
contactus@bogotobogo.com

Follow Bogotobogo

About Us

contactus@bogotobogo.com

YouTubeMy YouTube channel
Pacific Ave, San Francisco, CA 94115

Pacific Ave, San Francisco, CA 94115

Copyright © 2024, bogotobogo
Design: Web Master