analitics

Pages

Saturday, August 3, 2019

Python 3.7.3 : Using the flask - part 007.

This will be a long tutorial because will try to link some information's from the last tutorials.
First, the structure of the project can see into my GitHub project.
I create new templates and another python script named tserv.py for testing.
You can see easier how the POST method works and how to deal with a python database issue.
This script comes with an upload file feature and upload database with sqlite3 python module.
First, for upload a file we need the HTML5 file from templates folder named upload.html.
I update the base.html file to use the bootstrap framework.
import sqlite3
class UploadForm(FlaskForm):
    file = FileField()
    submit = SubmitField("submit")
    
@app.route('/upload',methods = ['GET','POST'])
def upload():
    form = UploadForm()
    
    if request.method == "POST" and form.validate():
        if form.validate_on_submit():
            file_name = form.file.data
            file_database(name = file_name.filename,data = file_name.read())
            print("File {}".format(file_name.filename))
            return render_template("upload.html", form = form)
    return render_template("upload.html", form = form)
def file_database(name,data):
    con=sqlite3.connect("file_upload.db")
    cursor = con.cursor()
    cursor.execute("""CREATE TABLE IF NOT EXISTS my_table (name TEXT, data BLOP) """)
    cursor.execute("""INSERT INTO my_table (name , data ) VALUES (?,?) """, (name, data))
    con.commit()
    cursor.close()
    con.close()
Let's run it:
python tserv.py
Into the main folder a database will be create and will fill with the file uploaded.
Now, if you want to add more we can create a download button into our UploadForm, is no need to have another python class.
First create your form tag into upload.html file and link with the python tserv.py code show bellow:
from flask import send_file
from io import BytesIO
...
@app.route('/download', methods=['GET','POST'])
def download():
    form = UploadForm()
    if request.method == "POST":
        con = sqlite3.connect("file_upload.db")
        cursor = con.cursor()
        cur_ex = cursor.execute(""" SELECT * FROM my_table """)
        for i in cur_ex.fetchall():
            name=i[0]
            data=i[1]
            break
        con.commit()
        cursor.close()
        con.close()
        return send_file(BytesIO(data), attachment_filename='test', as_attachment=True)
    return render_template("home.html", form = form)
When you run it the download button will download the first file upload into database.
This example tutorial can be more complex.
For example, you can show the database content into a new HTML file and then save with an open dialog to disk.