To use Docker to run a Flask app, you will need to create a Dockerfile that specifies how to build your container. Here's an example Dockerfile:
FROM python:3.9-alpine
WORKDIR /Corider-PyMongo
COPY requirements.txt requirements.txt
RUN pip install -r requirements.txt
COPY . .
EXPOSE 3000
CMD [ "python", "app.py" ]
This Dockerfile specifies the environment for building and running a Python Flask app with PyMongo. Here are the steps it follows:
- It starts from a base image of Python 3.9 running on Alpine Linux, which is a lightweight distribution of Linux.
- It sets the working directory inside the container to
/Corider-PyMongo
. - It copies the
requirements.txt
file to the container. - It installs the required Python packages from the
requirements.txt
file using pip. - It copies the rest of the files in the current directory to the container.
- It exposes port 3000 to allow connections to the Flask app.
- It sets the default command to run the Flask app using the command
python app.py
.
So, this Dockerfile creates a container that installs the required Python packages and runs a Flask app with PyMongo on port 3000.
docker build -t myflaskapp .
docker run -p 3000:3000 myflaskapp
since we exposed port 3000 we need to map our port to docker’s 3000 port.
This is a Flask application that provides an API to perform CRUD operations on a MongoDB database.
from flask import Flask, request,jsonify
from flask_restful import Api, Resource, reqparse
from flask_pymongo import PyMongo
from bson.objectid import ObjectId
app = Flask(__name__)
app.config['MONGO_URI'] =" "# Update this with your own MongoDB URI
mongo = PyMongo(app)
db = mongo.db
api = Api(app)
class home(Resource):
def get(self):
return {'message':'hello world'}
class Create(Resource):
def post(self):
data = request.get_json()
result = db.users.insert_one(data)
return {'id': str(result.inserted_id)}
import logging
logging.basicConfig(level=logging.DEBUG)
class Read(Resource):
def get(self):
users = db.users.find()
output = []
for user in users:
output.append({'id': str(user['_id']), 'name': user['name'], 'email': user['email'], 'password': user['password']})
return jsonify({'result': output})
class Read_id(Resource):
def get(self, id):
print(id)
result = db.users.find_one({'_id': ObjectId(id)})
print(result)
if result:
result['_id'] = str(result['_id'])
return result
else:
return {'error': 'Not found'}, 404
class Update(Resource):
def put(self, id):
data = request.get_json()
data = request.get_json()
result = db.users.update_one({'_id': ObjectId(id)}, {'$set': data})
if result.modified_count == 1:
return {'message': 'Updated successfully'}
else:
return {'error': 'Not found'}, 404
class Delete(Resource):
def delete(self, id):
result = db.users.delete_one({'_id': ObjectId(id)})
if result.deleted_count == 1:
return {'message': 'Deleted successfully'}
else:
return {'error': 'Not found'}, 404
- The
home
class defines a simple/
endpoint that returns a hello world message. - The
Create
class defines a/create
endpoint that accepts a JSON payload via a POST request and inserts the data into the MongoDBusers
collection. The newly inserted document's ID is returned in the response. - The
Read
class defines a/read
endpoint that retrieves all the documents in theusers
collection and returns them in a JSON format. - The
Read_id
class defines a/read-id/<string:id>
endpoint that accepts a document ID as a parameter and retrieves the corresponding document from theusers
collection. If the document is found, it is returned in a JSON format; otherwise, an error message is returned. - The
Update
class defines an/update/<string:id>
endpoint that accepts a document ID as a parameter and a JSON payload via a PUT request. The payload contains the updated fields for the corresponding document, which are updated in theusers
collection. If the update is successful, a success message is returned; otherwise, an error message is returned. - The
Delete
class defines a/delete/<string:id>
endpoint that accepts a document ID as a parameter and deletes the corresponding document from theusers
collection. If the delete is successful, a success message is returned; otherwise, an error message is returned.
api.add_resource(home, '/')
api.add_resource(Create, '/create')
api.add_resource(Read, '/read')
api.add_resource(Read_id, '/read-id/<string:id>')
api.add_resource(Update, '/update/<string:id>')
api.add_resource(Delete, '/delete/<string:id>')
The api.add_resource()
statements register each endpoint with the Flask app.
if __name__ == '__main__':
app.run(debug=True,host='0.0.0.0', port=3000)
Testing:
I have made use of postman to test out all the API endpoints and was sucessfully able to Create,Read,Update and Delete from the MongoDB database I created using MongoDB Atlas.
- Open Postman and create a new request of type GET.
- Enter the URL for the endpoint you want to test, e.g.
[http://](http://127.0.0.1:3000/)127.0.0.1:3000/read
. - Send the request and check the response in the "Body" tab. It should return a JSON object containing all the users present in the database if the request was successful.
- Open Postman and create a new request
[http://](http://127.0.0.1:3000/)127.0.0.1:3000/read-id/644bc21958e221462949dd7d
. - Set the HTTP method to GET.
- Click on the Send button to send the request.
- Postman will display the response from the server in the Response section, which should contain the user details if the user is found, or a message saying "User not found" if the user is not found.
- Open Postman and create a new request of type PUT.
- Enter the URL for the endpoint you want to test, e.g.
http://127.0.0.1:3000/update/<string:id>
where<id>
is the ID of the user you want to update. - In the request body, select the "raw" format and choose "JSON" from the dropdown menu.
- Enter the JSON object containing the updated user data, e.g.
{"name": "John", "email": "john@example.com", "password": "newpassword"}
. - Send the request and check the response in the "Body" tab. It should return a JSON object containing a "result" key with the message "User updated successfully" if the update was successful, or "User not found" if the user with the given ID does not exist in the database.
-
Open Postman and create a new request.
-
Set the request method to POST and enter the URL of your API endpoint, which should be
http://127.0.0.1:3000/create
. -
Select the "Body" tab and choose "raw" as the input format. Set the content type to "JSON (application/json)".
-
In the request body, enter the user data in JSON format. For example:
{ "name": "John Smith", "email": "john.smith@example.com", "password": "password123" }
-
Click the "Send" button to send the request to your API endpoint.
-
The response will be displayed in the "Body" tab of the response panel. It should contain a JSON object with a "result" field that says "User added successfully".
To evaluate the delete_user
method in Postman, follow these steps:
- Open Postman and create a new request.
- Set the request method to "DELETE".
- Enter the URL
http://127.0.0.1:3000/delete/<string:id>
, whereid
is the ID of the user you want to delete. - Click the "Send" button to send the request.
- Check the response to see if the user was deleted successfully. The response will be in JSON format and will contain a message indicating whether the user was deleted or not.