Importing and Downloading Recordsdata in Flask

0
4


This text will go over how you can add and obtain recordsdata utilizing a Flask database utilizing Python. Principally, now we have a bit for importing recordsdata the place we will add recordsdata that can mechanically save in our database. After we add a file and submit it, a message stating that your file has been uploaded and displaying the file title on the display seems. After we view our Flask SQLite database, we will see that our file has been mechanically saved within the database. We will additionally obtain our recordsdata by utilizing the /obtain /id quantity utilizing the hyperlink. Consequently, we will comprehend every part of this technique on this put up.

Importing and Downloading Recordsdata in Flask

For our add and return recordsdata with the database in a Flask, first, we create a templates folder for making select file and submit button in HTML file type so let’s get began. To add and obtain recordsdata with the database in Flask, first we have to obtain SQLite DB browser to avoid wasting our information in SQLite.

File construction

Uploading and Downloading Files in Flask

 

Templates File

Within the templates file, we are going to create just one HTML file which can function our all frontend half code.

index.html

Within the index.html file, we make the primary heading utilizing h1 for displaying precisely what we’re doing and after that, we write one type through which we declare the strategy POST motion by utilizing URL ‘/’ and after that, we initialize information sort by utilizing Enctype and we take the multipart/form-data on this so our all file will safely save in database and after that, we write code for easy enter button and in addition submit button for displaying all these functionalities clearly we’re utilizing some CSS in model tag for making our frontend half stunning

HTML

<!DOCTYPE html>

<html lang="en">

<head>

    <meta charset="UTF-8">

    <meta http-equiv="X-UA-Suitable" content material="IE=edge">

    <meta title="viewport" content material="width=device-width, initial-scale=1.0">

    <title>File Add Instance</title>

    <model>

      .okay{

            

           font-size: 20px;

      }

      .op{

        font-size: 20px;

        margin-left: -70px;

        font-weight: daring;

        background-color: yellow;

        border-radius: 5px;

        cursor: pointer;

      }

         

      

    </model>

</head>

<physique>

    <div class="middle">

        <h1> Importing and Returning Recordsdata With a Database in Flask  </h1>

        <type technique="POST" motion="/" enctype="multipart/form-data">

            <enter class="okay" sort="file" title="file">

            <button class="op">Submit</button>

        </type>

    </div>

      

</physique>

</html>

Output:

Uploading and Downloading Files in Flask

Html Output

app.py

After writing code for templates we create an app.py file outdoors of the templates folder and create app,.py through which we are going to write our essential code of importing and returning recordsdata with a database in a Flask in Python language.

Step 1: Import all libraries 

Within the app.py file we are going to write our essential a part of the code via these all operations will function simply first in app.py we have to import all vital libraries that are vital for doing add and returning recordsdata with database operations first we import io BytesIO this module will convert our all pdf recordsdata binary in under you’ll be able to see what sort of output will present within the database after we add any pdf within the database and we  import render_template for rendering templates and after that, we’re importing send_file module which can assist us to ship the file to database and after that, we’re importing flask_sqlchemy for our SQL information 

Python

from io import BytesIO

from flask import Flask, render_template, request, send_file

from flask_sqlalchemy import SQLAlchemy

Step 2:  Create a database 

After importing all libraries we create an SQL database for importing and returning our file we initialize the Flask operate and after that, we make a database sqlite:///db.sqlite3 to avoid wasting our importing recordsdata and we create one DB as SQLAchemy saving database

Python3

app = Flask(__name__)

app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False

db = SQLAlchemy(app)

Step 3: Create a desk for the database

after creating the database we have to make a desk database for which we create one ID which we make the first key after making the id we crate the filename and within the filename we initialize a varchar restrict of fifty and after that, we create one information which is a blob which suggests we will see ou file by click on on the blob and for making all these functionalities we write following traces of code in our app.py file 

Python3

class Add(db.Mannequin):

    id = db.Column(db.Integer, primary_key=True)

    filename = db.Column(db.String(50))

    information = db.Column(db.LargeBinary)

Step 4: Create an index operate

We create one index operate through which we set the primary path ‘/’ and after that, we cross the request for technique performance in technique performance we create one var add through which we initialize the filename and browse the file if we add a pdf so it’ll learn it in binary type after scripting this we create DB session in our database and in addition we commit our DB session after creating and after that we return file title with flashing therapeutic massage uploaded ‘ filename’ and we return our render template on index,.html file 

Python3

@app.route('/', strategies=['GET', 'POST'])

def index():

    if request.technique == 'POST':

        file = request.recordsdata['file']

        add = Add(filename=file.filename, information=file.learn())

        db.session.add(add)

        db.session.commit()

        return f'Uploaded: {file.filename}'

    return render_template('index.html')

After writing the code we have to create db.sqlite in our system to create a database we have to run the next command within the terminal:

python
from app import app, db
app.app_context().push()
db.create_all()
exit()
Uploading and Downloading Files in Flask

 

by operating the above command within the terminal we will create a database through which our file will save after importing and submitting the database and we will see our database within the occasion folder mechanically created for operating how you can run these instructions watch a video which is hooked up under.

Step 5: Create a obtain operate for downloading the file.

After importing our file we have to make a obtain operate for obtain our importing file  for obtain file we make one add variable through which we add an add question and we filter our recordsdata by id as we set each id distinctive so each file has a singular id and after that, we return our file by utilizing send_file and in addition for obtain pdf file we convert it into binary to our information file by utilizing BytesIO module and after we will obtain our file by utilizing the next hyperlink 

http://127.0.0.1:5000/obtain/id_number 

Python

@app.route('/obtain/<upload_id>')

def obtain(upload_id):

    add = Add.question.filter_by(id=upload_id).first()

    return send_file(BytesIO(add.information), download_name=add.filename, as_attachment=True )

Full Code

Python3

from io import BytesIO

from flask import Flask, render_template, request, send_file

from flask_sqlalchemy import SQLAlchemy

  

app = Flask(__name__)

app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False

db = SQLAlchemy(app)

  

class Add(db.Mannequin):

    id = db.Column(db.Integer, primary_key=True)

    filename = db.Column(db.String(50))

    information = db.Column(db.LargeBinary)

  

@app.route('/', strategies=['GET', 'POST'])

def index():

    if request.technique == 'POST':

        file = request.recordsdata['file']

        add = Add(filename=file.filename, information=file.learn())

        db.session.add(add)

        db.session.commit()

        return f'Uploaded: {file.filename}'

    return render_template('index.html')

  

@app.route('/obtain/<upload_id>')

def obtain(upload_id):

    add = Add.question.filter_by(id=upload_id).first()

    return send_file(BytesIO(add.information), 

                     download_name=add.filename, as_attachment=True)

To run the above code we have to run the next command within the terminal:

flask run

Output:

After operating these instructions within the terminal after we add recordsdata like pdf and pictures so following output will present within the database after we blob SQLite database.

Picture add

After we add photos so following picture sort interface will show on the display after we blob our database.

Uploading and Downloading Files in Flask

Database for picture 

Pdf add

After we add any pdf file so database converts our pdf file into the binary type so the next sort of interface will present after we add any pdf file within the database and the blob.

Uploading and Downloading Files in Flask

Database of pdf file in binary type 

Output Video:

LEAVE A REPLY

Please enter your comment!
Please enter your name here