How to Deploy a Flask Application With MongoDB on Fly.io
Avalie esse Tutorial
Nowadays, choosing the right database and deployment platform can make a significant difference in your application's performance and scalability. This tutorial will guide you through creating a Flask application that uses MongoDB Atlas and deploying it on Fly.io, a platform that makes deployment and scaling a breeze.
In this tutorial, we'll build a location-based discovery API using Flask and MongoDB Atlas. By combining Flask's simplicity with MongoDB's powerful geospatial features, we'll create a RESTful API that allows users to store, search, and discover locations. Whether you're building a travel app, a local business finder, or any location-aware service, this tutorial will show you how to leverage MongoDB's GIS capabilities for spatial queries, implement text search, and use aggregation pipelines for insights. We'll use MongoDB Atlas, a fully managed cloud database service, making it easy to deploy and scale our application, and Fly.io for hosting our Flask application in the cloud. All the code can be found on GitHub.
Before we dive into coding, let's set up our development environment:
- Install Python (if you haven't already).
- Create a new directory for your project:
1 mkdir flask-mongodb-fly 2 cd flask-mongodb-fly - Create and activate a virtual environment:
1 python -m venv venv 2 source venv/bin/activate # On Windows, use `venv\Scripts\activate` - Install the required packages:
1 pip install Flask pymongo gunicorn - Create a
requirements.txt
file:1 pip freeze > requirements.txt
Let's create a simple Flask application with routes for CRUD operations and a geospatial query. Create a file named
app.py
with the following content:1 import os 2 from flask import Flask, request, jsonify 3 from pymongo import MongoClient 4 from bson import json_util 5 import json 6 7 app = Flask(__name__) 8 9 # MongoDB Atlas connection string 10 mongodb_uri = os.environ.get("MONGODB_URI", "mongodb://localhost:27017/geoapp") 11 client = MongoClient(mongodb_uri) 12 db = client.get_database() 13 14 15 def hello_world(): 16 return "Hello, World\! This is a Flask & MongoDB app deployed on Fly.io" 17 18 19 def add_location(): 20 data = request.json 21 result = db.locations.insert_one(data) 22 return (jsonify({"message": "Location added successfully", "id": str(result.inserted_id)}), 201,) 23 24 25 def get_locations(): 26 locations = list(db.locations.find()) 27 return json.loads(json_util.dumps(locations)) 28 29 30 def find_nearby(): 31 lat = float(request.args.get("lat")) 32 lon = float(request.args.get("lon")) 33 max_distance = int(request.args.get("distance", 1000)) # Default to 1000 meters 34 35 nearby = db.locations.find({ 36 "location": { 37 "$near": { 38 "$geometry": { 39 "type": "Point", 40 "coordinates": [lon, lat] 41 }, 42 "$maxDistance": max_distance 43 } 44 } 45 }) 46 47 return json.loads(json_util.dumps(list(nearby))) 48 49 if __name__ == "__main__": 50 app.run(host="0.0.0.0", port=8080) # change to your ip address
This application includes:
- A home route ("/") that returns a simple greeting.
- A route to add new locations ("/locations" - POST).
- A route to retrieve all locations ("/locations" - GET).
- A route to find nearby locations based on coordinates and distance ("/nearby" - GET).
To use MongoDB with our Flask application, we need to set up a MongoDB Atlas account and create a cluster:
- Create a new cluster (choose the free tier for testing).
- In the Security tab, create a database user and whitelist your IP address.
- In the Clusters tab, click "Connect" and choose "Connect your application." You need to use the Python driver. Since we already installed PyMongo in Step 4 while setting up the development environment, we just need to add your connection string into the application code. Create an .env file in your project and add MONGODB_URI as an environment variable. Then, copy and paste the connection string.
- Replace
<password>
with your database user's password. This can be found in Security -> Database Access. The user should at least have read and write permission to the database.
Before deploying, let's test our application locally:
- Set the
MONGODB_URI
environment variable:1 export MONGODB_URI="your_mongodb_atlas_connection_string" Replaceyour_mongodb_atlas_connection_string
with your actual connection string. - Run the Flask application:
1 python app.py - Test the endpoints using URL:
1 Add a location 2 curl -X POST http://localhost:8080/locations -H "Content-Type: application/json" -d '{"name": "Eiffel Tower", "location": {"type": "Point", "coordinates": [2.2945, 48.8584.}}' 3 4 Get all locations 5 curl http://localhost:8080/locations 6 7 Find nearby locations 8 curl "http://localhost:8080/nearby?lat=48.8584.lon=2.2945.distance=5000"
Now, let's deploy our application to Fly.io:
- Install the Fly CLI:
1 curl -L https://fly.io/install.sh | sh - Sign up and log in to Fly.io:
1 fly auth signup 2 fly auth login - Set the MongoDB URI as a secret:
1 fly secrets set MONGODB_URI="your_mongodb_atlas_connection_string" Replaceyour_mongodb_atlas_connection_string
with your actual connection string. - Set up the configuration:
1 fly launch fly launch
is a command that initializes your application on Fly.io by creating afly.toml
configuration file and setting up the necessary infrastructure.The file.toml file will look something like this:1 # fly.toml app configuration file generated for flask-mongodb-fly-late-dew-6702 on 2024-11-18T15:45:10-07:00 2 # 3 # See https://fly.io/docs/reference/configuration/ for information about how to use this file. 4 # 5 6 app = 'your-app-name’' 7 primary_region = 'sea' 8 9 [build] 10 11 [http_service] 12 internal_port = 8080 13 force_https = true 14 auto_stop_machines = 'stop' 15 auto_start_machines = true 16 min_machines_running = 0 17 processes = ['app'] 18 19 [[vm]] 20 memory = '1gb' 21 cpu_kind = 'shared' 22 cpus = 1 - Deploy your app:
1 fly deploy After the app is successfully deployed, you can see it on Fly.io with the details:If we go to the URL, this is the “Hello, World!” app that we just deployed.
After deployment, let's verify that our application is working correctly:
- Open your app in a browser:
1 fly open - Test the endpoints using cURL:
1 Add a location 2 3 curl -X POST https://flask-mongodb-fly-wild-sky-7177.fly.dev/locations -H 'Content-Type: application/json' -d '{"name": "Central Park", "location": {"type": "Point", "coordinates": [-73.965355, 40.782865.}, "description": "Famous park in Manhattan"}' 1 Get all locations 2 curl https:flask-mongodb-fly-wild-sky-7177.fly.dev/locations 1 Find nearby locations 2 curl "https://flask-mongodb-fly-wild-sky-7177.fly.dev/nearby?lat=40.782865.lon=-73.965355.distance=1000" It shows the Manhattan park that we just POST:[{"_id":{"$oid":"6727b03c8fb4fcebcf186af9"},"description":"Famous park in Manhattan","location":{"coordinates":[-73.965355,40.782865.,"type":"Point"},"name":"Central Park"}]
- Monitor your app's logs:
1 fly logs
If you encounter a 500 Internal Server Error or other issues:
- Check your app's logs:
1 fly logs - Verify your MongoDB connection string:
1 fly secrets list - If needed, update your secrets:
1 fly secrets set MONGODB_URI="your_updated_mongodb_uri" - Redeploy your application:
1 fly deploy
Through this tutorial, we've built a robust, location-based API that demonstrates the power of MongoDB Atlas's geospatial features combined with Flask's web framework capabilities. We've implemented spatial queries for finding nearby locations, text search for discovering places, and aggregation pipelines for generating insights. The application showcases real-world GIS features that can be used for location tracking.
By deploying on Fly.io and using MongoDB Atlas, we've created a scalable solution that can serve as a foundation for various location-based services. Whether you're building a travel application, a local business directory, or any location-aware service, you can extend this foundation by adding authentication, more complex queries, or additional features specific to your use case.
For questions, comments, or to see what other developers are building using MongoDB, join us in the MongoDB Developer Community.
Principais comentários nos fóruns
Ainda não há comentários sobre este artigo.