Flask Blueprint : Image and File Upload API - Tutorial

in #utopian-io7 years ago (edited)

Why Blueprints?

Flask uses what they call as Blueprints to maintain a large and scalable application. It is used for making omponents and supporting common patterns within an application or across applications

maxresdefault.jpg

Writing APIs with Flask Blueprint

This blog post will cover how to write simple Blueprints using Flask. We will create endpoints for creating Image and File Upload.

So let's get started!

Basic Blueprint in Flask

Create a file called indexRoute.py

from flask import Blueprint, jsonify
router = Blueprint('routerName', __name__)

@router.route('/myroute', methods=['GET'])
def indexRoute():
    message = 'this is the index route'
    return jsonify({'message': message})

Now create the server.py file

from flask import Flask
from indexRoute import router

app = Flask(__name__)
app.add_resource('indexRoute', router, url_prefix='/api')

if __name__ == '__main__':
    app.run(debug=True)

Now you can simply access that route using http://locahost:5000/api/myroute

Creating routes for Image Upload

Let us suppose that the image will be send using the FileReader Javascript API.
Hence the Image will be received as a base64 string that will be decrypted and stored.

So, lets get into the route. Create a separate file called imageUpload.py

from flask import Blueprint, request, jsonify

router = Blueprint('imageUpload', __name__)

@router.route('/image', methods=['POST'])
def uploadImage():
    image = request.json['data']
    extension = request.json['extension']
    imageName = saveToImage(imageFile=image, extension=extension)
    return jsonify({'image': imageName})

The function saveToImage is implemented as following

import uuid
import os

def saveToImage(imageFile=None, extension='.png'):
    imageName = str(uuid.uuid4()) + extension
    imageDirectory = os.path.join(app.config.get('BASE_URL'), 'static', 'upload', 'image')
    imagePath = os.path.join(imageDirectory, imageName)
    image = open(imagePath, "wb")
    image.write(imaegFile.decode('base64'))
    image.close()

    return imageName

Here is a Youtube Video showing the usecase of the API :

Creating route for file upload

Let us assume that the file will be sent as a file object using frontend with an identifier key called file

Route for File upload

@router.route('/file', methods=['POST'])
def fileUpload():
    file = request.files['file']
    csvName = saveToCSV(csvFile=file, extension='.csv')
    return jsonify({'filename': csvName})

The function definition for the saveToCSV function is given below

def saveToCSV(csvFile=None, extension='.csv'):
    csvName = str(uuid.uuid4()) + extension
    csvDirectory = os.path.join(app.config.get('BASE_URL'), 'static', 'uploads', 'csv')
    csvPath = os.path.join(csvDirectory, csvName)
    csvFile.save(csvPath)

    return csvName

Congratulations Now you have your very own Flask Blueprint router for Image and File Upload.
All you need to do is define them inside your server.py just like

app.add_resource('fileUpload', fileUpload.router, url_prefix='/api')
app.add_resource('imageUpload', imageUpload.router, url_prefix='/api')

And now you're good to go

My Contributions

I've been contributing to FOSSASIA for a long time now. This Blog / tutorial is based upon my recent PRs in there project Badgeyay.
The Pull Request Associated with it are #697, #716 and #722
Follow me on github@gabru-md
Follow me on twitter@gabru_md

If you like this blog please comment down there. Thank you for reading this blog.

Sort:  

Thanks for the contribution!

In the future please make sure to follow (or at least make it similar to) the provided development template as there was some confusion as to whether your contribution was supposed to be a tutorial, a development contribution or a blog post.

I was also wondering if there is a reason you are using camel case when programming in Python?

Click here to see how your contribution was evaluated.


Need help? Write a ticket on https://support.utopian.io/.
Chat with us on Discord.
[utopian-moderator]

Hey @gabrum
Thanks for contributing on Utopian.
We’re already looking forward to your next contribution!

Contributing on Utopian
Learn how to contribute on our website or by watching this tutorial on Youtube.

Want to chat? Join us on Discord https://discord.gg/h52nFrV.

Vote for Utopian Witness!

Coin Marketplace

STEEM 0.26
TRX 0.20
JST 0.038
BTC 96689.25
ETH 3594.86
USDT 1.00
SBD 3.92