0% found this document useful (0 votes)
29 views13 pages

Server-Side Scripting

Uploaded by

Vikas Sharma
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
29 views13 pages

Server-Side Scripting

Uploaded by

Vikas Sharma
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 13

SERVER-SIDE SCRIPTING

Vikas Chandra Sharma, Swarrnim School of Computing & IT, Swarrnim Startup and
Innovation University

CHAPTER-1

Introduction to Server-Side Scripting Languages


1. Server-side Scripting Overview
- Server-side scripting is a technique used in web development where scripts run on a web
server to generate dynamic web content.
- These scripts interact with databases, process user input, and perform various server-side
tasks.
- Server-side scripting is crucial for creating interactive and data-driven web applications.

2. Different Server-Side Scripting Languages


- There are several server-side scripting languages, including:
- PHP: A widely used language known for its simplicity and integration with various
databases.
- Python: Known for its readability and versatility in web development.
- Ruby: Used in the Ruby on Rails (RoR) framework for rapid development.
- Node.js (JavaScript): Empowers developers to use JavaScript for server-side scripting.

Example: PHP is often used for tasks like processing forms and managing user
authentication.

3. Web Services
- Web services enable communication between different software applications over the
internet using standard protocols like HTTP.
- They are essential for building distributed and interconnected web systems.

4. Web Application Frameworks - MVC


- MVC (Model-View-Controller) is a design pattern used in web application development.
- It separates the application into three components: Model (data), View (presentation), and
Controller (logic).
- Frameworks like Django and Ruby on Rails (RoR) follow the MVC pattern to streamline
web application development.

5. General Purpose Frameworks - Django and RoR


- Django: A Python web framework that emphasizes rapid development, security, and
scalability.
- Ruby on Rails (RoR): A Ruby framework known for its convention-over-configuration
(CoC) and don't-repeat-yourself (DRY) principles.

Example: Django is used to build web applications like content management systems (e.g.,
Django CMS) and e-commerce platforms.

6. Discussion Forums, Wikis, Weblogs, Content Management Systems (CMS)


- Server-side scripting languages are commonly used to create various web applications:
- Discussion Forums: Platforms where users can engage in discussions, e.g., Reddit.
- Wikis: Collaborative websites where users can create and edit content, e.g., Wikipedia.
- Weblogs (Blogs): Personal or professional websites for publishing articles or posts.
- Content Management Systems (CMS): Tools for creating and managing websites
efficiently, e.g., WordPress.
CHAPTER-2
Introduction to Python
1. Setting up the Environment
- Python can be installed on various operating systems. You can set up the environment by
downloading Python from the official website (python.org) or using package managers like
Anaconda or pip.

2. Lexical Conventions and Syntax


- Python uses indentation to define code blocks.
- Example:

if x > 5:
print("x is greater than 5")

3. Variables and Data Types


- Variables are used to store data. Python supports various data types, including int, float,
str, bool, and more.
- Example:

name = "John"
age = 30
is_student = False

4. Operators
- Python supports operators for arithmetic, comparison, logical operations, and more.
- Example:

result = 10 + 5
is_equal = (x == y)

5. Statements and Expressions


- Statements are complete lines of code, while expressions are parts of code that produce
values.
- Example:

Statement
print("Hello, World!")

Expression
total = x + y

6. Decision Making
- Python uses if, elif, and else statements for decision-making.
- Example:

if age < 18:


print("You are a minor.")
else:
print("You are an adult.")
7. Loops
- Python supports for and while loops for iterating over sequences or executing code
repeatedly.
- Example:

for i in range(5):
print(i)

8. Data Structures
- Python provides various data structures like strings, tuples, lists, and dictionaries for
organizing and manipulating data.
- Example:

fruits = ['apple', 'banana', 'cherry']


person = {'name': 'John', 'age': 30}

9. Recursion
- Recursion is a programming technique where a function calls itself to solve a problem.
- Example:

def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n-1)

10. Date and Time


- Python's `datetime` Chapter allows working with dates and times.
- Example:

from datetime import datetime


current_time = datetime.now()

11. Functions
- Functions are reusable blocks of code that perform specific tasks.
- Example:

def greet(name):
return f"Hello, {name}!"

12. Chapters (math, random)


- Chapters are libraries of pre-written code. Python includes various Chapters, like `math`
for mathematical operations and `random` for random number generation.
- Example:

import math
import random
13. Files I/O
- Python can read from and write to files using built-in functions like `open()`.
- Example:
with open('data.txt', 'r') as file:
content = file.read()

14. Exceptions
- Exceptions are used to handle errors gracefully in Python.
- Example:
try:
result = 10 / 0
except ZeroDivisionError:
print("Division by zero is not allowed.")
Chapter 3: CGI and GUI Programming in Python

1. Classes and Objects:


- Definition: Classes in Python are a way to bundle data and functionality together. Objects
are instances of these classes, representing real-world entities.
- Example:
```python
class Person:
def __init__(self, name, age):
self.name = name
self.age = age

Creating objects
person1 = Person("John", 30)
person2 = Person("Alice", 25)
```

2. Regular Expressions:
- Definition: Regular expressions (regex) are powerful tools for pattern matching in strings.
They define search patterns for text processing.
- Example:
```python
import re

Validating email address


pattern = r'^[\w\.-]+@[\w\.-]+\.\w+$'
email = '[email protected]'
if re.match(pattern, email):
print("Valid email address")
```

3. CGI Programming:
- Definition: CGI programming enables the creation of dynamic web applications by
executing scripts on a web server in response to user requests.
- Example:
```python
CGI script for processing form data
print("Content-type: text/html\r\n\r\n")
print("<html><body>")
print("<h2>Hello, {}!</h2>".format(form_data['name']))
print("</body></html>")
```

4. Database Access Networking:


- Definition: Database access networking involves connecting Python applications to
databases, executing queries, and retrieving or modifying data.
- Example:
```python
import mysql.connector
Connecting to MySQL database
connection = mysql.connector.connect(
host="localhost",
user="username",
password="password",
database="example_db"
)

Executing SQL query


cursor = connection.cursor()
cursor.execute("SELECT * FROM users")
result = cursor.fetchall()
```

5. Sending Email:
- Definition: Sending email using Python involves utilizing libraries like `smtplib` to
connect to an email server and send messages programmatically.
- Example:
```python
import smtplib
from email.mime.text import MIMEText

Sending email
server = smtplib.SMTP('smtp.example.com', 587)
server.starttls()
server.login("[email protected]", "password")

msg = MIMEText("Hello, this is a test email.")


msg['Subject'] = "Test Email"
msg['From'] = "[email protected]"
msg['To'] = "[email protected]"

server.sendmail("[email protected]", "[email protected]", msg.as_string())


server.quit()
```

6. Multithreading:
- Definition: Multithreading enables concurrent execution of multiple threads within a
Python program, enhancing performance.
- Example:
```python
import threading

def print_numbers():
for i in range(5):
print(i)

def print_letters():
for letter in 'ABCDE':
print(letter)
Creating threads
thread1 = threading.Thread(target=print_numbers)
thread2 = threading.Thread(target=print_letters)

Starting threads
thread1.start()
thread2.start()
```

7. XML Processing:
- Definition: XML processing involves parsing and manipulating XML data in Python
using libraries like `xml.etree.ElementTree`.
- Example:
```python
import xml.etree.ElementTree as ET

Parsing XML data


xml_data = '<person><name>John</name><age>30</age></person>'
root = ET.fromstring(xml_data)
```

8. GUI Programming:
- Definition: GUI programming in Python involves creating visual interfaces for
applications using libraries like Tkinter or PyQt.
- Example:
```python
from tkinter import Tk, Label, Button

class GUIApp:
def __init__(self, master):
self.master = master
master.title("GUI Application")

self.label = Label(master, text="Hello, GUI!")


self.label.pack()

self.button = Button(master, text="Click me!", command=self.print_message)


self.button.pack()

def print_message(self):
print("Button clicked!")

root = Tk()
app = GUIApp(root)
root.mainloop()
```

9. Extending and Embedding Python:


- Definition: Extending Python involves integrating Python code with other programming
languages, while embedding Python involves including Python interpreters within other
applications.
- Example:
- *Extending Python in C:*
```c
include <Python.h>

int main() {
Py_Initialize();
PyRun_SimpleString("print('Hello from C!')");
Py_Finalize();
return 0;
}
```
- *Embedding Python:*
```c
include <Python.h>

int main() {
Py_Initialize();
PyRun_SimpleString("print('Hello from embedded Python!')");
Py_Finalize();
return 0;
}
Chapter 4: Introduction to Ruby on Rails

1. MVC Architecture:
- Definition: MVC (Model-View-Controller) is a software design pattern used in Ruby on
Rails to structure code into three interconnected components for better organization and
scalability.
- Example:
In a blog application:
- Model: Manages data structures, such as Post and Comment models.
- View: Displays information, presenting posts and comments to users.
- Controller: Handles user interactions, managing requests and updating models
accordingly.

2. How to Install:
- Steps:
1. Install Ruby using RVM (Ruby Version Manager).
2. Install Rails using the gem package manager.
3. Verify the installation using terminal commands.
- Example:
```bash
Install RVM
\curl -sSL https://get.rvm.io | bash -s stable
source ~/.rvm/scripts/rvm

Install Ruby
rvm install ruby

Install Rails
gem install rails

Verify installation
ruby -v
rails -v
```

3. Framework, Directory Structure, Features:


- Framework Overview:
- Ruby on Rails is a web application framework written in Ruby.
- Emphasizes convention over configuration, streamlining development.
- Directory Structure:
- Follows a specific structure for models, views, controllers, and more.
- Eases navigation and maintains a consistent layout.
- Key Features:
- Automatic code generation with powerful scaffolding.
- Built-in testing tools like RSpec and integration with databases.

4. Basic Rails Application:


- Steps:
1. Create a new Rails application using the `rails new` command.
2. Understand the basic components: models, views, controllers, and routes.
3. Run the application using the `rails server` command.
- Example:
```bash
Create a new Rails application
rails new my_blog

Navigate to the application directory


cd my_blog

Generate a scaffold for posts


rails generate scaffold Post title:string body:text

Run the migration to create the database table


rake db:migrate

Start the Rails server


rails server
```
This example creates a simple blog application with posts, including title and body
attributes.
Chapter 5: Advanced Rails Applications

1. Setting up the Database:


- Steps:
1. Configure database connections in the `database.yml` file.
2. Use migrations to define and modify database tables.
3. Run migrations to apply changes to the database.
- Example:
```yaml
database.yml
development:
adapter: postgresql
database: my_rails_app_development
username: postgres
password: secret
host: localhost
port: 5432
```
Setting up a PostgreSQL database for a Rails application, configuring connection details
in `database.yml`.

2. Active Records, Migrations:


- Active Records:
- Rails' Active Record provides an Object-Relational Mapping (ORM) system, simplifying
database interactions through Ruby objects.
- Migrations:
- Migrations are scripts that manage database schema changes over time, ensuring version
control and consistency.
- Example:
```ruby
Define a model with Active Record associations
class User < ApplicationRecord
has_many :posts
end

Create a migration to add a column to the users table


rails generate migration AddAdminToUsers admin:boolean
```
Defining a `User` model with associations and creating a migration to add an `admin`
column.

3. Controllers, Routes, Views:


- Controllers:
- Controllers handle user requests, process input, and manage the interaction between
models and views.
- Routes:
- Routes define the URLs and map them to corresponding controller actions.
- Views:
- Views display information to users based on data provided by controllers.
- Example:
```ruby
UsersController handles user-related actions
class UsersController < ApplicationController
def new
Controller action for displaying the registration form
end
end

Define a route for the registration form


get '/register', to: 'usersnew'
```
Creating a controller for user actions, defining a route, and setting up a view for user
registration.

4. Layouts, Scaffolding, AJAX:


- Layouts:
- Layouts define the overall structure and design of a Rails application, providing a
consistent template for views.
- Scaffolding:
- Scaffolding generates basic CRUD functionality (Create, Read, Update, Delete) for
models, speeding up development.
- AJAX:
- AJAX allows for asynchronous updates, enhancing user experience without page
refreshes.
- Example:
Using scaffolding to quickly create CRUD operations for a resource like `Post` and
implementing AJAX for dynamic updates.

5. Uploading Files, Sending Email:


- Uploading Files:
- Rails supports file uploads using libraries like CarrierWave or Active Storage, enabling
storage and retrieval of user-uploaded files.
- Sending Email:
- Rails provides Action Mailer for sending emails from applications, facilitating
communication with users.
- Example:
Implementing file uploads for user avatars using CarrierWave and sending email
notifications for account activation.

You might also like