Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
31 views72 pages

Unit-4 Frameworks

Uploaded by

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

Unit-4 Frameworks

Uploaded by

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

Python Frameworks

Python is one of the most acceptable languages among


web and application developers because of its strong
emphasis on efficiency and readability.

There are numerous outstanding Python web


frameworks, each with their own specialities and
features.
Django

Category − Django belongs to the full-stack Python


framework.
Release − Latest release – 2.1 version, commonly used
release – 1.8, 1.6 version.
About − Built by experienced developers, Django is a
high level Python web framework which allows rapid,
clean and pragmatic design development. Django
handles much of the complexities of web
development, so you can focus on writing your app
without a need to reinvent the wheel. It’s free and
open source.
To map objects to database table, Django uses ORM and the same is
used to transfer from one database to other.

It works with mostly all important databases like Oracle, MySQL,


PostgreSQL, SQLite, etc.

There are numerous websites in the industry which uses Django as


their primary framework for backend development.
Features of Django

Some of the exemplary features of this Python web framework are −


URL routing
Authentication
Database schema migrations
ORM (Object-relational mapper)
Template engine
Flask

Category − Flask belongs to Non Full-stack frameworks.

Release − 1.0.2 released on 2018-05-02

About − It is classified as a micro-framework as we don’t require any


particular libraries or tools.

It has no form validation or database abstraction layer or any other


components where pre-existing third party libraries provide common
functions.
However, flask support multiple extensions which extended the
application features as if they were implemented in Flask itself.

Extensions exist for object-relational mappers, form validation,


upload handling, various open authentication technologies and
several common frameworks related tools.
Features of Flask
 Integrated support for unit testing
 Restful request dispatching
 Contains development server and debugger
 Uses Jinja2 templating
 Support for secure cookies
 Unicode-based
 100% WSGI 1.0 compliant
 Extensive documentation
 Google App Engine compatibility
 Extensions available to enhance features desired
Web2py

Category − Web2py belongs to Full-stack framework family.

Release − 2.17.1, released on 2018-08-06

About − Python 2.6, 2.7 to Python 3.x version. With no further


dependencies, it’s a complete package in itself.

Development, database administration, debugging, deployment,


testing, and maintenance of applications all can be done through
web interface, but generally not required.

It is a scalable open source framework that comes with its own web-
based IDE alongside a code editor, one-click deployment and
debugger.
Features of Web2py

 This framework comes with many developing tools and built-in


features that eliminate the hassle of complexity to the
developers.

 With no installation and configuration, it is easy to run.

 Supports almost all major operating system, like Windows,


Unix/Linux, Mac, Google App Engine and almost all web hosting
platform through Python 2.7/3.5/3.6/ version.

 Easy to communicate with MySQL, MSSQL, IBM DB2, Informix,


Ingres, MongoDB, SQLite, PostgreSQL, Sybase, Oracle and
Google App Engine.
 It prevents the most common types of vulnerabilities including
Cross Site Scripting, Injection Flaws, and Malicious File
Execution.

 Supports error tracking and internationalization.

 Multiple protocols readability.

 Employs successful software engineering practices that makes


code easy to read and maintain.

 Ensure user-oriented advancements through backward


compatibility.
Pyramid

Category − Pyramid is a non-Full Stack Frameworks

Release − 1.9.2, released on 2018-04-23

About − Pyramid is a small, fast, down-to-earth Python web


framework. It is developed as part of the Pylons Project. It is
licensed under a BSD-like license.

It makes real-world web application development and


deployment more fun, more predictable and more productive.
Features of Pyramid

Python Pyramid is an open sourced framework with the following features −

Simplicity − Anyone can start to work with it without any prior knowledge
about it.

Minimalism − Quite out of the box, Pyramid comes with only some important
tools, which are needed for almost every web application, may it be security
or serving static assets like JavaScript and CSS or attaching URLs to code.

Documentation − Includes exclusive and up to date documentation.

Speed − Very fast and accurate.

Reliability − It is developed, keeping in mind that it is conservative and tested


exhaustively. If not tested properly, it will be considered as broke.

Openness − It’s sold with a permissive and open license.


Dash
Category − The Dash framework belongs to “other” Python web
frameworks.

Release − 0.24.1, core dash backend.

About − Dash as an open source library for creating interactive


web-based visualizations.

The plotly team created Dash – an open source framework that


leverages Flask, React.js and plotly.js to build custom data
visualization apps.

Key highlight of this library is that you can build highly interactive
web application only through Python code. Data scientists love
dash framework, specially all those who are less familiar with
web development.
With Dash, developers get access to all the configurable
properties and underlying Flask instance.

The applications developed using Dash framework can be


deployed to servers and are eventually rendered in the web
browser.

Dash applications are inherently cross-platform (Linux/Win/Mac)


and mobile friendly and the capabilities of applications can be
extended by the rich set of Flask Plugins.

Features of Dash

Provides access to configurable properties and Flask instance


Through Flash plugins, we can extend the capabilities of the Dash
application
Mobile-ready
Introduction of Django
Django is a back-end server side web framework.

Django is free, open source and written in Python.

Django makes it easier to build web pages using Python.


What is Django?
Django is a Python framework that makes it easier to create web sites using
Python.

Django takes care of the difficult stuff so that you can concentrate on building
your web applications.

Django emphasizes reusability of components, also referred to as DRY (Don't


Repeat Yourself), and comes with ready-to-use features like login system,
database connection and CRUD operations (Create Read Update Delete).

Django is especially helpful for database driven websites.


How does Django Work?

Django follows the MVT design pattern (Model View Template).

Model - The data you want to present, usually data from a


database.

View - A request handler that returns the relevant template and


content - based on the request from the user.

Template - A text file (like an HTML file) containing the layout of


the web page, with logic on how to display the data.
Model
The model provides data from the database.

In Django, the data is delivered as an Object Relational


Mapping (ORM), which is a technique designed to make it
easier to work with databases.

The most common way to extract data from a database is


SQL. One problem with SQL is that you have to have a pretty
good understanding of the database structure to be able to
work with it.

Django, with ORM, makes it easier to communicate with the


database, without having to write complex SQL statements.

The models are usually located in a file called models.py.


View
A view is a function or method that takes http requests as
arguments, imports the relevant model(s), and finds out what
data to send to the template, and returns the final result.

The views are usually located in a file called views.py.

Template
A template is a file where you describe how the result should be
represented.

Templates are often .html files, with HTML code describing the
layout of a web page, but it can also be in other file formats to
present other results, but we will concentrate on .html files.
Django uses standard HTML to describe the layout, but uses Django tags to
add logic:

<h1>My Homepage</h1>

<p>My name is {{ firstname }}.</p>


The templates of an application is located in a folder named templates.
URLs
Django also provides a way to navigate around the different pages in a
website.

When a user requests a URL, Django decides which view it will send it to.

This is done in a file called urls.py.


When you have installed Django and created your first Django
web application, and the browser requests the URL, this is
basically what happens:

Django receives the URL, checks the urls.py file, and calls the
view that matches the URL.

 The view, located in views.py, checks for relevant models.


 The models are imported from the models.py file.
 The view then sends the data to a specified template in the
template folder.
 The template contains HTML and Django tags, and with the
data it returns finished HTML content back to the browser.
Django History

Django was invented by Lawrence Journal-World in 2003, to


meet the short deadlines in the newspaper and at the same
time meeting the demands of experienced web developers.

Initial release to the public was in July 2005.

Latest version of Django is 4.0.3 (March 2022).


To install Django, you must have Python installed, and a package manager like
PIP.

PIP is included in Python from version 3.4.

Django Requires Python


To check if your system has Python installed, run this command in the command
prompt:

python --version
If Python is installed, you will get a result with the version number, like this

Python 3.9.2
If you find that you do not have Python installed on your computer, then you can
download it for free from the following website: https://www.python.org/
PIP
To install Django, you must use a package manager like PIP, which is included in
Python from version 3.4.

To check if your system has PIP installed, run this command in the command
prompt:

pip --version
If PIP is installed, you will get a result with the version number.

For me, on a windows machine, the result looks like this:

pip 20.2.3 from c:\python39\lib\site-packages\pip (python 3.9)


If you do not have PIP installed, you can download and install it from this page:
https://pypi.org/project/pip/
Virtual Environment

It is suggested to have a dedicated virtual environment for each Django project, and one
way to manage a virtual environment is venv, which is included in Python.

With venv, you can create a virtual environment by typing this in the command prompt,
remember to navigate to where you want to create your project:

Windows:

py -m venv myproject
Unix/MacOS:

python -m venv myproject


This will set up a virtual environment, and create a folder named "myproject" with
subfolders and files, like this:

myproject
Include
Lib
Scripts
pyvenv.cfg
Then you have to activate the environment, by typing this command:
Windows:

myproject\Scripts\activate.bat
Unix/MacOS:

source myproject/bin/activate
Once the environment is activated, you will see this result in the command
prompt:

Windows:

(myproject) C:\Users\Your Name>


Unix/MacOS:

(myproject) ... $
Install Django
Finally, we can install Django.

Remember to install Django while you are in the virtual


environment!

Django is installed using pip, with this command:

Windows:

(myproject) C:\Users\Your Name>py -m pip install Django


Unix/MacOS:

(myproject) ... $ python -m pip install Django


Check Django Version

You can check if Django is installed by asking for its version


number like this:

(myproject) C:\Users\Your Name>django-admin --version


If Django is installed, you will get a result with the version
number:

4.0.3
My First Project
Once you have come up with a suitable name for your Django project, like
mine: myworld, navigate to where in the file system you want to store the code
(in the virtual environment), and run this command in the command prompt:

django-admin startproject myworld


Django creates a myworld folder on my computer, with this content:

myworld
manage.py
myworld/
__init__.py
asgi.py
settings.py
urls.py
wsgi.py

These are all files and folders with a specific meaning, it is more important to
know that this is the location of your project, and that you can start building
applications in it.
Run the Django Project
Now that you have a Django project, you can run it, and see what it looks like in a browser.

Navigate to the /myworld folder and execute this command in the command prompt:

py manage.py runserver

Which will produce this result:

Watching for file changes with StatReloader


Performing system checks...

System check identified no issues (0 silenced).

You have 18 unapplied migration(s). Your project may not work properly until you apply the
migrations for app(s): admin, auth, contenttypes, sessions.
Run 'python manage.py migrate' to apply them.
December 02, 2021 - 13:14:51
Django version 3.2.9, using settings 'myworld.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CTRL-BREAK.
Open a new browser window and type 127.0.0.1:8000 in the address bar.

The result:
Django Create App

Create App
I will name my app members.

Start by navigating to the selected location where you want to store


the app, and run the command below.

If the server is still running, and you are not able to write commands,
press [CTRL] [BREAK] to stop the server and you should be back in the
virtual environment.

py manage.py startapp members


Django creates a folder named members in my project, with this
content:
myworld
manage.py
myworld/
members/
migrations/
__init__.py
__init__.py
admin.py
apps.py
models.py
tests.py
views.py
A web page that uses Django is full of views with different tasks and missions.

Views are usually put in a file called views.py located on your app's folder.

There is a views.py in your members folder that looks like this:

members/views.py:

from django.shortcuts import render

# Create your views here.


Find it and open it, and replace the content with this:

members/views.py:

from django.shortcuts import render


from django.http import HttpResponse

def index(request):
return HttpResponse("Hello world!")
URLs
Create a file named urls.py in the same folder as the
views.py file, and type this code in it:

members/urls.py:

from django.urls import path


from . import views

urlpatterns = [
path('', views.index, name='index'),
]
The urls.py file you just created is specific for the members
application. We have to do some routing in the root
directory myworld as well.
There is a file called urls.py on the myworld folder, open that file
and add the include module in the import statement, and also add
a path() function in the urlpatterns[] list, with arguments that will
route users that comes in via 127.0.0.1:8000/members/.

Then your file will look like this:

myworld/urls.py:

from django.contrib import admin


from django.urls import include, path

urlpatterns = [
path('members/', include('members.urls')),
path('admin/', admin.site.urls),
]
In the browser window, type 127.0.0.1:8000/members/ in the address bar.
Create a templates folder inside the members folder, and create a
HTML file named myfirst.html.

The file structure should be something like this:

myworld
manage.py
myworld/
members/
templates/
myfirst.html
Open the HTML file and insert the following:

members/templates/myfirst.html:

<!DOCTYPE html>
<html>
<body>

<h1>Hello World!</h1>
<p>Welcome to my first Django project!</p>

</body>
</html>
Modify the View
Open the views.py file and replace the index view with this:

members/views.py:

from django.http import HttpResponse


from django.template import loader

def index(request):
template = loader.get_template('myfirst.html')
return HttpResponse(template.render())
Change Settings
To be able to work with more complicated stuff than "Hello World!", We have to tell
Django that a new app is created.

This is done in the settings.py file in the myworld folder.

Look up the INSTALLED_APPS[] list and add the members app like this:

myworld/settings.py:

INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'members.apps.MembersConfig'
]
Then run this command:

py manage.py migrate
Which will produce this output:

Operations to perform:
Apply all migrations: admin, auth, contenttypes, sessions
Running migrations:
Applying contenttypes.0001_initial... OK
Applying auth.0001_initial... OK
Applying admin.0001_initial... OK
Applying admin.0002_logentry_remove_auto_add... OK
Applying admin.0003_logentry_add_action_flag_choices... OK
Applying contenttypes.0002_remove_content_type_name... OK
Applying auth.0002_alter_permission_name_max_length... OK
Applying auth.0003_alter_user_email_max_length... OK
Applying auth.0004_alter_user_username_opts... OK
Applying auth.0005_alter_user_last_login_null... OK
Applying auth.0006_require_contenttypes_0002... OK
Applying auth.0007_alter_validators_add_error_messages... OK
Applying auth.0008_alter_user_username_max_length... OK
Applying auth.0009_alter_user_last_name_max_length... OK
Applying auth.0010_alter_group_name_max_length... OK
Applying auth.0011_update_proxy_permissions... OK
Applying auth.0012_alter_user_first_name_max_length... OK
Applying sessions.0001_initial... OK
(myproject)C:\Users\Your Name\myproject\myworld>
Start the server by navigating to the /myworld folder and execute this command:

py manage.py runserver
In the browser window, type 127.0.0.1:8000/members/ in the address bar.

The result should look like this:


A Django model is a table in your database.

SQLite Database
When we created the Django project, we got an empty SQLite database. It was
created in the myworld root folder.

We will use this database in this tutorial.

Create Table (Model)


To create a new table, we must create a new model.

In the /members/ folder, open the models.py file. It is almost empty by default,
with only an import statement and a comment:

members/models.py:

from django.db import models

# Create your models here.


To add a Members table in our database, start by creating a Members
class, and describe the table fields in it:

members/models.py:

from django.db import models

class Members(models.Model):
firstname = models.CharField(max_length=255)
lastname = models.CharField(max_length=255)
The first field, "firstname" is a Text field, and will contain the first name of
the members.

The second field, "lastname" is also a Text field, with the members' last
name.

Both "firstname" and "lastname" is set up to have a maximum of 255


characters.
Then navigate to the /myworld/ folder and run this command:

py manage.py makemigrations members


Which will result in this output:

Migrations for 'members':


members\migrations\0001_initial.py
- Create model Members

(myproject) C:\Users\Your Name\myproject\myworld>


Django creates a file with any new changes and stores the file in the /migrations/
folder.

Next time you run py manage.py migrate Django will create and execute an SQL
statement, based on the content of the new file in the migrations folder.

Run the migrate command:

py manage.py migrate
Which will result in this output:

Operations to perform:
Apply all migrations: admin, auth, contenttypes, members, sessions
Running migrations:
Applying members.0001_initial... OK

(myproject) C:\Users\Your Name\myproject\myworld>


The SQL statement created from the model is:

CREATE TABLE "members_members" (


"id" INT NOT NULL PRIMARY KEY AUTOINCREMENT,
"firstname" varchar(255) NOT NULL,
"lastname" varchar(255) NOT NULL);
Now you have a Members table in you database!
Add Records
The Members table is empty, we should add some members to it.
To open a Python shell, type this command:

py manage.py shell

Add a record to the table, by executing these two lines:

>>> member = Members(firstname='Emil', lastname='Refsnes')


>>> member.save()
Execute this command to see if the Members table got a member:

>>> Members.objects.all().values()
Hopefully, the result will look like this:

<QuerySet [{'id': 1, 'firstname': 'Emil', 'lastname': 'Refsnes'}]>


Add Multiple Records
You can add multiple records by making a list of Members objects, and
execute .save() on each entry:

>>> member1 = Members(firstname='Tobias', lastname='Refsnes')


>>> member2 = Members(firstname='Linus', lastname='Refsnes')
>>> member3 = Members(firstname='Lene', lastname='Refsnes')
>>> member4 = Members(firstname='Stale', lastname='Refsnes')
>>> members_list = [member1, member2, member3, member4]
>>> for x in members_list:
>>> x.save()
Modify the View
Change the index view to include the template:

members/views.py:

from django.http import HttpResponse


from django.template import loader
from .models import Members

def index(request):
mymembers = Members.objects.all().values()
template = loader.get_template('index.html')
context = {
'mymembers': mymembers,
}
return HttpResponse(template.render(context, request))
Add a new template in the templates folder, named add.html:

members/templates/add.html:

<h1>Add member</h1>

<form action="addrecord/" method="post">


{% csrf_token %}
First Name:<br>
<input name="first">
<br><br>
Last Name:<br>
<input name="last">
<br><br>
<input type="submit" value="Submit">
</form>
Add a "delete" column in the members template:

members/templates/index.html:

<h1>Members</h1>

<table border="1">
{% for x in mymembers %}
<tr>
<td>{{ x.id }}</td>
<td>{{ x.firstname }}</td>
<td>{{ x.lastname }}</td>
<td><a href="delete/{{ x.id }}">delete</a></td>
</tr>
{% endfor %}
</table>

<p>
<a href="add/">Add member</a>
</p>
Web2py
Web2py is a free, open-source web framework for Python that focuses on rapid
development and ease of use. It allows developers to build web applications quickly with
minimal setup. Below are key features and aspects of web2py:
Key Features of Web2py
No Installation Required:
Web2py comes with a built-in web server, so it doesn't require a separate
installation.
You just download and run it without needing to install or configure external
dependencies.
Python-Based:
Written entirely in Python and supports Python 2.x and 3.x versions.
Python code is used throughout the development process, making it easy to
integrate with other Python libraries.
Integrated IDE:
It provides a web-based integrated development environment (IDE) that includes
code editing, debugging, and testing tools.
This IDE allows you to manage applications directly via a web interface.
• Security:
– Web2py focuses heavily on security with built-in features for preventing common
vulnerabilities like SQL Injection, Cross-Site Scripting (XSS), and Cross-Site Request
Forgery (CSRF).
– Session management and access control are handled in a secure way with user
authentication modules.
• Built-in Components:
– Database Abstraction Layer (DAL): It supports multiple database backends like
SQLite, MySQL, PostgreSQL, Oracle, MSSQL, etc., using a powerful DAL. You can work
with databases without writing SQL code.
– AJAX and jQuery Integration: Allows dynamic, AJAX-enabled interactions without
much boilerplate code.
– Templating Engine: A simple and fast template engine for creating web pages.
• Batteries Included:
– Web2py provides many built-in modules like authentication, form handling, and
RESTful APIs, meaning you don’t need third-party plugins for most basic tasks.
• Multi-Database Support:
– It can connect to different databases simultaneously and supports database
migrations.
• Portable:
– You can run a Web2py application on various platforms such as Windows, macOS, and
Linux. It also supports deploying on Google App Engine and other cloud platforms.
Structure of a Web2py Application

Web2py applications are organized around the Model-View-Controller


(MVC) architecture:
Models: Define the database schema and relationships.
Controllers: Handle requests, business logic, and manage user interactions.
Views: Handle the rendering of HTML pages and templates.
Example of Web2py Code
Here’s a simple Web2py application showing the basics:
Model (db.py):
Python Copy code
# Define a simple table
db.define_table('person',
Field('name'),
Field('email'))
Controller (default.py):
python
Copy code
# Function to display a form and insert data into the 'person' table
def index():
form = SQLFORM(db.person).process()
if form.accepted:
response.flash = 'Record inserted successfully!'
people = db(db.person).select()
return dict(form=form, people=people)
View (index.html):
html
Copy code
{{extend 'layout.html'}}
<h2>Enter Person's Info</h2>
{{=form}}
<h2>List of People</h2>
<ul>
{{for person in people:}}
<li>{{=person.name}} - {{=person.email}}</li>
{{pass}}
</ul>
• Running Web2py
• To run web2py, follow these steps:
• Download Web2py from the official site: Web2py
• Unzip and run web2py.py (or web2py.exe on Windows).
• Open the web browser and go to http://127.0.0.1:8000 to
access the web-based interfaceYou can create and manage
applications from the web interface, and it provides functionality
for editing code, managing databases, and testing applications.
• Deployment Options
• Web2py applications can be deployed on popular cloud services,
including AWS, Google Cloud, and Heroku.
• It also offers features like automated backups, caching, and
performance optimization tools to support large-scale
applications.
Conclusion

• Web2py is ideal for developers seeking a


lightweight yet robust Python web framework
that emphasizes ease of use, security, and
rapid development.
• Its all-in-one approach makes it a great choice
for small to medium-sized applications, and its
simplicity allows developers to focus on
application logic rather than configuration.

You might also like