Create a simple Python web page
Create a simple Python web page
operations with MongoDB, you can use the Flask web framework combined with PyMongo
(which is a Python library to work with MongoDB). Below is an example of how to
implement this.
Prerequisites
Before you begin, make sure you have:
If you're using MongoDB Atlas, create a cluster and get the connection string
(you'll use this later).
app = Flask(__name__)
# MongoDB connection setup (replace this with your MongoDB URI if using MongoDB
Atlas)
client = MongoClient('mongodb://localhost:27017/') # Local MongoDB
db = client['crud_db']
collection = db['items']
@app.route('/')
def index():
items = collection.find() # Retrieve all items from the collection
return render_template('index.html', items=items)
return redirect(url_for('index'))
return render_template('add.html')
@app.route('/edit/<item_id>', methods=['GET', 'POST'])
def edit_item(item_id):
item = collection.find_one({'_id': ObjectId(item_id)})
if request.method == 'POST':
name = request.form['name']
description = request.form['description']
return redirect(url_for('index'))
@app.route('/delete/<item_id>', methods=['POST'])
def delete_item(item_id):
collection.delete_one({'_id': ObjectId(item_id)})
return redirect(url_for('index'))
if __name__ == '__main__':
app.run(debug=True)
Step 3: HTML Templates
You need to create the corresponding HTML templates for the pages. These will be
stored in a folder named templates.
1. index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>MongoDB CRUD Operations</title>
</head>
<body>
<h1>Items</h1>
<a href="{{ url_for('add_item') }}">Add Item</a>
<table border="1">
<thead>
<tr>
<th>Name</th>
<th>Description</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
{% for item in items %}
<tr>
<td>{{ item['name'] }}</td>
<td>{{ item['description'] }}</td>
<td>
<a href="{{ url_for('edit_item',
item_id=item['_id']) }}">Edit</a>
<form action="{{ url_for('delete_item',
item_id=item['_id']) }}" method="post" style="display:inline;">
<button type="submit">Delete</button>
</form>
</td>
</tr>
{% endfor %}
</tbody>
</table>
</body>
</html>
2. add.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Add Item</title>
</head>
<body>
<h1>Add Item</h1>
<form action="{{ url_for('add_item') }}" method="POST">
<label for="name">Name:</label>
<input type="text" name="name" required><br><br>
<label for="description">Description:</label>
<textarea name="description" required></textarea><br><br>
<button type="submit">Add Item</button>
</form>
<br>
<a href="{{ url_for('index') }}">Back to List</a>
</body>
</html>
3. edit.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Edit Item</title>
</head>
<body>
<h1>Edit Item</h1>
<form action="{{ url_for('edit_item', item_id=item['_id']) }}" method="POST">
<label for="name">Name:</label>
<input type="text" name="name" value="{{ item['name'] }}" required><br><br>
<label for="description">Description:</label>
<textarea name="description" required>{{ item['description']
}}</textarea><br><br>
<button type="submit">Update Item</button>
</form>
<br>
<a href="{{ url_for('index') }}">Back to List</a>
</body>
</html>
Step 4: Running the Application
Save the Python code in a file called app.py.
Create the templates folder in the same directory as your Python file and place the
HTML files inside it.
Run the application with:
python app.py
By default, Flask runs on http://127.0.0.1:5000/. Open your browser and navigate to
this URL to see the app in action.
Key Points:
MongoDB Operations: We're using PyMongo to perform CRUD operations on the MongoDB
database.
Flask: The Flask app has routes for adding, editing, and deleting items in the
database.
Templates: HTML templates for each of the pages (index, add, edit) to display the
data and interact with it.
This example is a basic starting point. You can enhance it by adding features such
as validation, error handling, and more complex data relationships.
You said:
give steps to create mongodb db and tables
ChatGPT said:
To work with MongoDB in your Python project, you'll need to create a database and
collections (MongoDB equivalent of tables). MongoDB is a NoSQL database, meaning it
doesn't have tables in the traditional sense like SQL databases do, but it has
collections of documents.
Here's how you can create a database and collections in MongoDB, both using the
MongoDB shell and Python with PyMongo.
1. Setting up MongoDB
Step 1: Install MongoDB
If you haven't installed MongoDB yet, follow these instructions:
Windows: Download from MongoDB Downloads and follow the installation guide.
macOS: Use Homebrew: brew tap mongodb/brew and then brew install mongodb-
[email protected].
Linux: Use the official MongoDB instructions for your distro (e.g., Ubuntu,
CentOS).
Once installed, make sure MongoDB is running:
mongo
You'll enter the MongoDB interactive shell, where you can run commands to create a
database, collections, and manipulate documents.
db.items.insertOne({
"name": "Sample Item",
"description": "This is a sample item description."
})
Now MongoDB has created the crud_db database and the items collection, with one
document inside it.
show databases
This will list all the databases on the MongoDB server. The crud_db database should
appear now.
show collections
This will list all collections in the currently selected database (crud_db). You
should see the items collection.
By using PyMongo in Python, you can easily integrate MongoDB into your Python
applications and perform CRUD operations programmatically.
ChatGPT ca