Sei sulla pagina 1di 45

Python

Django Framework
Open CV
Image Processing
Machine Learning
LINUX (Cent OS 7)
Prequisites :
CENTOS / RHEL, Python 3.6, OpenCV, opencv-python,
refer to centos.txt that I asked you to download

Install virtualenv using pip3 install virtualenv

Create a virtual environment using the following statements

python -m virtualenv django

a django folder will be created in the folder from where you executed the above
now while staying in the folder that contains the django folder, type

source django/bin/activate

The prompt will now be prefixed with (django) which means we are now in a virtual environment for
this particular session and whatever we will be installing will be for this session / project only

upgrade pip, for that type

pip3 install --upgrade pip

now install django for this environment, for that type

pip3 install Django==2.1.2


pip3 install opencv-python
pip3 install opencv-contrib-python

now move to django folder and type the following to create a new folder structure as discussed in the
classroom session

django-admin startproject projiproc


now edit the settings.py from django/projiproc/projiproc folder, look for the line
ALLOWED_HOSTS=[] and change it to ALLOWED_HOSTS=['192.168.1.175']
Note : replace the IP that I specified with your IP
now go to the django/prijiproc folder that contains the manage.py file and type

python manage.py migrate

Now to start server type the following

python manage.py runserver 192.168.1.175:8000

Note : my centos7.txt contains information about how to open port in firewall settings, you will have to
openport 8000, if you need to access the webapplication from other machine.
Now in the browser type the following in the address bar
http://192.168.1.175:8000 and you should see the following

Now let us create our first application. We have already discussed it in the classroom session that a
project is a collection of application (apps)

Press ctrl c to shutdown the server

stay in django/projiproc folder


django-admin starapp iprocone

necessary folder structure for iprocone will be created

now go to django/projiproc/prrojiproc folder and edit the urls.py file

and against import add import for include module, for that change the following line
from django.urls import path

to

from django.urls import path,include

now below must be a list definition for urlpatterns, insert one element at the beginning as follows
path('iprocone/',include('iprocone.urls')),
Now move to django/projiproc/iprocone folder and create a file named as urls.py
The contents of the file should be as shown below

urls.py (django/projiproc/iprocone folder)


from django.urls import path
from . import views
urlpatterns=[path('',views.index,name='index')]

Now in the same folder resides a file by the name of views.py, edit it and add the following to it

from django.http import *


def index(request):
return HttpResponse('django app1 iproc one home page');

now move to django/projiproc folder and run the server as done earlier

python manage.py runserv192.168.1.175:8000

and in the address bar of the browser type

http://192.168.1.175:8000/iprocone

and you should see the message ( django app1 iproc one home page )

Thats it. We have just now learned how to setup and django project + app. Now lets start building our
project.

Exit from the virtual environment, now let us install postgre on cent os

Install POST GRE SQL


yum install postgresql-server postgresql-contrib
postgresql-setup initdb
systemctl start postgresql
systemctl enable postgresql → this is for starting postgresql on boot

A user named as postgres automatically gets added on linux


set its password using
passwd postgres → this password is being set for the linux user postgres

su – postgres → now you will be logged in as postgres (linux user)

now lets move into the postgres shell, for that type

psql

postgres=# will appear as postgres shell prompt


create a database named as projiprocdb by typing → (Note : if you are doing practicals at my place, I
will create the necessary database /user for you and will give you its access, you don't need to to that)
create database projiprocdb;

Now let us create a user named as projiprocuser with password as projiprocuser

CREATE USER projiprocuser WITH PASSWORD 'projiproc';

a user / role will be created by the name of projiprocuser

ALTER ROLE projiprocuser SET client_encoding TO 'utf8'; → important for django


ALTER ROLE projiprocuser SET default_transaction_isolation TO 'read committed';
ALTER ROLE projiprocuser SET timezone TO 'UTC';

GRANT ALL PRIVILEGES ON DATABASE projiprocdb TO projiprocuser;

Now let us change the postgre sql peer authentication system, so that the linux user account need not
match the postgre account as it will be quite irritating for us

find a file pg_hba.conf, for that type the following

find / -name pg_hba.conf


see where it resides (in my case I got the path → /var/lib/pgsql/data/pg_hba.conf
edit it and look for the first word peer

the lines must be as follows

local all all peer

replace peer with md5 and on the next two lines replace ident with md5

now restart the postgre sql service, by typing


service postgresql restart

Now login into the psql shell by typing

psql -Uprojiprocuser -dprojiprocdb -W

when prompted for passport, provide the password that we have set (projiproc)
and you should see the psql shell prompt as
projiprocdb=#

\q to quit out of the shell

Now activate the django virtual environment by typing this from the parent folder of django

source django/bin/activate

now let us install a module required for postgre while staying in the enabled virtual environment

pip3 install psycopg2

Now let us configure the (projiproc) project settings to use the database we created

move to django/proiproc/projiproc folder


edit the settings.py and find the DATABASES entry
It right now contains the default database as sqlite, we need to set it to postgresql
change it to the following

DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'projiprocdb',
'USER': 'projiprocuser',
'PASSWORD': 'projiproc',
'HOST': 'localhost',
'PORT': ''
}
}
make one more change to settings.py
insert this string as the first elements againts the list (INSTALLED_APPS)

'iprocone.apps.IproconeConfig', → first alphabet of the app uppercased then rest followed


b Config, this has been discussed in classroom session

at my end it now looks as follows

INSTALLED_APPS = [
'iprocone.apps.IproconeConfig',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]

now we will create our model, our object is that we want a table by the name of member with fields as
follows
some id as primary key and it should be automatically assigned by postgre
email_id char(100) not null unique
name char(100) not null
requested_at datetime not null
uploaded_file char(100) not null
processing_time integer not null

Now instead of creating a table and then mapping a model with it, we will create model and will ask
django to migrate the model to relevant table, which means that the framework will login into the
postgre sql and will issue necessary sql statement to create the tables to represent the models in our
application.

Edit the /django/projiproc/iprocone/models.py and set the contents as follows

from django.db import models

# Create your models here.


class Member(models.Model):
email_id=models.CharField(max_length=100)
name=models.CharField(max_length=35)
requested_at=models.DateTimeField('Request at')
uploaded_file=models.CharField(length=100)
processing_time=models.IntegerField()
action=models.CharField(max_length=200)

Now let us activate this model, which means that create a table that would correspond to this model
(Member)
now move to the folders that contains manage.py (django\projiproc) and type

python manage.py makemigrations

if there are no typing mistakes then you should get to see -Create Model Member as the lart part of the
output.

Now see the contents of iprocone/migrations folder, you should see a file by the name of
0001_initial.py
now type

python manage.py sqlmigrate iprocone 0001

you should see the create table statement. Don't worry about the field type varchar(35) instead of
char(35) and output may vary according to RDBMS.
Now type the following to generate the necesssary table.

python manage.py migrate

Now login to the postgres sql using projiprocuser (account name), password (projiprocuer) and
database a (projiproc)

psql -Uprojiprocuser -dprojiprocdb -W

provide password and at the psql shell type \d and in the list you should see iprocone_member table.
Type \d iprocone_member and you will get to see the field details.
Type \q to quite from psql shell

Now let us create an admin account for this project, for that type

python manage.py createsuperuser

use common sense and feed username/password accordingly

Now start server as we did earlier and in the browser's address bar type

http://192.168.1.175:8000/admin

Provide username and password and you can see the admin home page
Now shutdown the server and login into postgresql psql shell as done earlier and see the list of tables,
and you will see that django has created many tables related to user and groups
Now let us move ahead with our project.

Now let us start building our pages

In iprocone folder create a folder name as static

move to the static folder and type


wget "http://tm-certificates.com/iproconeresources.zip"

the zip file will be downloaded, unzip it using

unzip iproconeresources.zip

the necessay folders will be created for bootstrap/fontawsome/popper and jquery


create a folder named as css in static folder
in it create the following styles.css file
Note : Gap between lines is just for clarity

styles.css (location iprocone/static/css)

@import "https://fonts.googleapis.com/css?family=Poppins:300,400,500,600,700";

body {

font-family: 'Poppins', sans-serif;

background: #fafafa;

p{

font-family: 'Poppins', sans-serif;

font-size: 1.1em;

font-weight: 300;

line-height: 1.7em;

color: #999;

a, a:hover, a:focus {

color: inherit;
text-decoration: none;

transition: all 0.3s;

.navbar {

padding: 15px 10px;

background: #fff;

border: none;

border-radius: 0;

margin-bottom: 40px;

box-shadow: 1px 1px 3px rgba(0, 0, 0, 0.1);

.navbar-btn {

box-shadow: none;

outline: none !important;

border: none;

.line {

width: 100%;

height: 1px;

border-bottom: 1px dashed #ddd;

margin: 40px 0;

/* ---------------------------------------------------
* SIDEBAR STYLE

* ----------------------------------------------------- */

.wrapper {

display: flex;

width: 100%;

align-items: stretch;

perspective: 1500px;

#sidebar {

min-width: 250px;

max-width: 250px;

background: #000;

color: #fff;

transition: all 0.6s cubic-bezier(0.945, 0.020, 0.270, 0.665);

transform-origin: bottom left;

#sidebar.active {

margin-left: -250px;

transform: rotateY(100deg);

#sidebar .sidebar-header {

padding: 20px;
background: #003366;

#sidebar ul.components {

padding: 20px 0;

border-bottom: 1px solid #fff;

#sidebar ul p {

color: #fff;

padding: 10px;

#sidebar ul li a {

padding: 10px;

font-size: 1.1em;

display: block;

#sidebar ul li a:hover {

color: #7386D5;

background: #fff;

#sidebar ul li.active > a, a[aria-expanded="true"] {

color: #000;

background: #97CBFF;

}
a[data-toggle="collapse"] {

position: relative;

.dropdown-toggle::after {

display: block;

position: absolute;

top: 50%;

right: 20px;

transform: translateY(-50%);

ul ul a {

font-size: 0.9em !important;

padding-left: 30px !important;

background: #6d7fcc;

ul.CTAs {

padding: 20px;

ul.CTAs a {

text-align: center;

font-size: 0.9em !important;


display: block;

border-radius: 5px;

margin-bottom: 5px;

a.download {

background: #fff;

color: #7386D5;

a.article, a.article:hover {

background: #6d7fcc !important;

color: #fff !important;

/* ---------------------------------------------------

* CONTENT STYLE

* ----------------------------------------------------- */

#content {

width: 100%;

padding: 20px;

min-height: 100vh;

transition: all 0.3s;

}
#sidebarCollapse {

width: 40px;

height: 40px;

background: #f5f5f5;

cursor: pointer;

#sidebarCollapse span {

width: 80%;

height: 2px;

margin: 0 auto;

display: block;

background: #555;

transition: all 0.8s cubic-bezier(0.810, -0.330, 0.345, 1.375);

transition-delay: 0.2s;

#sidebarCollapse span:first-of-type {

transform: rotate(45deg) translate(2px, 2px);

#sidebarCollapse span:nth-of-type(2) {

opacity: 0;

#sidebarCollapse span:last-of-type {

transform: rotate(-45deg) translate(1px, -1px);

}
#sidebarCollapse.active span {

transform: none;

opacity: 1;

margin: 5px auto;

/* ---------------------------------------------------

* MEDIAQUERIES

* ----------------------------------------------------- */

@media (max-width: 768px) {

#sidebar {

margin-left: -250px;

transform: rotateY(90deg);

#sidebar.active {

margin-left: 0;

transform: none;

#sidebarCollapse span:first-of-type,

#sidebarCollapse span:nth-of-type(2),

#sidebarCollapse span:last-of-type {

transform: none;

opacity: 1;

margin: 5px auto;

}
#sidebarCollapse.active span {

margin: 0 auto;

#sidebarCollapse.active span:first-of-type {

transform: rotate(45deg) translate(2px, 2px);

#sidebarCollapse.active span:nth-of-type(2) {

opacity: 0;

#sidebarCollapse.active span:last-of-type {

transform: rotate(-45deg) translate(1px, -1px);

.centered {

position: fixed;

z-index: 999;

height: 2em;

width: 2em;

overflow: show;

margin: auto;

top: 0;

left: 0;

bottom: 0;

right: 0;

}
.imageEditor {

margin: auto;

top: 0;

left: 0;

bottom: 0;

right: 0;

padding: 20px;

border: 2px solid gray;

max-height:800px;

max-width:800px;

.currentDate {

float:right;

padding-top:5px;

padding-right:5px;

font-size: 16pt;

.topBar{

height:40px;

background: #43464B;

color: white;

margin-bottom:10px;

.nav-company{

font-size:20pt;
position: fixed;

margin-left:40px;

.page-footer{

color: #003336;

#spinnerWrap {

position: fixed;

width: 100%;

height:100%;

display: flex;

background: rgba(0, 0, 0, 0.91);

top: 0;

.spinnerIcon {

margin: auto;

color: #fff;

text-align: center;

font-size:40pt;

.imageFileName {

float: left;

padding-top:5px;
padding-left:5px;

font-size: 16pt;

in iprocone folder create a folder named as templates


in templates folder create the following index.html file

index.html (location iprocone/templates folder)

{% load static %}

<!DOCTYPE html>

<html>

<head>

<meta charset="utf-8">

<meta name="viewport" content="width=device-width, initial-scale=1.0">

<meta http-equiv="X-UA-Compatible" content="IE=edge">

<title>Thinking Machines - ImageProcessor</title>

<!-- Bootstrap CSS CDN -->

<link rel="stylesheet" type='text/css' href="{% static 'bootstrap-4/css/bootstrap.min.css' %}">

<!-- Our Custom CSS -->

<link rel="stylesheet" href="{% static 'css/styles.css' %}">

<!-- Font Awesome JS -->

<script defer src="{% static 'fontawesome/solid.js' %}"></script>

<script defer src="{% static 'fontawesome/fontawesome.js' %}"></script>

<script>

function ViewState()

this.state='none'; // other states -> open | opening


this.fileName='';

this.name='';

this.email='';

var viewState=new ViewState();

var openFileDivision=null;

var clientArea=null;

function initializeState()

$.ajax({

url: "getState",

type: "GET",

cache: false,

success: function (res) {

viewState=res;

updateView();

});

function updateView()

if(clientArea==null) clientArea=$('#clientArea');

if(openFileDivision==null) openFileDivision=$('#openFileDivision');

if(viewState.state=='none')

$('#sidebar').css('visibility','hidden');

$('#sidebarCollapse').css('visibility','hidden');
$('#sidebar').hide();

$('#sidebarCollapse').hide();

$('#sidebar').css('display','none');

$('#sidebarCollapse').css('display','none');

clientArea.html(openFileDivision);

$('#fileOptions').css('visibility','hidden');

$('#topBar').css('visibility','hidden');

if(viewState.state=='opening')

$('#clientArea').html('<i class="fa fa-spinner fa-spin centered" style="font-size:24px"></i>');

if(viewState.state=='open')

$('#sidebar').css('visibility','visible');

$('#sidebarCollapse').css('visibility','visible');

$('#sidebar').css('display','');

$('#sidebarCollapse').css('display','');

$('#sidebar').show();

$('#sidebarCollapse').show();

$('#fileOptions').css('visibility','visible');

$('#topBar').css('visibility','visible');

$('#clientArea').html("<img class='imageEditor' src='/iprocone/getImage?&xcsdf="+encodeURI(new Date())


+"'>");

function closeFile()
{

viewState.state='none';

updateView();

$.ajax({

url: "closeFile",

type: "GET",

cache: false,

success: function (res) {

// do nothing

});

function openFile()

var openFileForm=document.getElementById('openFileForm');

var formData=new FormData(openFileForm);

viewState.state='opening';

updateView();

$('#spinnerWrap').css('display','');

$('#spinnerWrap').css('visibility','visible');

$('#spinnerWrap').show();

$.ajax({

url: "openFile",

type: "POST",

data: formData,

enctype: 'multipart/form-data',

processData: false,
contentType: false,

cache: false,

success: function (res) {

viewState.state='open';

viewState.fileName=res.fileName;

viewState.email=res.email;

viewState.name=res.name;

openFileForm.reset();

updateView();

$('#spinnerWrap').css('display','none');

$('#spinnerWrap').css('visibility','hidden');

$('#spinnerWrap').hide();

$('#imageFileName').html('Image : '+viewState.fileName);

});

function toGrayscale()

$('#spinnerWrap').css('display','');

$('#spinnerWrap').css('visibility','visible');

$('#spinnerWrap').show();

$.ajax({

url: "toGrayscale",

type: "GET",

cache: false,

success: function (res) {

updateView();
$('#spinnerWrap').css('display','none');

$('#spinnerWrap').css('visibility','hidden');

$('#spinnerWrap').hide();

});

</script>

</head>

<body>

<div class="wrapper">

<!-- Sidebar Holder -->

<nav id="sidebar" style='visibility:hidden;display:none'>

<div class="sidebar-header">

<h3>iMagic</h3>

</div>

<ul class="list-unstyled components" id='imageProcessingOptions'>

<p>Image Processing</p>

<li>

<a href="javascript:toGrayscale()">To Grayscale</a>

</li>

<li>

<a href="javascript:$('#scaleItModal').modal('show')">Scale It</a>

</li>

<li>

<a href="#">Set Border</a>

</li>
<li><a href='#'>Many more .........</a>></li>

</ul>

</nav>

<!-- Page Content Holder -->

<div id="content">

<nav id='navigationBar' class="navbar navbar-expand-lg navbar-light bg-light">

<div class="container-fluid">

<button type="button" id="sidebarCollapse" class="navbar-btn"


style='visibility:hidden;display:none'>

<span></span>

<span></span>

<span></span>

</button>

<span class='nav-company'>Thinking Machines</span>

<span id='fileOptions' style='visibility:hidden'>

<button class="btn btn-dark d-inline-block d-lg-none ml-auto" type="button" data-toggle="collapse"


data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-
label="Toggle navigation">

<i class="fas fa-align-justify"></i>

</button>

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

<ul class="nav navbar-nav ml-auto">

<li class="nav-item active" >

<a class="nav-link" href="javascript:closeFile()">Close file</a>


</li>

</ul>

</div>

</span>

</div>

</nav>

<div id='topBar' class='topBar' style='visibility:hidden'>

<span class='imageFileName' id='imageFileName'></span>

<span class='currentDate'>{{ today }}</span>

</div>

<div id='clientArea'>

<div id='openFileDivision'>

<h3>Open file and let the magic begin</h3>

<form id='openFileForm' enctype="multipart/form-data">

<div class='form-group'>

{% csrf_token %}

<label for='email'>Email Id.</label>

<input class='form-control' type='text' id='email' name='email'>

</div>

<div class='form-group'>

<label for='name'>Name</label>

<input class='form-control' type='text' id='name' name='name'>

</div>

<div class='form-group'>

<input class='form-control' type='file' id='fileName' name='fileName' accept='image/*'>

</div>

<button type='button' onclick='openFile()' class='btn btn-primary'>Open file</button>


</form>

</div> <!-- open file div end -->

</div> <!-- client area ends -->

<div class="line"></div>

<footer class="page-footer">

<!-- Copyright -->

<div class=" text-center">© 2018 Copyright:

<a href="http://thinkingmachines.in/"> Thinking Machines</a>

</div>

<!-- Copyright -->

</footer>

</div>

</div>

<div id="spinnerWrap" style='visibility:hidden;display:none'>

<div class="spinnerIcon">

Loading<br/>

<i class="fa fa-spinner fa-spin" style="font-size:48px"></i>

</div>

</div>

<div class="modal fade" id="scaleItModal">

<div class="modal-dialog modal-dialog-centered">

<div class="modal-content">
<!-- Modal Header -->

<div class="modal-header">

<h4 class="modal-title">Scale It</h4>

<button type="button" class="close" data-dismiss="modal">&times;</button>

</div>

<!-- Modal body -->

<div class="modal-body">

<form id='scaleItForm' class='form-horizontal'>

<div class='form-group'>

{% csrf_token %}

<label for='width'>Width %</label>

<input class='form-control' type='number' min='-10' max='200' step='1' value='100' id='height' name='width'>

</div>

<div class='form-group'>

<label for='height'>Height %</label>

<input class='form-control' type='number' min='-10' max='200' step='1' value='100' id='height' name='height'>

</div>

<div class='form-group'>

<label for='maintainAspectRation'>Maintain Aspect Ratio</label>

<input class='form-control' type='checkbox' checked id='maintainAspectRatio' name='maintainAspectRation' >

</div>

</form>

</div>

<!-- Modal footer -->


<div class="modal-footer">

<button type="button" class="btn btn-primary">Scale it</button>

<button type="button" class="btn btn-danger" data-dismiss="modal">Close</button>

</div>

</div>

</div>

</div>

<!-- jQuery CDN - Slim version (=without AJAX) -->

<script src="{% static 'jquery-3.3.1/jquery.min.js' %}"></script>

<!-- Popper.JS -->

<script src="{% static 'popper/popper.min.js' %}"></script>

<!-- Bootstrap JS -->

<script src="{% static 'bootstrap-4/js/bootstrap.min.js' %}"></script>

<script type="text/javascript">

$(document).ready(function () {

$('#sidebarCollapse').on('click', function () {

$('#sidebar').toggleClass('active');

$(this).toggleClass('active');

});

});

$.ajaxSetup({

beforeSend: function(xhr, settings) {

function getCookie(name) {
var cookieValue = null;

if (document.cookie && document.cookie != '') {

var cookies = document.cookie.split(';');

for (var i = 0; i < cookies.length; i++) {

var cookie = jQuery.trim(cookies[i]);

// Does this cookie string begin with the name we want?

if (cookie.substring(0, name.length + 1) == (name + '=')) {

cookieValue = decodeURIComponent(cookie.substring(name.length + 1));

break;

return cookieValue;

if (!(/^http:.*/.test(settings.url) || /^https:.*/.test(settings.url))) {

// Only send the token to relative URLs i.e. locally.

xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken'));

});

window.addEventListener('load',initializeState);

</script>

</body>

</html>

following is the urls.py in iprocone folder


urls.py (location iprocone folder)
from django.urls import path

from . import views

urlpatterns=[ path('',views.index,name='index'),

path('openFile',views.openFile,name='openFile'),

path('getImage',views.getImage,name='getImage'),

path('toGrayscale',views.toGrayscale,name='toGrayscale'),

path('getState',views.getState,name='getState'),

path('closeFile',views.closeFile,name='closeFile'),

in django/projiproc folder create a folder named as filestore


move to django/projiproc/projiproc folder

edit the urls.py as make its contents as follows

urls.py (django/projiproc/projiproc) folder

"""projiproc URL Configuration

The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/2.1/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.urls import include, path
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path,include

urlpatterns = [
path('iprocone/',include('iprocone.urls')),
path('admin/', admin.site.urls),
]

following is the settings.py in the django/projiproc/projiproc folder

settings.py (location django/projiproc/projiproc folder)


"""
Django settings for projiproc project.

Generated by 'django-admin startproject' using Django 2.1.2.

For more information on this file, see


https://docs.djangoproject.com/en/2.1/topics/settings/

For the full list of settings and their values, see


https://docs.djangoproject.com/en/2.1/ref/settings/
"""

import os

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)


BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

# Quick-start development settings - unsuitable for production


# See https://docs.djangoproject.com/en/2.1/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'ncu#i0esnc5r(f&ju0y-iotex2u0fkgc2j-mz8f2z1qqb@#7m$'

# SECURITY WARNING: don't run with debug turned on in production!


DEBUG = True

ALLOWED_HOSTS = ['192.168.1.175']

# Application definition

INSTALLED_APPS = [
'iprocone.apps.IproconeConfig',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]

MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

ROOT_URLCONF = 'projiproc.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]

WSGI_APPLICATION = 'projiproc.wsgi.application'

# Database
# https://docs.djangoproject.com/en/2.1/ref/settings/#databases

DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'projiprocdb',
'USER': 'projiprocuser',
'PASSWORD': 'projiproc',
'HOST': 'localhost',
'PORT': ''
}
}
# Password validation
# https://docs.djangoproject.com/en/2.1/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]

# Internationalization
# https://docs.djangoproject.com/en/2.1/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/2.1/howto/static-files/
STATIC_URL = '/static/'
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR,'filestore')
Now the last part, edit the views.py in iprocone folder, I am providing the functions (without code) but
with what to do)

Complete it

views.py
from django.shortcuts import render
import datetime
from django.http import *
from django.core.files.storage import FileSystemStorage
import uuid
import os
import cv2
from pathlib import Path
def index(request):
today=datetime.datetime.now()
return render(request,'index.html',{
"today": today.strftime("%d-%m-%Y")
})

def isFileOpen(request):
Check that stack name email and fileName exists in session, if all exists return True
else remove the ones that exists and return False

def getState(request):
Call isFileOpen, if it sends back true then extract name,email,fileName return the response as follows
return JsonResponse({'state': 'open','name': name,'email': email,'fileName':fileName})
else return the following response

return JsonResponse({'state':'none','name':'','email':'','fileName':''})

def openFile(request):
check if the request is of type POST and file 'fileName' has been uploaded or not. Check the
request.FILES part
If not then do nothing, we don't care that nothing happens on the client side
if yes then extract data against 'fileName' from request.FILES[]
use FileSystemStorage to store the file, it will give back the actual new name
extract email,name from request.POST[]
ask save method FileStorage class to save the contents of the imageFile by the name of the file being
uploaded (use imageFile.name), the save method will return the actual name of the uploaded file.
Trap it as imageFileName
set the session expiry time (10 hours)
ceate a list() as stack and insert the imageFileName at top
keep (stack as 'stack',name as 'name',email as 'email' and imageFile.name as 'fileName') in session
then return JsonResponse({'fileName':imageFile.name})

def getImage(request):
if request.method=="GET" and request.session.has_key('stack'):
stack=request.session['stack']
if len(stack)>0:
fileToServe=os.path.abspath(os.path.join(os.path.dirname( __file__ ), '..', 'filestore/%s'%stack[0]))
return FileResponse(open(fileToServe,'rb'))
return HttpResponse('')

def closeFile(request):
check if session has a key named as stack
if yes then extract the list, traverse it
create absolute path (/home/django/projiproc/filestore/name_of_file_to_delete) on every iteration and
delete the file from file system
then delete the stack/name/email/fileName and whatever you must have kept, from the session

then return JsonResponse({'response':'closed'})

def toGrayscale(request):
check if stack exists in session, if yes extract the zeroth element from the stack, create a string that
would contain the absolute path of the zeroth index element
extract its extension
generate a new unique string (use uuid module)
attach the extension
ask opencv function to open the original file
convert it to grayscale and save it by newly generated namee
insert the new name on stack
keep the stack in session
then return JsonResponse({'response':'convertedToGrayscale'})
if stack doesn't exist in session then return HttpResponse('')

Run the server and view the webapplication

http://192.168.1.175:8000/iprocone and you should see whatever you saw in the classroom session

Potrebbero piacerti anche