Explore o novo chatbot do Developer Center! O MongoDB AI chatbot pode ser acessado na parte superior da sua navegação para responder a todas as suas perguntas sobre o MongoDB .

Junte-se a nós no Amazon Web Services re:Invent 2024! Saiba como usar o MongoDB para casos de uso de AI .
Desenvolvedor do MongoDB
Central de desenvolvedor do MongoDBchevron-right
Produtoschevron-right
MongoDBchevron-right

How to Deploy a Flask Application With MongoDB on Fly.io

Karen Zhang5 min read • Published Dec 02, 2024 • Updated Dec 02, 2024
FlaskMongoDBPython
Ícone do FacebookÍcone do Twitterícone do linkedin
Avalie esse Tutorial
star-empty
star-empty
star-empty
star-empty
star-empty
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.

1. Set up the development environment

Before we dive into coding, let's set up our development environment:
  1. Install Python (if you haven't already).
  2. Create a new directory for your project:
    1mkdir flask-mongodb-fly
    2cd flask-mongodb-fly
  3. Create and activate a virtual environment:
    1python -m venv venv
    2source venv/bin/activate # On Windows, use `venv\Scripts\activate`
  4. Install the required packages:
    1pip install Flask pymongo gunicorn
    Installing required packages
  5. Create a requirements.txt file:
    1pip freeze > requirements.txt

2. Create a basic Flask application

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:
1import os
2from flask import Flask, request, jsonify
3from pymongo import MongoClient
4from bson import json_util
5import json
6
7app = Flask(__name__)
8
9# MongoDB Atlas connection string
10mongodb_uri = os.environ.get("MONGODB_URI", "mongodb://localhost:27017/geoapp")
11client = MongoClient(mongodb_uri)
12db = client.get_database()
13
14@app.route("/")
15def hello_world():
16 return "Hello, World\! This is a Flask & MongoDB app deployed on Fly.io"
17
18@app.route("/locations", methods=["POST"])
19def 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@app.route("/locations", methods=["GET"])
25def get_locations():
26 locations = list(db.locations.find())
27 return json.loads(json_util.dumps(locations))
28
29@app.route("/nearby", methods=["GET"])
30def 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
49if __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).

3. Integrate MongoDB with Flask

To use MongoDB with our Flask application, we need to set up a MongoDB Atlas account and create a cluster:
  1. Create a new cluster (choose the free tier for testing).
  2. In the Security tab, create a database user and whitelist your IP address.
  3. 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.
  4. 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.

4. Test the application locally

Before deploying, let's test our application locally:
  1. Set the MONGODB_URI environment variable:
    1export MONGODB_URI="your_mongodb_atlas_connection_string"
    Replace your_mongodb_atlas_connection_string with your actual connection string.
  2. Run the Flask application:
    1python app.py
  3. Test the endpoints using URL:
    1# Add a location
    2curl -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
    5curl http://localhost:8080/locations
    6
    7# Find nearby locations
    8curl "http://localhost:8080/nearby?lat=48.8584.lon=2.2945.distance=5000"

5. Deploy to Fly.io

Now, let's deploy our application to Fly.io:
  1. Install the Fly CLI:
    1curl -L https://fly.io/install.sh | sh
  2. Sign up and log in to Fly.io:
    1fly auth signup
    2fly auth login
  3. Set the MongoDB URI as a secret:
    1fly secrets set MONGODB_URI="your_mongodb_atlas_connection_string"
    Replace your_mongodb_atlas_connection_string with your actual connection string.
  4. Set up the configuration:
    1fly launch
    fly launch is a command that initializes your application on Fly.io by creating a fly.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
    6app = 'your-app-name’'
    7primary_region = 'sea'
    8
    9[build]
    10
    11[http_service]
    12internal_port = 8080
    13force_https = true
    14auto_stop_machines = 'stop'
    15auto_start_machines = true
    16min_machines_running = 0
    17processes = ['app']
    18
    19[[vm]]
    20memory = '1gb'
    21cpu_kind = 'shared'
    22cpus = 1
  5. Deploy your app:
    1fly 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.

6. Post-deployment steps

After deployment, let's verify that our application is working correctly:
  1. Open your app in a browser:
    1fly open
  2. Test the endpoints using cURL:
    1# Add a location
    2
    3curl -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
    2curl https:flask-mongodb-fly-wild-sky-7177.fly.dev/locations
    1# Find nearby locations
    2curl "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"}]
  3. Monitor your app's logs:
    1fly logs

7. Troubleshooting common deployment issues

If you encounter a 500 Internal Server Error or other issues:
  1. Check your app's logs:
    1fly logs
  2. Verify your MongoDB connection string:
    1fly secrets list
  3. If needed, update your secrets:
    1fly secrets set MONGODB_URI="your_updated_mongodb_uri"
  4. Redeploy your application:
    1fly deploy

Conclusão

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.
Iniciar a conversa

Ícone do FacebookÍcone do Twitterícone do linkedin
Avalie esse Tutorial
star-empty
star-empty
star-empty
star-empty
star-empty
Relacionado
Tutorial

Um guia para novatos sobre como integrar o MongoDB com o TensorFlow usando JavaScript


Sep 04, 2024 | 15 min read
Tutorial

Crie uma API RESTful com .NET Core e MongoDB


Sep 11, 2024 | 8 min read
Tutorial

Planejador de partes favoritas do operador Joe com Playwright, LlamaIndex e MongoDB Atlas Vector Search


Nov 12, 2024 | 11 min read
Tutorial

Usando o LINQ para consultar o MongoDB em um aplicativo .NET Core


Jun 10, 2024 | 6 min read
Sumário