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
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!
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
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 :
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
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.