0% found this document useful (0 votes)
3 views

Create a simple Python web page

Uploaded by

prashanth_17883
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

Create a simple Python web page

Uploaded by

prashanth_17883
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 6

o create a simple Python web page that performs CRUD (Create, Read, Update, Delete)

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:

Python 3.x installed.


MongoDB installed and running on your local machine or a cloud service like MongoDB
Atlas.
The required Python packages:
Flask: for the web framework.
PyMongo: to interact with MongoDB.
You can install the required packages using pip:

pip install Flask pymongo


Step 1: Setting up MongoDB
First, make sure MongoDB is running. If you're using MongoDB locally, ensure the
MongoDB server is started (mongod).

If you're using MongoDB Atlas, create a cluster and get the connection string
(you'll use this later).

Step 2: Creating the Flask App


Here's a simple Flask application with CRUD operations.

from flask import Flask, render_template, request, redirect, url_for


from pymongo import MongoClient
from bson.objectid import ObjectId

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)

@app.route('/add', methods=['GET', 'POST'])


def add_item():
if request.method == 'POST':
name = request.form['name']
description = request.form['description']

# Insert the item into the MongoDB collection


collection.insert_one({
'name': name,
'description': description
})

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']

# Update the item in MongoDB


collection.update_one(
{'_id': ObjectId(item_id)},
{'$set': {'name': name, 'description': description}}
)

return redirect(url_for('index'))

return render_template('edit.html', item=item)

@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:

Windows: Start MongoDB as a service using net start MongoDB.


macOS/Linux: Run mongod to start the MongoDB server.
By default, MongoDB runs on localhost:27017.

Step 2: Access MongoDB Shell


Open a terminal and enter the MongoDB shell by typing:

mongo
You'll enter the MongoDB interactive shell, where you can run commands to create a
database, collections, and manipulate documents.

2. Create MongoDB Database and Collections


In MongoDB, you don't explicitly "create" a database or collection. They are
created automatically when you insert data.

Example: Create a Database and Collection


Switch to a database: If the database doesn't exist, MongoDB will create it once
you insert data. You can switch to a database with the use command:

use crud_db # Switches to a database named "crud_db"


Create a Collection: Collections are automatically created when you insert
documents. If you want to explicitly create a collection (though it’s not
necessary), you can use:

db.createCollection("items") # Creates a collection named "items"


However, if you skip this step and simply insert data, MongoDB will automatically
create the collection for you.

Insert a document (This will create the collection automatically):

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.

3. Viewing the Database and Collections


After you have inserted some data, you can view the databases and collections:

Show all databases:

show databases
This will list all the databases on the MongoDB server. The crud_db database should
appear now.

Show collections in the current database:

show collections
This will list all collections in the currently selected database (crud_db). You
should see the items collection.

View data in the collection:

db.items.find().pretty() # View all documents in the "items" collection


This will return the document(s) inside the items collection.

4. Creating MongoDB Database and Collections Using Python (PyMongo)


To interact with MongoDB using Python, you will need the pymongo library.

Step 1: Install PyMongo


If you haven't installed it yet, you can do so using pip:

pip install pymongo


Step 2: Connect to MongoDB
Here's a Python script to connect to MongoDB, create a database, and insert data
into a collection.

from pymongo import MongoClient

# Connect to MongoDB (assuming it's running locally)


client = MongoClient('mongodb://localhost:27017/')

# Create a new database named "crud_db"


db = client['crud_db']

# Create a new collection named "items"


collection = db['items']

# Insert a document into the collection


item = {
"name": "Sample Item",
"description": "This is a sample item description."
}
collection.insert_one(item)

print("Database and Collection Created and Data Inserted")


Step 3: Verify the Data
You can verify that the document has been inserted using a MongoDB shell query or
from your Python script:

# Retrieve all items in the collection


items = collection.find()

for item in items:


print(item)
This script will connect to the crud_db database and the items collection, insert a
document, and then print all documents in the collection.

5. Understanding MongoDB Database and Collections


Databases: MongoDB databases are containers for collections. You can have multiple
databases in MongoDB.
Collections: Collections are equivalent to tables in relational databases, but they
don't require a fixed schema. Collections can hold documents with different
structures.
Documents: Each document in a collection is a set of key-value pairs (JSON-like
objects). Documents are flexible, meaning fields can vary across documents.
Example Workflow:
Create database (implicitly by inserting a document).
Create collections (implicitly by inserting a document into them).
Insert documents into collections.
Query documents using the MongoDB shell or PyMongo.
Recap: Basic MongoDB Commands
Switch Database: use <db_name>
Show Databases: show databases
Show Collections: show collections
Create Collection: db.createCollection('<collection_name>')
Insert Document: db.<collection_name>.insertOne({key: value})
View Documents: db.<collection_name>.find().pretty()
Conclusion
MongoDB allows you to work with flexible and scalable data models. You don't need
to explicitly define a schema, and the database and collections are automatically
created when you insert data. However, you can also create them explicitly if
needed.

By using PyMongo in Python, you can easily integrate MongoDB into your Python
applications and perform CRUD operations programmatically.

ChatGPT ca

You might also like