To extend your Flask application to store form results in a MongoDB database, you'll need to perform a few steps:
1. **Install MongoDB Driver**: You'll need to install `pymongo`, the MongoDB driver for Python. You can install it using pip:
```
pip install pymongo
```
2. **Database Setup**: Assuming your MongoDB server is already running on `localhost` with the default port `27017`, you can create a seed program to set up your database and collection.
Here's a simple seed program that creates a database named `calculatorDB` and a collection named `calculations`:
```python
from pymongo import MongoClient
def seed_database():
client = MongoClient('localhost', 27017) # Connect to MongoDB server
db = client.calculatorDB # Create a database named 'calculatorDB'
db.calculations.drop() # Drop the collection if it already exists
db.create_collection('calculations') # Create a new collection named 'calculations'
print("Database and collection created successfully.")
if __name__ == '__main__':
seed_database()
```
Run this script once to initialize your database and collection.
3. Integrate MongoDB with Flask App
Modify your Flask application to insert calculation results into the MongoDB database.
Here's an updated version of your `app.py` to include MongoDB integration:
```python
from flask import Flask, request, render_template
from pymongo import MongoClient
import datetime
app = Flask(__name__)
client = MongoClient('localhost', 27017)
db = client.calculatorDB
@app.route('/', methods=['GET', 'POST'])
def index():
if request.method == 'POST':
try:
value1 = float(request.form['value1'])
value2 = float(request.form['value2'])
operator = request.form['operator']
result = calculate(value1, value2, operator)
# Insert the calculation into MongoDB
db.calculations.insert_one({
'value1': value1,
'value2': value2,
'operator': operator,
'result': result,
'timestamp': datetime.datetime.now()
})
except ValueError:
result = "Invalid input"
except Exception as e:
result = str(e)
return render_template('index.html', result=result)
return render_template('index.html')
# Rest of your Flask app...
if __name__ == '__main__':
app.run(debug=True)
```
In this version, every time a calculation is performed and submitted via your form, the details along with the result are stored in the `calculations` collection of your `calculatorDB` database in MongoDB.
Ensure that MongoDB is running on your host, and the MongoDB Python driver is installed in your environment. Also, handle the MongoDB connection appropriately, closing it when not needed, especially in a production environment. This example keeps it simple for educational purposes.