wt (2)

Download as pdf or txt
Download as pdf or txt
You are on page 1of 8

Express js Https methods

Express.js, is a web application framework for Node.js, HTTP methods play a


crucial role in defining the behavior of your routes and handling different types of
requests
1.GET: This method is used to request data from a specified resource. In
Express, you can define a route using app.get() method, which specifies the
route path and a callback function that will be executed when that route is
accessed via a GET request.
app.get('/users', function(req, res) {
// Handle GET request for '/users'});
2.POST: POST requests are used to submit data to be processed to a specified
resource. You can define a POST route using app.post() method,
app.post('/users', function(req, res) {
// Handle POST request for '/users'});
3.PUT: PUT requests are used to update data to a specified resource. In
Express, you can define a PUT route using app.put() method.
app.put('/users/:id', function(req, res) {
// Handle PUT request for '/users/:id'});
4.DELETE: DELETE requests are used to delete data from a specified resource.
You can define a DELETE route using app.delete() method.
app.delete('/users/:id', function(req, res) {
// Handle DELETE request for '/users/:id'});

url binding" could refer to the process of binding or associating a route URL with
a specific handler function. This process allows you to define how your
application responds to various HTTP requests sent to specific URLs.
1.Defining Routes: You use Express's methods like app.get(), app.post(), etc., to
define what happens when certain URLs are accessed with specific HTTP
methods.
const express = require('express');
const app = express();
app.get('/hello', function(req, res) {
res.send('Hello, World!');});
app.post('/submit', function(req, res) {
res.send('Form submitted successfully!');});
app.listen(3000, function() {
console.log('Server is listening on port 3000');});
-Accessing http://localhost:3000/hello will respond with "Hello, World!".
-Sending a POST request to http://localhost:3000/submit will respond with "Form
submitted successfully!".
2.Dynamic Parts of URLs: You can also have dynamic parts in URLs, like
/users/:id, where :id represents a variable. Express will then capture whatever
value is there and make it available in req.params.
app.get('/users/:id', function(req, res) {
const userId = req.params.id;
res.send(`User ID: ${userId}`);});
-Accessing http://localhost:3000/users/123 will respond with "User ID: 123".

Data types in MongoDB


1. String: A string is a sequence of UTF-8 characters. It is the most common data
type used for storing textual data.
2. Integer: An integer represents a whole number with no decimal places. It can
be either 32-bit or 64-bit, depending on the platform.
3. Double: A double represents a floating-point number with decimal places. It is
stored as a 64-bit floating-point number.
4. Boolean: A boolean value can be either true or false.
5. Date: A date represents a specific point in time. It is stored as the number of
milliseconds since the Unix epoch (January 1, 1970, UTC).
6. ObjectID: An ObjectID is a 12-byte unique identifier for a document. It is
automatically generated by MongoDB when a document is inserted.
7. Array: An array is an ordered list of values. It can contain any data type,
including other arrays and documents.
8. Embedded Document: An embedded document is a document that is nested
inside another document. It can contain any data type, including other arrays
and documents.
9. Binary Data: Binary data can be used to store non-textual data, such as
images or audio files.
10. Regular Expression: A regular expression is a pattern used to match text
strings.
11. Null: Null represents a missing or undefined valu
Routing(Expressjs)
1.Setting Up Express:
First, you need to set up an Express application by importing the Express module
and creating an instance of the Express application.
const express = require('express');
const app = express();
2.Defining Routes:
Routes in Express are defined using HTTP methods (GET, POST, PUT, DELETE,
etc.) on the Express application instance (app). Each route specifies a URL
pattern and a handler function that gets executed when the route is matched.
app.get('/', function(req, res) {
res.send('Welcome to the homepage!');});
app.post('/submit', function(req, res) {
res.send('Form submitted successfully!');});
3.Route Parameters:
Express allows you to define dynamic parts in route URLs using parameters.
These parameters are specified by prefixing them with a colon (:). The parameter
values can then be accessed in the request object (req.params).
// Example route with a dynamic parameter
app.get('/users/:userId', function(req, res) {
const userId = req.params.userId;
res.send(`User ID: ${userId}`);});
4.Sending Responses:
Inside route handler functions, you use methods of the response (res) object to
send responses back to the client. This could include sending HTML, JSON, or
other types of data.
app.get('/about', function(req, res) {
res.send('<h1>About Us</h1><p>This is the about page.</p>');});
5.Listening for Requests:
After defining all the routes, you need to start the Express server and listen for
incoming requests on a specific port.
const PORT = 3000;
app.listen(PORT, function() {
console.log(`Server listening on port ${PORT}`);});
Flask (http methods,Sessions and cookies)
from flask import Flask, render_template, request, redirect, url_for, session
app = Flask(__name__)
app.secret_key = 'your_secret_key' # Set a secret key for session encryption
# Dummy user data (in real-world scenarios, this would be stored securely)
users = {
'john': 'password1',
'jane': 'password2'}
@app.route('/', methods=['GET', 'POST'])
def login():
if request.method == 'POST':
username = request.form['username']
password = request.form['password']
if username in users and users[username] == password:
# Successful login, store user session
session['username'] = username
return redirect(url_for('protected'))
else:
# Failed login, render login page with error message
return render_template('login.html', error='Invalid username or password')
# For GET requests, simply render the login page
return render_template('login.html', error=None)
@app.route('/protected')
def protected():
# Protected page, only accessible after successful login
if 'username' in session:
return f"Welcome to the protected page, {session['username']}!"
else: return redirect(url_for('login'))
@app.route('/logout')
def logout():
# Logout: clear session
session.pop('username', None)
return redirect(url_for('login'))
if __name__ == '__main__':
app.run(debug=True)
1. Flask HTTP Methods:
The Flask application defines a single route / using the @app.route('/') decorator,
which accepts both GET and POST requests. This is specified by passing
methods=['GET', 'POST'] to the decorator.
-GET Request Handling: When a GET request is made to the root URL (/), the
login() function is called. Inside this function, it renders the login.html template.
-POST Request Handling: When a POST request is made to the root URL (/), the
login() function is also called. Inside this function, it retrieves the username and
password from the form data submitted by the user. If the provided credentials
match one of the dummy users in the users dictionary, the username is stored in
the session using session['username'] = username. Then, it redirects the user to
the /protected route. If the credentials are invalid, it renders the login.html
template again with an error message.
2. Sessions in Flask:
-Secret Key: app.secret_key = 'your_secret_key' sets a secret key for session
encryption. This is necessary for securely storing session data.
-Session Storage: Upon successful login, the user's username is stored in the
session using session['username'] = username.
-Session Access: In the /protected route, it checks if the 'username' key exists in
the session. If it does, it means the user is logged in, and it greets the user with a
personalized message. If not, it redirects the user back to the login page.
-Session Clearing: The /logout route is provided to handle user logout. It removes
the 'username' key from the session using session.pop('username', None).
3. Cookies in Flask:
Flask uses cookies for session management. When a user logs in, a session
cookie is sent to the client's browser, which contains a session identifier. This
identifier is used to associate subsequent requests from the same client with the
correct session data stored on the server.
-Secret Key: As mentioned earlier, the secret key is used for encrypting session
data, including the session identifier stored in the cookie.
-Session Management: The session object handles the creation and
management of session cookies transparently. Developers interact with the
session object to store and retrieve session data without directly dealing with
cookies.
Features of MongoDB
1.Schema-less Database: MongoDB allows collections to hold documents of
varying structure, providing flexibility in data representation without requiring a
predefined schema.
2.Document Oriented: Data in MongoDB is stored in flexible, JSON-like
documents rather than rigid tables, enabling easy storage and retrieval of
complex data structures.
3.Indexing: MongoDB automatically indexes every field in documents, making
data retrieval faster and more efficient. This indexing capability enhances query
performance, especially when dealing with large datasets.
4.Scalability: MongoDB offers horizontal scalability through sharding, enabling
distribution of data across multiple servers. This allows for seamless expansion
of database capacity as data volume grows.
5.Replication: MongoDB supports replication, creating redundant copies of data
across multiple servers to ensure high availability and fault tolerance. If one
server fails, data can be retrieved from another replica.
6.Aggregation: MongoDB provides powerful aggregation features, allowing users
to perform complex operations on grouped data and compute results efficiently.
Aggregation pipelines, map-reduce functions, and single-purpose aggregation
methods facilitate data analysis and manipulation.
7.High Performance: The combination of these features, including scalability,
indexing, replication, and aggregation, contributes to MongoDB's high
performance and data persistence compared to other databases. This makes
MongoDB a preferred choice for applications requiring fast and efficient data
storage and retrieval.

Create Database: use mydatabase


Example: Use Users
Drop Database : use mydatabase
db.dropDatabase()
Create Collection : db.createCollection(“collectionName”)
Drop Collection : use mydatabase
db.mycollection.drop()
Mongodb Aggregation
db.students.insertMany([
{ "sid": "S001", "sname": "John Doe", "age": 20, "address": "Vizag" }])
1.$matchIn MongoDB's aggregation framework, the $match stage is used to filter
documents by specific criteria.
db.collection.aggregate([
{ $match: { field: value } }])
2.$project: This is the projection operator, which specifies the fields to include or
exclude.
db.students.aggregate ( [
{ $project: { _id: 0, sname: 1, address: 1 } }] );
3.$group:Counting the Number of Students:
db.students.aggregate([
{ $group: { _id: null, count: { $sum: 1 } } }]);
4.$limit: Limit the result to 5 documents:
db.students.aggregate( [
{ $limit: 5 }] );
5..$sort: Sort students by age in descending order:
db.students.aggregate([
{ $sort: { age: -1 } }]);
6.$lookup : to perform a join between the "students" collection and the "courses"
collection
db.students.aggregate([ {
$lookup: {
from: "courses",
localField: "sid",
foreignField: "student_id",
as: "courses_taken" } }]);
Create (C):To create new documents in a collection, you use the insertOne() or
insertMany() methods.
db.collection.insertOne({ name: "John", age: 30, email: "[email protected]" });
Read (R):To read data from a collection, you use the find() method.
db.collection.find({ age: { $gte: 25 } });
Update (U):To update existing documents in a collection, you use the
updateOne() or updateMany() methods.
db.collection.updateOne({ name: "John" }, { $set: { age: 35 } });
Delete (D):To delete documents from a collection, you use the deleteOne() or
deleteMany() methods.
db.collection.deleteOne({ name: "John" });
You can also use the deleteMany() method to delete multiple documents
matching a criteria.

Data Modelling
1.Understand app needs: Know what data types, relationships, and usage
patterns are required.
2.Identify entities: Pinpoint objects and their relationships, like one-to-one or
many-to-many.
3.Embed or reference: Choose between embedding related data or referencingit.
4.Denormalization: Duplicate data across documents to optimize reads,
balancing with update concerns.
5.Schema design: Define document structure for consistency and performance
benefits.
6.Indexing: Create indexes on frequently queried fields to speed up reads.
7.Data access patterns: Design the model to align with common queries for
optimal performance.
8.Sharding and scaling: Plan for data distribution across servers or clusters for
scalability.
9.Performance and storage: Analyze data volume and growth to ensure efficient
storage and retrieval.
10.Data migration and evolution: Anticipate future changes and plan for schema
updates and migrations.

You might also like