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 5 : Uploading an image

Python-Flask.png




Bookmark and Share





bogotobogo.com site search:



Note

In the previous part of this series, we implemented the feature of editing and deleting blog posts.

In this part of the series, we'll implement an option for the user to upload an image representing a blog post, an option to mark the post as accomplished, and an option to set privacy.

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

tree-p5.png

They are available from FlaskApp/p5







templates/addBlog.html

Let's start by modifying our "add blog" page to include an option to upload an image.

First, we'll modify the form-horizontal to a vertical form, so remove the class form-horizontal from the form.

We'll also add three new controls:

  1. a file upload control to upload photos
  2. a check box to mark the blog post as private
  3. another check box to mark the blog as completed.

Here is the modified templates/addBlog.html:

<!DOCTYPE html>
<html lang="en">
 
<head>
    <title>Python Flask Blog App</title>
 
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css">
 
    <link href="//getbootstrap.com/examples/jumbotron-narrow/jumbotron-narrow.css" rel="stylesheet">
 
    <script src="/static/js/jquery-3.1.1.js"></script>
    <style>
        .btn-file {
            position: relative;
            overflow: hidden;
        }
         
        .btn-file input[type=file] {
            position: absolute;
            top: 0;
            right: 0;
            min-width: 100%;
            min-height: 100%;
            font-size: 100px;
            text-align: right;
            filter: alpha(opacity=0);
            opacity: 0;
            outline: none;
            background: white;
            cursor: inherit;
            display: block;
        }
    </style>
 
</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>
 
        <form role="form" method="post" action="/addBlog">
 
            <!-- Form Name -->
            <legend>Create Your Blog Post</legend>
 
            <!-- Text input-->
            <div class="form-group">
                <label for="txtTitle">Title</label>
 
                <input id="txtTitle" name="inputTitle" type="text" placeholder="placeholder" class="form-control input-md">
 
            </div>
 
            <!-- Textarea -->
            <div class="form-group">
                <label for="txtPost">Description</label>
 
                <textarea class="form-control" id="txtPost" name="inputDescription"></textarea>
 
            </div>
 
            <div class="form-group">
                <label for="txtPost">Photos</label>
 
                <div class="input-group">
                    <span class="input-group-btn">
                    <span class="btn btn-primary btn-file">
                        Browse… <input type="file" id="fileupload" name="file" multiple>
                    </span>
                    </span>
                    <input type="text" class="form-control" readonly>
                </div>
 
            </div>
 
            <div class="form-group">
                <label>Mark this as private and not visible to others.</label>
                <br/>
                <input type="checkbox"> Mark as Private <span class="glyphicon glyphicon-lock" aria-hidden="true"></span>
            </div>
 
            <div class="form-group">
                <label>Have you already accomplished this?</label>
                <br/>
                <input type="checkbox"> Mark as Done <span class="glyphicon glyphicon-ok" aria-hidden="true"></span>
            </div>

            <!-- Button -->
            <div class="form-group">
 
                <p class="text-center">
                    <input id="singlebutton" name="singlebutton" class="btn btn-primary" type="submit" value="Publish" />
                </p>
            </div>
 
        </form>
 
        <footer class="footer">
            <p>©etaman.com 2017</p>
        </footer>
 
    </div>
</body>
 
</html>
AddBlogWithUpload.png



File upload via blueimp jQuery-File-Upload

We're going to use blueimp jQuery-File-Upload to upload a file. Download the required the files from GitHub. Extract the source and add the following script references to addBlog.html:

<script src="/static/js/jquery-3.1.1.js"></script>
<script src="/static/js/jquery.ui.widget.js"></script>
  
<script type="text/javascript" src="/static/js/jquery.fileupload.js"></script>
<script type="text/javascript" src="/static/js/jquery.fileupload-process.js"></script>
<script type="text/javascript" src="/static/js/jquery.fileupload-ui.js"></script>

On addBlog.html page load, add the plugin initiation code to the file upload button click.

$(function() {
    $('#fileupload').fileupload({
        url: 'upload',
        dataType: 'json',
        add: function(e, data) {
            data.submit();
        },
        success: function(response, status) {
            console.log(response);
        },
        error: function(error) {
            console.log(error);
        }
    });
})

We attached the file upload plugin to the #fileupload button. The file upload plugin posts the file to the /upload request handler, which we'll define in app.py:

@app.route('/upload', methods=['GET', 'POST'])
def upload():
    if request.method == 'POST':
        file = request.files['file']
        extension = os.path.splitext(file.filename)[1]
        f_name = str(uuid.uuid4()) + extension
        file.save(os.path.join(app.config['UPLOAD_FOLDER'], f_name))
    return json.dumps({'filename':f_name})

ImageFileUploadShow.png



Modifying tbl_blog

Now we may want to modify our tbl_blog table structure to include three new fields.

Let's alter the tbl_blog as shown below:

ALTER TABLE `FlaskBlogApp`.`tbl_blog` 
ADD COLUMN `blog_file_path` VARCHAR(200) NULL AFTER `blog_date`,
ADD COLUMN `blog_accomplished` INT NULL DEFAULT 0 AFTER `blog_file_path`,
ADD COLUMN `blog_private` INT NULL DEFAULT 0 AFTER `blog_accomplished`;

mysql> use FlaskBlogApp;
Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A

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

mysql> desc 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    |                |
| blog_file_path    | varchar(200)  | YES  |     | NULL    |                |
| blog_accomplished | int(11)       | YES  |     | 0       |                |
| blog_private      | int(11)       | YES  |     | 0       |                |
+-------------------+---------------+------+-----+---------+----------------+
8 rows in set (0.01 sec)

mysql> 




Updating stored procedures

Let's modify our stored procedures sp_addBlog and sp_updateBlog to include the newly added fields to the database.

Before we modify the , we may want to see the full list:

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-04 10:00:03 | 2016-12-04 10:00:03 | DEFINER       |         | utf8                 | utf8_general_ci      | latin1_swedish_ci  |
| FlaskBlogApp | sp_createUser    | PROCEDURE | root@localhost | 2016-12-03 14:50:34 | 2016-12-03 14:50:34 | DEFINER       |         | utf8                 | utf8_general_ci      | latin1_swedish_ci  |
| FlaskBlogApp | sp_deleteBlog    | PROCEDURE | root@localhost | 2016-12-05 16:28:27 | 2016-12-05 16:28:27 | DEFINER       |         | utf8                 | utf8_general_ci      | latin1_swedish_ci  |
| FlaskBlogApp | sp_GetBlogById   | PROCEDURE | root@localhost | 2016-12-05 06:45:30 | 2016-12-05 06:45:30 | DEFINER       |         | utf8                 | utf8_general_ci      | latin1_swedish_ci  |
| FlaskBlogApp | sp_GetBlogByUser | PROCEDURE | root@localhost | 2016-12-10 08:35:08 | 2016-12-10 08:35:08 | DEFINER       |         | utf8                 | utf8_general_ci      | latin1_swedish_ci  |
| FlaskBlogApp | sp_updateBlog    | PROCEDURE | root@localhost | 2016-12-05 08:58:41 | 2016-12-05 08:58:41 | DEFINER       |         | utf8                 | utf8_general_ci      | latin1_swedish_ci  |
| FlaskBlogApp | sp_validateLogin | PROCEDURE | root@localhost | 2016-12-04 04:09:38 | 2016-12-04 04:09:38 | DEFINER       |         | utf8                 | utf8_general_ci      | latin1_swedish_ci  |
+--------------+------------------+-----------+----------------+---------------------+---------------------+---------------+---------+----------------------+----------------------+--------------------+
8 rows in set (0.01 sec)

sp_addBlog:

USE `FlaskBlogApp`;
DROP procedure IF EXISTS `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,
    IN p_file_path varchar(200),
    IN p_is_private int,
    IN p_is_done int
)
BEGIN
    insert into tbl_blog(
        blog_title,
        blog_description,
        blog_user_id,
        blog_date,
        blog_file_path,
        blog_private,
        blog_accomplished
    )
    values
    (
        p_title,
        p_description,
        p_user_id,
        NOW(),
        p_file_path,
        p_is_private,
        p_is_done
    );
END$$
 
DELIMITER ;

sp_updateBlog:

USE `FlaskBlogApp`;
DROP procedure IF EXISTS `sp_updateBlog`;
 
DELIMITER $$
USE `FlaskBlogApp`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_updateBlog`(
IN p_title varchar(45),
IN p_description varchar(1000),
IN p_blog_id bigint,
In p_user_id bigint,
IN p_file_path varchar(200),
IN p_is_private int,
IN p_is_done int
)
BEGIN
update tbl_blog set
    blog_title = p_title,
    blog_description = p_description,
    blog_file_path = p_file_path,
    blog_private = p_is_private,
    blog_accomplished = p_is_done
    where blog_id = p_blog_id and blog_user_id = p_user_id;
END$$
 
DELIMITER ;




-
Modifying the /addBlog request handler's method

Next, modify the /addBlog request handler's method in app.py to read the newly posted fields and pass them to the stored procedure:

@app.route('/addBlog',methods=['POST'])
def addBlog():
    try:
        if session.get('user'):
            _title = request.form['inputTitle']
            _description = request.form['inputDescription']
            _user = session.get('user')

            if request.form.get('filePath') is None:
                _filePath = ''
            else:
                _filePath = request.form.get('filePath')
            if request.form.get('private') is None:
                _private = 0
            else:
                _private = 1
            if request.form.get('done') is None:
                _done = 0
            else:
                _done = 1            

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

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

        else:
            return render_template('error.html',error = 'Unauthorized Access')
    except Exception as e:
        return render_template('error.html',error = str(e))
    finally:
        cursor.close()
        conn.close()




templates/addBlog.html

In the addBlog.html page we'll need to set the name attribute for the elements to be posted. So add name to both the newly-added check boxes:

<div class="form-group">
    <label>Mark this as private and not visible to others.</label>
    <br/>
    <input type="checkbox"> Mark as Private <span class="glyphicon glyphicon-lock" aria-hidden="true"></span>
</div>

<div class="form-group">
    <label>Have you already accomplished this?</label>
    <br/>
    <input type="checkbox"> Mark as Done <span class="glyphicon glyphicon-ok" aria-hidden="true"></span>
</div>

Now we also need to pass the upload file path. So we'll create a hidden input field and set its value in the file upload success callback:

<div class="pull-right">
  <img id="imgUpload" style="width: 140px; height: 140px;" class="img-thumbnail"><input type="hidden" name="filePath" id="filePath"></input>
</div>

Set its value in the file upload success callback:

<script>
  $(function(){
        $('#fileupload').fileupload({
            url: 'upload',
            dataType: 'json',
            add: function (e, data) {
              data.submit();
            },
            success:function(response,status) {
              console.log(response.filename);
              var filePath = 'static/Uploads/' + response.filename;
              $('#imgUpload').attr('src',filePath);
              $('#filePath').val(filePath);
              console.log('success');
            },
            error:function(error){
                    console.log(error);
            }
        });
  })
</script>

Sign in using valid credentials and try to add a new blog with all the required details. Once added successfully, it should be listed on the user home page:

AddingItemBeforePublish.png
PublishedPostWithUploadedImage.png




Modify the Edit Blog Implementat

First, we need to add some HTML code for the three new fields. So open up userHome.html and add the following HTML code after the title and description HTML:

<div class="modal-body">
  <form role="form">
    <div class="form-group">
      <label for="recipient-name" class="control-label">Title:</label>
      <input type="text" class="form-control" id="editTitle">
    </div>
    <div class="form-group">
      <label for="message-text" class="control-label">Description:</label>
      <textarea class="form-control" id="editDescription"></textarea>
    </div>

    <div class="form-group">
      <label for="txtPost">Photos</label>
                     
      <div class="input-group">
        <span class="input-group-btn">
          <span class="btn btn-primary btn-file">
                Browse… <input type="file" id="fileupload" name="file" multiple>
          </span>
        </span>
        <div class="pull-right">
          <img id="imgUpload" style="width: 140px; height: 140px;" class="img-thumbnail"><input type="hidden" name="filePath" id="filePath"></input>
        </div>
      </div> 
    </div>

    <div class="form-group">
      <label>Mark this as private and not visible to others.</label><br/>
      <input id="chkPrivate" name="private" type="checkbox"> Mark as Private <span class="glyphicon glyphicon-lock" aria-hidden="true"></span>
    </div>

    <div class="form-group">
      <label>Have you already accomplished this?</label><br/>
      <input id="chkDone" name="done" type="checkbox"> Mark as Done <span class="glyphicon glyphicon-ok" aria-hidden="true"></span>
    </div>
 </form>
</div>

We'll need to fetch the required data to populate the above fields on edit. So let's modify the stored procedure sp_GetBlogById to include the additional fields as shown:

USE `FlaskBlogApp`;
DROP procedure IF EXISTS `sp_GetBlogById`;

DELIMITER $$
USE `FlaskBlogApp`$$

CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_GetBlogById`(
IN p_blog_id bigint,
In p_user_id bigint
)
BEGIN
select blog_id,blog_title,blog_description,blog_file_path,blog_private,blog_accomplished from tbl_blog where blog_id = p_blog_id and blog_user_id = p_user_id;
END$$
 
DELIMITER ;

Next, we'll need to modify the JSON string in the /getBlogById route method to include the new fields. Modify the blog list in /getBlogById as shown:

@app.route('/getBlogById',methods=['POST'])
def getBlogById():
    try:
        if session.get('user'):
            _id = request.form['id']
            _user = session.get('user')
 
            conn = mysql.connect()
            cursor = conn.cursor()
            cursor.callproc('sp_GetBlogById',(_id,_user))
            result = cursor.fetchall()

            blog = []
            #blog.append({'Id':result[0][0],'Title':result[0][1],'Description':result[0][2]})
            blog.append({'Id':result[0][0],'Title':result[0][1],'Description':result[0][2],'FilePath':result[0][3],'Private':result[0][4],'Done':result[0][5]})

            return json.dumps(blog)
        else:
            print "fail getBlogById()"
            return render_template('error.html', error = 'Unauthorized Access')
    except Exception as e:
        return render_template('error.html',error = str(e))

To render the result, we need to parse the data received in the success callback of the Edit JavaScript function in userHome.html:

function Edit(elm) {
  localStorage.setItem('editId',$(elm).attr('data-id'));
  $.ajax({
      url: '/getBlogById',
      data: {
          id: $(elm).attr('data-id')
      },
      type: 'POST',
      success: function(res) {
        var data = JSON.parse(res);
        console.log(data);
        $('#editTitle').val(data[0]['Title']);
        $('#editDescription').val(data[0]['Description']);
        $('#imgUpload').attr('src',data[0]['FilePath']);
        if(data[0]['Private']=="1"){
          $('#chkPrivate').attr('checked','checked');
        }
        if(data[0]['Done']=="1"){
          $('#chkDone').attr('checked','checked');
        }
        $('#editModal').modal();
      },
      error: function(error) {
          console.log(error);
      }
  });
}

After a successful signin, try to edit a wish from the wish list. We should have the data populated in the Edit popup:

EditUpdateWithImage.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