How to upload a file in Cloudant Nosql DB using python-flask?

In this article I am going to explain how to upload a file in Cloudant Nosql DB using python-flask. Furthermore, I am also going to explain how to delete, download and list the files in the Nosql database. If you already know how to store file in bluemix storage using python, then this might be a bit easier. If not, you can read the article here.

First of all, you install cloudant package for your python

pip install cloudant

Now you are ready to get into action.

Carry on upto step 3 described here, if you don’t have a bluemix account. If you have already created an account, you can procees from step 5.

add_service

Select Cloudant after that.

On the left side panel select ‘Environment Variables’. These are credentials associated with your Cloudant Nosql DB, which your bound python application will utilize to connect. You will need username, password and url.

Using Python-Flask

First of all we import the packages

from flask import Flask, request, make_response
from cloudant import Cloudant

Set the value of username, password and url now. These are taken from the environmental variable described above.

USERNAME = "#username"
PASSWORD = "#password"
URL = "#url"

Now it’s time to make the connection to the account.

client = Cloudant(USERNAME, PASSWORD, url=URL)
# Connect to the account
client.connect()

Now connect to the database
my_database = client[‘#databasename’]

In this example I have I am putting ‘index.html’ in ‘static’ folder in the same directory as the main python file resides. My index file source code looks like this. I am going to reference my python code based on this.

<body>
 <div class="container">
   <h1>Here you can upload a file</h1>
   <form id="upload_form" action="/upload" method="POST" enctype="multipart/form-data">
      <input type="file" name="file" accept="uploaded_files/*" multiple>
      <input type="submit" name="upload" value="Upload">
   </form>
   <hr>
   <h1>Here you can download a file</h1>
   <form id="download_form" action="/download" method="POST">
     File Name: <input type="text" name="filename" placeholder="Enter file name"><br><br>
     <input type="submit" name="download" value="download">
   </form>
   <hr>
   <h1>Here you can delete a file</h1>
   <form id="delete_form" action="/delete" method="POST">
     File Name: <input type="text" name="filename" placeholder="Enter file name"><br><br>
     <input type="submit" name="delete" value="delete">
   </form>
   <hr>
   <h1>Here you can List all the files</h1>
   <form id="list_form" action="/list_files" method="POST">
     <input type="submit" name="list" value="list">
   </form>
   <hr>
  </div>
 </body>

Now lets get into flask

app = Flask(__name__)

APP_ROOT = os.path.dirname(os.path.abspath(__file__))

@app.route('/')
def index():
	return app.send_static_file('index.html')
if __name__ == "__main__":
	app.run(debug=True)
#################################
#We will put our main codes inside here
######	###################
# Disconnect from the account
client.disconnect()

For uploading a file, we establish a route

@app.route('/upload', methods=['POST'])
def upload():

Lets receive the file uploaded from upload form of index.html

file = request.files['file']
file_name = file.filename

It is time to encode the file to upload

from base64 import b64encode
uploaded_file_content = b64encode(file.read())

Now we have to create data to put into a document in Nosql

for document in my_database:
data = {'file_name': file_name, '_attachments': {file_name : {'data': uploaded_file_content}}}

Lets create the document and the file will be uploaded.

doc = my_database.create_document(data)

The file is uploaded to your document. You can give id to your document by just putting “‘_Id’ = #id” as a parameter in data

If you want to know how to download and delete those attachments(file), then click here.

All the Best

Leave a Reply

1 Comment on "How to upload a file in Cloudant Nosql DB using python-flask?"

avatar
jose luis
Guest

hello

i am working with flask on bluemix but actually i had a problem when i want to save an image,

so i think the problem is the url because i did not to save the image on bluemix. the project works fine in my localhost in my computer.

so please can you help me ?

wpDiscuz