You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何与mLab进行数据读写?解决Heroku上Flask计分板数据丢失问题

Hey there! Let's get your Flask app connected to mLab so you don't lose those scoreboard updates anymore. Here's a step-by-step breakdown to make it work:

Step 1: Set Up Your mLab Database
  • Head to your mLab dashboard and create a new MongoDB database (the free sandbox tier works great for small-scale projects like a scoreboard).
  • Create a dedicated database user (be sure to save the username and password—you’ll need these later).
  • Copy the MongoDB connection string from mLab’s interface; it’ll look something like this:
    mongodb://<dbuser>:<dbpassword>@dsxxxxxx.mlab.com:xxxxx/<dbname>
    
Step 2: Install Required Packages
  • Add these dependencies to your requirements.txt file (so Heroku automatically installs them during deployment):
    flask
    flask-pymongo
    
  • For local testing, install them via pip:
    pip install flask flask-pymongo
    
Step 3: Configure Your Flask App to Connect to mLab

We’ll use environment variables to keep your database credentials secure (never hardcode passwords in your Git repo!). Here’s how to set up the connection in your Flask app (e.g., app.py):

import os
from flask import Flask, jsonify, request
from flask_pymongo import PyMongo

app = Flask(__name__)

# Pull the connection string from an environment variable (best practice)
app.config["MONGO_URI"] = os.environ.get("MLAB_MONGO_URI")

# For local testing only (don't commit this line to Git!)
# app.config["MONGO_URI"] = "mongodb://your-username:your-password@dsxxxxxx.mlab.com:xxxxx/your-db-name"

mongo = PyMongo(app)

To set the environment variable on Heroku, run this command in your terminal:

heroku config:set MLAB_MONGO_URI="your-full-mlab-connection-string"
Step 4: Implement Read/Write Operations for the Scoreboard

Let’s create endpoints to update and fetch scores. We’ll use a scoreboard collection in your mLab database to store player data.

Update or Add a Player’s Score

@app.route('/update-score', methods=['POST'])
def update_score():
    data = request.get_json()
    player_name = data.get('player_name')
    new_score = data.get('score')

    # Update the player's score, or insert a new entry if they don't exist
    mongo.db.scoreboard.update_one(
        {'player_name': player_name},
        {'$set': {'score': new_score}},
        upsert=True
    )
    return jsonify({"message": "Score updated successfully!"})

Fetch the Entire Scoreboard

@app.route('/get-scores', methods=['GET'])
def get_scores():
    # Fetch all entries and exclude MongoDB's default _id field from the response
    scores = list(mongo.db.scoreboard.find({}, {'_id': 0}))
    return jsonify({"scoreboard": scores})
Step 5: Test and Deploy
  • Test your endpoints locally first to confirm reads and writes work with mLab.
  • Push your updated code to Heroku, and your scoreboard data will now persist in mLab instead of Heroku’s ephemeral filesystem—no more lost updates!

内容的提问来源于stack exchange,提问作者Quinten C

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 08:20:23