Flask Internship Report
Flask Internship Report
1
CEREBRA SOFTWARE AND CONSULTANCY COMPANY
Certification of Completion
2
ADI KAVI NANNAYA UNIVERSITY RAJAMAHENDRAVARAM
UNIVERSITY COLLEGE of ENGINEERING
DECLARATION
I, declare that . . .
The work contained in this report is original and has been done by me under the guidance of my supervisor.
The work has not been submitted to any other institute for any Degree or Diploma. I have followed the
guidelines provided by the University in preparing the report.
I have confirmed to the norms and guidelines given in the Ethical code of the Conduct of the University.
3
ADI KAVI NANNAYA UNIVERSITY RAJAMAHENDRAVARAM
UNIVERSITY COLLEGE of ENGINEERING
CERTIFICATION
This is to certify that the INTERNSHIP based on WEB DEVELOPMENT USING FLASK AND REST APIS
NANNAYA UNIVERSITY, is a record of Bonafide project work carried out by him under my supervision and
guidance and is worthy of consideration for the award of the degree of Bachelor of Technology.
4
ADI KAVI NANNAYA UNIVERSITY RAJAMAHENDRAVARAM UNIVERSITY COLLEGE
of ENGINEERING
ACKNOWLEDGEMENT
I wish to express my deep sense of gratitude to Mr.Denit Thomas , Senior Web Developer at
CEREBRA Software and IT Consultancy and also for MR.SHIVA SANKAR CEO OF CEREBRA SOFTWARE AND
CONSULTANCY, vishakapatnam for giving me an opportunity to complete my Internship on the Web
development using Flask and Rest API which helps me for the partial fulfilment of my degree in Bachelor of
Technology in Computer Science and Engineering.
I extend my sincere thanks to my mentor and guide, Dr. V.PERSIS , for introducing and making me to
meet Dr Ravi Sankar, Senior Principal Scientist, CTRI and encouraging me to complete my internship.
5
About CEREBRA COMPANY:
is Cerebra Consulting Inc is a System Integrator and IT Services Solution provider with a focus on Big Data,
Business Analytics, Cloud Solutions, Amazon Web Services, Salesforce, Oracle EBS, Peoplesoft, Hyperion,
Oracle Configurator, Oracle CPQ, Oracle PLM and Custom Application Development. Utilizing solid business
experience, industry-specific expertise, and proven methodologies, we consistently deliver measurable
results for our customers. Cerebra has partnered with leading enterprise software companies and cloud
providers such as Oracle, Salesforce, Amazon and able to leverage these partner relationships to deliver
high-quality, end-to-end customer solutions that are targeted to the needs of each customer.
To disseminate the information and knowledge and technologies developed by the institute, it is necessary
to develop a web portal for global accessing. The web portal should contain the information on research
activities of CTRI on tobacco, advisories to farmers, facilities available, package of practices, varieties
developed and staff information. By accessing this web portal, farmers can get the knowledge on
management of pests and diseases, curing and grading and other parameters required for growing of the
tobacco crop in a beneficial way.
6
INDEX
1 Introduction 9
3 Platforms 12-13
6 Implementation
6.1) Technologies Used 31
7 Testing
7.1) Introduction 40-42
9 Bibliography 49
7
CHAPTER 1
INTRODUCTION
Web development refers in general to the tasks associated with developing websites for
hosting via intranet or internet. The web development process includes web design, web
content development, client-side/server-side scripting and network security configuration,
among other tasks.
In a broader sense, web development encompasses all the actions, updates, and operations
required to build, maintain and manage a website to ensure its performance, user experience,
and speed are optimal.
It might also, but not necessarily, include all those strategic actions needed to ensure its proper
ranking on search engine results. Usually, those tasks pertain to a different specialization,
namely search engine optimization (SEO)
Web development is also known as website development, while the professionals that
maintain a website are called web developers or (more commonly) web devs.
CHAPTER -2
REST APIS
8
What is REST?
REST stands for Representational State Transfer. It’s a software architectural style for
implementing web services. Web services implemented using the REST architectural style are
known as the RESTful Web services.
REST API:
A REST API is an API implementation that adheres to the REST architectural constraints. It acts
as an interface. The communication between the client and the server happens over HTTP.
A REST API takes advantage of the HTTP methodologies to establish communication between
the client and the server. REST also enables servers to cache the response that improves the
application’s performance.
The communication between the client and the server is a stateless process. By that, I mean
every communication between the client and the server is like a new one.
There is no information or memory carried over from the previous communications. So, every
time a client interacts with the backend, the client has to send the authentication information
9
to it as well. This enables the backend to figure out whether the client is authorized to access
the data or not.
When implementing a REST API the client communicates with the backend endpoints. This
entirely decouples the backend and the client code.
REST endpoint:
An API/REST/Backend endpoint means the URL of a service. For
example, https://myservice.com/users/{username} is a backend endpoint for fetching the user
details of a particular user from the service.
The REST-based service will expose this URL to all its clients to fetch the user details using the
above stated URL.
API gateway:
authentication, sanitizing the input data, and other necessary tasks before providing access to
the application resources.
10
CHAPTER-3
PLATFORMS
11
Platforms used:
Languages: Python, Json
Code platform: Pycharm
Rest API platform: Using Postman
Uploading code: Into GitHub
PYCHARM:
PyCharm is an integrated development environment (IDE) used in computer programming,
specifically for the Python language. It is developed by the Czech company JetBrains (formerly
known as IntelliJ).[5] It provides code analysis, a graphical debugger, an integrated unit tester,
integration with version control systems (VCSes), and supports web development with Django
as well as data science with Anaconda.
PyCharm is cross-platform, with Windows, macOS and Linux versions. The Community Edition is
released under the Apache License, and there is also Professional Edition with extra features –
released under a proprietary license.
FEATURES:
Coding assistance and analysis, with code completion, syntax and error
highlighting, linter integration, and quick fixes
Project and code navigation: specialized project views, file structure views and
quick jumping between files, classes, methods and usages
Python refactoring: includes rename, extract method, introduce variable,
introduce constant, pull up, push down and others
Support for web frameworks: Django, web2py and Flask [professional edition
only]
Integrated Python debugger
Integrated unit testing, with line-by-line code coverage
Google App Engine Python development [professional edition only]
Version control integration: unified user interface
for Mercurial, Git, Subversion, Perforce and CVS with change lists and merge
Support for scientific tools like matplotlib, numpy and scipy [professional
edition only]
PLUGINS:
PyCharm provides an API so that developers can write their own plugins to extend PyCharm
features. Several plugins from other JetBrains IDE also work with PyCharm. There are more
than 1000 plugins which are compatible with PyCharm.
12
LINKS:
PYCHARM HOME PAGE: https://www.jetbrains.com/pycharm/
13
CHAPTER-4
POSTMAN:
Postman is an API (application programming interface) development tool which helps to build, test and
modify APIs. Almost any functionality that could be needed by any developer is encapsulated in this tool.
It is used by over 5 million developers every month to make their API development easy and simple. It has
the ability to make various types of HTTP requests (GET, POST, PUT, PATCH), saving environments for later
use, converting the API to code for various languages (like JavaScript, Python).
to communicate with each other. We use APIs whenever we use an application like Twitter,
Facebook, sending text messages, or checking the weather over the phone.
HTTP:
HTTP (Hypertext Transfer Protocol) is the collection of rules for the transmission of data on the World
Wide Web, like graphic images, text, video, sound, and other multimedia data. The Web users
implicitly make use of HTTP as soon as they open their Web Browser. HTML Tutorial
Example: A user or browser enters the HTTP request to the server; the server then returns the user
14
response. This response includes the request status information and may consist of the requested
material as well.
The most commonly used HTTP methods are GET, POST, PUT, PATCH, HEAD, DELETE, and OPTIONS.
users, Postman has become a tool of convenience. Following are the reasons why Postman is used:
1. Accessibility- One can use it anywhere after installing Postman into the device by simply logging
in to the account.
2. Use Collections-Postman allows users to build collections for their API-calls. Every set can
create multiple requests and subfolders. It will help to organize the test suites.
3. Test development- To test checkpoints, verification of successful HTTP response status shall
the Collection Runner or Newman, which saves time for repeated tests.
as one can use the same collection but for a different setting.
6. Debugging- To effectively debug the tests, the postman console helps to track what data is
being retrieved.
7. Collaboration- You can import or export collections and environments to enhance the sharing
files. You may also use a direct connection to share the collections.
LINK:
This link is used for downloading the postman app : https://www.postman.com/downloads/
15
CHAPTER-5
Creating Requests:
Let's create a new request in Postman. In the request, we can have many details. And during this
request creation process, you have to enter a URL and select the method. Other than you can
Step 2: Click on New option from the top left corner of the Postman homepage window. Once you
19.1M
398
HTML Tutorial
16
Step 4: Once you select the Request option, you will be prompted to enter the request name, and you
can also describe that API for future use. The description section is optional; we can leave it blank.
17
Step 5: Scroll down and click on + Create Collection.
18
Enter the collection Name (here, 'Collection-01' is my collection name) and click on the right mark.
19
Once you click on the save button, a new tab will open with your given request name.
20
Step 7: Enter www.javatpoint.com in the address bar and click on Send.
Once you select the Send, you will get the following response.
21
Setting Request URLs:
For sending the request, you should have a URL that defines the API endpoint. All API operation is
usually associated with an endpoint, which is a place from where these APIs can access the resources
To access the API in Postman, you need to enter the URL, and each URL contains an endpoint.
o When you create an API, usually, the URL is the base location plus path.
the base
o And if you use a third-party API, then you don't need to supply the URL, your API provider
22
Some commonly used methods are:
POST: To send the new data to an API, we can use this method.
23
CHAPTER-6
Rest API Response Codes
Here are some sample Response Codes which we will normally see while performing REST API testing over
POSTMAN or over any REST API client.
1) 100 Series:
These are temporary Responses
100 Continue
101 Switching Protocols
102 Processing
2) 200 Series:
The client accepts the Request, being processed successfully at the server.
200 – OK
201 – Created
202 – Accepted
203 – Non-Authoritative Information
204 – No Content
205 – Reset Content
206 – Partial Content
207 – Multi-Status
208 – Already Reported
226 – IM Used
3) 300 Series:
Most of the codes related to this series are for URL Redirection.
300 – Multiple Choices
301 – Moved Permanently
302 – Found
303 – Check Other
304 – Not Modified
305 – Use Proxy
306 – Switch Proxy
307 – Temporary Redirect
308 – Permanent Redirect
4) 400 Series:
These are specific to client-side error.
400 – Bad Request
401 – Unauthorised
402 – Payment Required
403 – Forbidden
404 – Not Found
405 – Method Not Allowed
406 – Not Acceptable
407 – Proxy Authentication Required
408 – Request Timeout
409 – Conflict
410 – Gone
411 – Length Required
412 – Precondition Failed
24
413 – Payload Too Large
414 – URI Too Long
415 – Unsupported Media Type
416 – Range Not Satisfiable
417 – Expectation Failed
418 – I’m a teapot
421 – Misdirected Request
422 – Unprocessable Entity
423 – Locked
424 – Failed Dependency
426 – Upgrade Required
428 – Precondition Required
429 – Too Many Requests
431 – Request Header Fields Too Large
451 – Unavailable For Legal Reasons
5) 500 Series:
These are specific to the server-side error.
500 – Internal Server Error
501 – Not Implemented
502 – Bad Gateway
503 – Service Unavailable
504 – Gateway Timeout
505 – HTTP Version Not Supported
506 – Variant Also Negotiates
507 – Insufficient Storage
508 – Loop Detected
510 – Not Extended
511 – Network Authentication Required
25
CHAPTER-7
FLASK FRAME WORK
WHAT IS FLASK:
Flask is a micro web framework written in Python. It is classified as a microframework because it does
not require particular tools or libraries. It has no database abstraction layer, form validation, or any
other components where pre-existing third-party libraries provide common functions. However, Flask
supports extensions that can add application features as if they were implemented in Flask itself.
Extensions exist for object-relational mappers, form validation, upload handling, various open
FEATURES:
Development server and debugger
Integrated support for unit testing
RESTful request dispatching
Uses Jinja templating
Support for secure cookies (client side sessions)
100% WSGI 1.0 compliant
Unicode-based
Extensive documentation
Google App Engine compatibility
Extensions available to enhance features desired
EXAMPLE:
The following code shows a simple web application that displays "Hello World!" when visited:
app = Flask(__name__)
@app.route("/")
def hello_world():
return "<p>Hello, World!</p>"
1.First we imported the Flask class. An instance of this class will be our WSGI application.
2.Next we create an instance of this class. The first argument is the name of the application’s module or
package. __name__ is a convenient shortcut for this that is appropriate for most cases. This is needed so that
Flask knows where to look for resources such as templates and static files.
3.We then use the route() decorator to tell Flask what URL should trigger our function.
26
4.The function returns the message we want to display in the user’s browser. The default content type is HTML,
so HTML in the string will be rendered by the browser.
By default, Flask does not include a database abstraction layer, form validation or anything else where different
libraries already exist that can handle that. Instead, Flask supports extensions to add such functionality to your
application as if it was implemented in Flask itself. Numerous extensions provide database integration, form
validation, upload handling, various open authentication technologies, and more. Flask may be “micro”, but it’s
ready for production use on a variety of needs.
27
CHAPTER-8
HOW TO UPLOAD CODE INTO GIT FROM PYCHARM:
Git is an open-source version control system. It means that whenever a developer develops some project (like
an app) or something, he/she constantly update it catering to the demands of users, technology, and whatsever
it maybe. Version control systems keep these revisions straight, storing the modifications in a central
repository. It allows developers to easily collaborate, as they can download a new version of the software,
make changes, and upload the newest revision. Every developer can see these new changes, download them,
and contribute. Git is used to storing the source code for a project and track the complete history of all
changes to that code, while GitHub is a cloud-based platform built around the Git tool. So it’s necessary to
upload your project on GitHub.
Step by step process to upload the Python project on GitHub from the pycharm:
Step 1: Go to VCS panel which is present on the top of pycharm and click on it. After clicking select the
“Enable Version Control Integration“.
After clicking the Enable Version Control Integration a pop up will arise like following. Then
select Git from the drop-down menu and click OK. This will initialize the project for GitHub.
Step 2: The next step is to click on the green tik present in the upper part of the pycharm. Basically this
symbol refers to Commit and what it does is it will collect all unversioned files and make them ready to
28
Update on github
After clicking this a new screen will pop up like the following. Now, first, select the unversioned files,
then input the Commit message as “Initial Commit” and then click on the Commit button.
29
Step 3: The last step to be followed is to go to VCS then select Import into Version Control and then click
on Share project on GitHub.
After clicking this a pop up will arise where the user has to enter its GitHub login id and password. After
successfully logged in to its account one more pop up will come like following where the user has to give
its Repository name and the Description of their repository. Then click on the share button and done.
Note: Don’t put blank spaces or special characters while giving the Repository name.
30
CHAPTER-9
MAIN CODE IN PYTHON:
CONTROLLER:
from flask import Flask, request
import json
app = Flask(__name__)
@app.route('/key', methods=["Get"])
def fetch_key():
return json.dumps(result)
@app.route('/encrypt', methods=["post"])
def encrypt_file():
data = request.get_json()
return json.dumps(s)
@app.route('/decrypt', methods=["post"])
def decrypt_file():
data = request.get_json()
s = {'decrypt_data': result}
return json.dumps(s)
if __name__ == "__main__":
app.run()
Above code is the main code and it saved as controller because this code controlle other code in project
Here we are using the packages from python and we have to save them as plugins in pycharm and we easily
31
import them from pychram
PACKAGES USED:
1.Flask
2.Json
3.Cryptography
4.Fernet
Json:
The full-form of JSON is JavaScript Object Notation. It means that a script (executable) file which is made of
text in a programming language, is used to store and transfer the data. Python supports JSON through a
built-in package called json. To use this feature, we import the json package in Python script. The text in
JSON is done through quoted-string which contains the value in key-value mapping within { }. It is similar to
the dictionary in Python.
json.dump()
json module in Python module provides a method called dump() which converts the Python objects into
appropriate json objects. It is a slight variant of dumps() method.
1. The dumps() is used when the objects are required to be in string format and is used for parsing,
printing, etc, .
2. The dumps() does not require any such file name to be passed.
Cryptography:
Cryptography is the practice of securing useful information while transmitting from one computer to another or
storing data on a computer. Cryptography deals with the encryption of plaintext into ciphertext and decryption
of ciphertext into plaintext. Python supports a cryptography package that helps us encrypt and decrypt data.
The fernet module of the cryptography package has inbuilt functions for the generation of the key, encryption
of plaintext into ciphertext, and decryption of ciphertext into plaintext using the encrypt and decrypt methods
respectively. The fernet module guarantees that data encrypted using it cannot be further manipulated or read
without the key.
32
METHODS:
1.generate_key() : This method generates a new fernet key. The key must be kept safe as it is the most
important component to decrypt the ciphertext. If the key is lost then the user can no longer decrypt the
message. Also if an intruder or hacker gets access to the key they can not only read the data but also
forge the data.
2.encrypt(data) : It encrypts data passed as a parameter to the method. The outcome of this encryption is
known as a “Fernet token” which is basically the ciphertext. The encrypted token also contains the current
timestamp when it was generated in plaintext. The encrypt method throws an exception if the data is not
in bytes.
PARAMETERS:
1.data (bytes) – The plaintext to be encrypted.
2.Return value: A ciphertext that cannot be read or altered without the key. It is URL-safe base64-encoded
and is referred to as Fernet token.
3.decrypt(token,ttl=None) : This method decrypts the Fernet token passed as a parameter to the method.
On successful decryption the original plaintext is obtained as a result, otherwise an exception is thrown.
SERVEICE :
from cryptography.fernet import Fernet
import json
fernet = Fernet(key)
enc = fernet.encrypt(content.encode())
return enc
def decrypt_file(enc,key):
fernet = Fernet(key)
dec = fernet.decrypt(enc).decode()
return dec
33
def fetch_key():
key = Fernet.generate_key()
return key
34