Flask blog app tutorial 5 : Uploading an image – 2020

Flask blog app tutorial 5 : Uploading an image

Python-Flask.png

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 namesYou can turn off this feature to get a quicker startup with -ADatabase changedmysql> 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)BEGINupdate 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)BEGINselect 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

Please enable JavaScript to view the comments powered by Disqus.

Xổ số miền Bắc