You are on page 1of 28

DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

ST JOSEPH ENGINEERING COLLEGE, MANGALURU-575028


ASSIGNMENT
ON

Application Development Using Python (18CS55)


Submitted by
AKUL VINOD - 4SO19CS012
ANISHA N- 4SO19CS019
ANKITH THOMAS- 4SO19CS021
DHANYASHREE S- 4SO19CS048
JAYALAKSHMI H A-4SO19CS064

CSE ‘A’
Submitted to Dr Melwyn D'Souza
Asst. Professor,
Dept of CSE Affiliated to Visvesvaraya Technological University, Belagavi

2021-22
Problem 1
A menu driven program that is used to download a CSV file from a website and
then convert the CSV file to a document.
Code:
from selenium import webdriver
import csv
import docx

print("__MENU__") #Display MENU


print("1.Download a CSV file")
print("2.Convert a CSV file to docx")

while(True):
ch=int(input("Enter your choice : ")) #Enter the choice continuosly

if ch==1:
print('Googling........') #display text while downloading the page.
try: #Exception handling
browser=webdriver.Chrome() #opening Chrome browser
browser.get('https://support.staffbase.com/hc/en-
us/articles/360007108391-CSV-File-Examples') #Going to the site from where
rhe file to be downloaded
elem=browser.find_element_by_css_selector('#article-container > article >
section.article-info > div > div.article-body > div:nth-child(4) > h3:nth-child(5) >
a:nth-child(2)')
#finding the link from where the file to be downloaded from the page
elem.click() #click on the link to download the file
except:
print('An error occured while scraping!! Check your internet connection')
#exception occurs if the downloadind process is not successful

if ch==2:
file=open('C:\\Users\\ANISHA N\\Desktop\\Fifth
sem\\ADP\\Project\\Username.csv','rt') #opening the csv file
reader=csv.reader(file) #reading csv file
data=list(reader) #passing the content into a list
length=len(data) #calculating length of the list

OutFile=docx.Document() #opening an output document

for i in range (0,length): #iterating through each line


for j in range (0,len(data[i])): #iterating through each words
OutFile.add_paragraph(data[i][j]+' ') #add the lines from CSV file to
Document
OutFile.save('C:\\Users\\ANISHA N\\Desktop\\Fifth
sem\\ADP\\Project\\Document.docx') #saving the document in folder

Output Screenshots
Problem 2
Program to perform Create(), Read(),Update() and Delete() using
databases.By using Flask, SQLAlchemy(Database) and JSON ,we have
created a Feedback Centre app,which performs CRUD Operations. We
have used HTML forms and the contents that have been filled in the
form, are inserted to database using POST method. We can retrieve
the contents from the database using GET method. The
jsonify()method displays the content in JSON format. When the
requested url is not found in the server, 404 error message will be
displayed in JSON format.
Code:

app.py :-

from flask import


Flask,render_template,request,url_for,redirect,jsonify #Importing
required modules
from flask_sqlalchemy import SQLAlchemy #importing SQLAlchemy
database
from datetime import datetime
import json

app=Flask(__name__) #defining app


app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///posts.db' #app
configuration with SQLAlchemy database
db=SQLAlchemy(app)

class BlogPost(db.Model): #BlogPost class


id=db.Column(db.Integer,primary_key=True) #Defining
attributes and constraints for database
title=db.Column(db.String(100),nullable=False)
content=db.Column(db.Text,nullable=False)
author=db.Column(db.String(20),nullable=False,default='N/A')

date_posted=db.Column(db.DateTime,nullable=False,default=datetime
.utcnow)

def __repr__(self):
return "Blog post "+str(self.id)

@app.errorhandler(404) #If the requested url is not found,


then it displays 404 error message
def errorhandler(error):
return (jsonify({'message':'Not Found','code':404})) #displaying error
in the form of JSON

@app.route('/') #defining route for / , it allows only


GET method.
def index():
return render_template('index.html') #if URL is localhost:5000/
then index.html page will be displayed.

@app.route('/posts',methods=['POST','GET']) # route = /posts, it


allows POST and Get methods
def posts():
try:
if request.method =='POST':
post_title=request.form['title'] #collecting all information from
the html input fields and stores it-
post_content=request.form['content'] # -in database table as new
Blog post
post_author=request.form['author']
new_post =
BlogPost(title=post_title,content=post_content,author=post_author)
db.session.add(new_post)
db.session.commit()
return redirect('/posts') #after adding new row to the
database, redirect to /posts page

else:
all_posts=BlogPost.query.order_by(BlogPost.date_posted).all()
return render_template('posts.html') #if method is not POST , then
it renders posts.html page,which contains-
# -html form to create
new post
except Exception as err:
return f"{err}"

@app.route('/posts/delete/', methods=['POST','DELETE'])
def delete(): # deleting a post from the
database
try:
if request.method == 'POST':
all_posts=BlogPost.query.order_by(BlogPost.date_posted).all() #
collecting all rows(all posts) from the database.
id=request.form['del'] # collecting id of the post from the
html input field,which is to be deleted.
post=BlogPost.query.get(id) # Checking whether the post with
given id is exists in database.
if post: # if it exists, then delete that post from
database
db.session.delete(post)
db.session.commit() # without commiting,no changes will
going to apply!
delpost=BlogPost.query.get(id) # After deleting,again we are
checking the existance of that post.
if not delpost: # If that post is Successfully deleted,
then display the below message
return '''<h1 style="text-align:center; font-family:Arial,
Helvetica, sans-serif; margin-top:200px;">Successfully deleted. <a
href="/posts/normalview"> VIEW</a> all posts to see changes</h1>

'''
if not post: # If the post with given id not exist in database, then
display the error message in JSON format.
return jsonify({'message':'Invalid Post ID'})
except Exception as err:
return f"{err}"

@app.route('/posts/edit/<int:id>', methods=['GET','POST']) # route for


editing Blog posts. It takes id of the post (integer)
def edit(id):
post=BlogPost.query.get_or_404(id) # get the post by
using supplied post id.
if request.method == 'POST':
post.title=request.form['title'] #take new title for the
post,specified in html input field and apply changes to-
post.author=request.form['author'] #- the
original post
post.content=request.form['content']
db.session.commit()
return redirect('/posts')

else:
return render_template('edit.html',post=post)

@app.route('/posts/normalview',methods=['GET'])
def normalview():
all_posts=BlogPost.query.order_by(BlogPost.date_posted).all() #
Getting all the blog posts from the database

return render_template('normalview.html',posts=all_posts) #
displaying all posts in normalview.html page bypassing
#- posts object.
@app.route('/posts/jsonview',methods=['GET'])
def jsonview(): #JSON view of all posts
all_posts=BlogPost.query.order_by(BlogPost.date_posted).all() #
Getting all the blog posts from the database

output=[] # new output list,to store


dictionary
for post in all_posts:
data={} #new dictionary to store data
of each post.
data['id']=post.id
data['title']=post.title
data['content']=post.content
data['author']=post.author
output.append(data) #appending each
dictionary to output list.

return jsonify(output) # displaying all posts in


JSON format

if __name__=='__main__':
app.run(debug=True) # running our app. Automatically
changes will be saved because of debug=True.
base.html :-
<!DOCTYPE html>
<html lang="en">

<head>

<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-
scale=1.0">
<link rel="stylesheet" href="static/1.css"</link>
<link rel="stylesheet"
href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstr
ap.min.css"
integrity="sha384-
JcKb8q3iqJ61gNV9KGb8thSsNjpSL0n8PARn9HuZOnIxN0hoP+VmmDGM
N5t9UJ0Z" crossorigin="anonymous">
<!--<link rel="stylesheet" href="{{ url_for('static',
filename='css/main.css') }}">-->

{% block head%} {% endblock%}


</head>

<body>
<nav class="navbar navbar-expand navbar-dark bg-dark">
<a class="navbar-brand" href="/">Blog Post</a>
<button class="navbar-toggler" type="button" data-
toggle="collapse" data-target="#navbarsExample02"
aria-controls="navbarsExample02" aria-expanded="false" aria-
label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>

<div class="collapse navbar-collapse" id="navbarsExample02">


<ul class="navbar-nav mr-auto">
<li class="nav-item active">
<a class="nav-link" href="/">Home <span class="sr-
only">(current)</span></a>
</li>
<li class="nav-item">
<a class="nav-link" href="/posts">Create/Delete</a>
</li>
<li class="nav-item">
<a class="nav-link"
href="/posts/normalview">View/Edit</a>
</li>
</li>
<li class="nav-item">
<a class="nav-link" href="/posts/jsonview">JSON
Format</a>
</li>
</ul>

</div>
</nav>

<div class="container">
{% block body%} {% endblock%}
</div>

<script
src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap
.min.js"
integrity="sha384-
B4gt1jrGC7Jh4AgTPSdUtOBvfO8shuf57BaghqFfPlYxofvL8/KUEfYiJOMM
V+rV"
crossorigin="anonymous"></script>
</body>
<style>

</style>

</html>

edit.html :-

{% extends 'base.html' %}

{% block head%}
<title>Edit Movie</title>
{% endblock%}

{% block body%}

<h2 class="ph2">Edit</h2>
<form action="/posts/edit/{{ post.id }}" method="POST">
<label for="title">Movie Title</label>
<input class="form-control" type="text" placeholder="ID of the
Post" name="title" id="title" value="{{ post.title }}">
<label for="author">Director</label>
<input class="form-control" type="text" placeholder="ID of the
Post" name="author" id="author" value="{{ post.author }}">
<br>

<label for="content">Movie Description</label>


<textarea class="form-control" id="content" name="content"
rows="3" placeholder="Contents" >{{ post.content }}</textarea>

<br>

<input class="btn btn-primary" type="submit" value="Save" id="btn">


</form>

<h3 style="text-align: center;">Create new Movie Feedback</h3>

<a href="/posts" class="btn btn-success" style="margin-left: 47%;"><b


style="font-size: larger;">+</b> New Movie</a>
{% endblock %}

index.html :-

{% extends 'base.html' %}

{% block head%}
<title>Flask app</title>
{% endblock%}

{% block body%}
<h1 style=" font-family: sans-serif;color:crimson">Welcome To Movie
Feedback Center!</h1>
<!--<h4 style="text-align: center; font-family: Arial, Helvetica, sans-
serif;">If you want to see the posts, <a
href="/posts">click here</a></h4> -->
<br>
<main role="main">
<div class="jumbotron">
<div class="col-sm-8 mx-auto">
<h1 style="color:crimson">A Movie Feedback Centre for Movie
Lovers using Python Flask</h1>
<p style="color:crimson"> We have created a simple <b>Movie
feedback app</b> using Flask which demonstrates the use of
<b>Databases, JSON and Web API.</b> </p>
<h3 style="text-align: center;color:crimson; font-
size:50px">By</h3>
<p style="text-align: center;color:crimson"><b>Ankith
Thomas</b></p>
<p style="text-align: center;color:crimson"><b>Anisha N</b></p>
<p style="text-align: center;color:crimson"><b>Jayalakshmi H
A</b></p>
<p style="text-align: center;color:crimson"><b>Dhanyashree
S</b></p>
<p style="text-align: center;color:crimson"><b>Akul Vinod</b></p>

<p>
<a class="btn btn-success" href="/posts" role="button">Go to
Movies &raquo;</a>
</p>

</div>
</div>
</main>
{% endblock%}

normalview.html :-

<head>
<link rel="stylesheet"
href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstr
ap.min.css"
integrity="sha384-
JcKb8q3iqJ61gNV9KGb8thSsNjpSL0n8PARn9HuZOnIxN0hoP+VmmDGM
N5t9UJ0Z" crossorigin="anonymous">
<title>ALL MOVIES</title>
</head>

<body style="background:skyblue">
<hr>
<h2 style="display: inline;">ALL Movies</h2>
<a style="display: inline; float: right;" href="/posts" class="btn btn-
primary">+ New Movie</a>
<a style="float: right; margin-right: 5%;" href="/posts" class="btn btn-
danger">- Delete Movie</a>
<hr style="height: 10px; background-color: crimson;">
{% for post in posts %}
<h5> Movie ID: {{ post.id}}</h5>
<h5>Movie Title: {{ post.title }}</h5>
<h5><p style="white-space: pre-wrap;">Description: {{
post.content}}</p></h5>
<h5>Director: {{ post.author}}</h5>
<a class="btn btn-primary" href="/posts/edit/{{ post.id }}"
style=""><p>Edit Movie {{ post.id }}</p></a>
<hr style="height: 5px; background-color: green;">
{% endfor %}

</body>

posts.html :-

{% extends 'base.html' %}

{% block head%}
<title>Posts</title>
{% endblock%}

{% block body%}
<hr>
<h2 class="ph2" style="text-align: left;color:crimson">Movie
Feedback</h2>
<form action="/posts" method="POST">
<label for="title" style="color:crimson">Movie Title:</label>
<input class="form-control" type="text" placeholder="Movie Title"
name="title" id="title">
<br>
<label for="author" style="color:crimson">Director:</label>
<input class="form-control" type="text" placeholder="Director of the
movie" name="author" id="author"><br>
<label for="content" style="color:crimson">Description:</label>
<textarea class="form-control" id="content" name="content"
rows="3" placeholder="Description"></textarea>
<br>
<input class="btn btn-success" type="submit" value="Post" id="btn" >
</form>
<hr style="height: 10px; background-color:red;">
<h2 style="color:crimson">Delete Movie</h2>
<form action="/posts/delete/" method="POST">
<label for="del"style="color:crimson">Enter Movie ID:</label>
<input class="form-control" type="text" placeholder="ID of the
Movie" name="del" id="del"><br>
<input class="btn btn-danger" type="submit" value="Delete">
</form>

<hr>

<h4 style="text-align: center;">Go Back to <a href="/">Home


Page</a></h4>
<h4 style="text-align: center;"><a href="/posts/normalview">View
and Edit</a> all Posts </h4>
<h4 style="text-align: center;">View All Posts in <a
href="/posts/jsonview">JSON format</a></h4>

{% endblock %}
THE END
Output Screenshots

You might also like