October 16, 2018

Srikaanth

CherryPy Latest Most Frequently Asked Interview Questions Answers

What Is Cherrypy?

CherryPy is a web framework of Python which provides a friendly interface to the HTTP protocol for Python developers. It is also called a web application library.

CherryPy uses Python’s strengths as a dynamic language to model and bind HTTP protocol into an API. It is one of the oldest web frameworks for Python, which provides clean interface and reliable platform.

What Is Multithreaded Application Server?

CherryPy is designed based on the multithreading concept. Every time a developer gets or sets a value into the CherryPy namespace, it is done in the multi-threaded environment.

Both cherrypy.request and cherrypy.response are thread-data containers, which imply that your application calls them independently by knowing which request is proxied through them at runtime.

Application servers using the threaded pattern are not highly regarded because the use of threads is seen as increasing the likelihood of problems due to synchronization requirements.

What Are The Other Alternatives Include?

Multi-process Pattern: Each request is handled by its own Python process. Here, performance and stability of the server can be considered as better.

Asynchronous Pattern: Here, accepting new connections and sending the data back to the client is done asynchronously from the request process. This technique is known for its efficiency.

URL Dispatching: The CherryPy community wants to be more flexible and that other solutions for dispatchers would be appreciated. CherryPy 3 provides other built-in dispatchers and offers a simple way to write and use your own dispatchers.

Applications used to develop HTTP methods. (GET, POST, PUT, etc.)
The one which defines the routes in the URL – Routes Dispatcher
HTTP Method Dispatcher

In some applications, URIs are independent of the action, which is to be performed by the server on the resource.

For example,http://xyz.com/album/delete/10

The URI contains the operation the client wishes to carry out.

By default, CherryPy dispatcher would map in the following way

album.delete(12)
Routes Dispatcher.
CherryPy Latest Most Frequently Asked Interview Questions Answers
CherryPy Latest Most Frequently Asked Interview Questions Answers

Here is a list of the parameters for the method required in dispatching:

The name parameter is the unique name for the route to connect.
The route is the pattern to match URIs.
The controller is the instance containing page handlers.
Using the Routes dispatcher connects a pattern that matches URIs and associates a specific page handler.

What Is Cherrypy Environment Setup?

CherryPy comes in packages like most open-source projects, which can be downloaded and installed in various ways which are mentioned as follows:

Using a Tarball
Using easy_install
Using Subversion

What Are The Basic Requirements For Installation Of Cherrypy Framework Include?

The basic requirements for installation of CherryPy framework include:

Python with version 2.4 or above
CherryPy 3.0
Installing a Python module is considered an easy process. The installation includes the use of the following commands.

python setup.py build
python setup.py install

The packages of Python are stored in the following default directories:

On UNIX or Linux,
/usr/local/lib/python2.4/site-packages
or
/usr/lib/python2.4/site-packages
On Microsoft Windows,-- C:Python or C:Python2x
On Mac OS,---Python:Lib:site-package

How To Installation Using Tarball?

A Tarball is a compressed archive of files or a directory. The CherryPy framework provides a Tarball for each of its releases (alpha, beta, and stable).

It contains complete source code of the library. The name comes from the utility used in UNIX and other operating systems.

Here are the steps to be followed for the installation of CherryPy using tar ball:

Step 1 − Download the version as per user requirements

Step 2 − Search for the directory where Tarball has been downloaded and uncompress it. For Linux operating system, type the following command: tar zxvf cherrypy-x.y.z.tgz

For Microsoft Windows, the user can use a utility such as 7-Zip or Winzip to uncompress the archive via a graphical interface.

Step 3 − Move to the newly created directory and use the following command to build CherryPy: python setup.py build

For the global installation, the following command should be used: python setup.py install

What Is History Of Cherrypy?

Remi Delon released the first version of CherryPy in late June 2002. This was the starting point of a successful Python web library. Remi is a French hacker who has trusted Python for being one of the greatest alternatives for web application development.

The project developed by Remi attracted a number of developers who were interested in the approach. The approach included the following features

CherryPy was close to the model-view-controller pattern.
A CherryPy class has to be processed and compiled by the CherryPy engine to produce a self-contained Python module embedding the complete application and also its own built-in web server.
CherryPy can map a URL and its query string into a Python method call

What Are The Strengths Of Cherrypy?

The following features of CherryPy are considered as its strengths:

Simplicity: Developing a project in CherryPy is a simple task with few lines of code developed as per the conventions and indentations of Python.

CherryPy is also very modular. The primary components are well managed with correct logic concept and parent classes are expandable to child classes.

Power: CherryPy leverages all the power of Python. It also provides tools and plugins, which are powerful extension points needed to develop world-class applications.

Open-source: CherryPy is an open-source Python Web Framework (licensed under the open-source BSD license), which means this framework can be used commercially at ZERO cost.

Community Help: It has a devoted community which provides complete support with various types of questions and answers. The community tries to give complete assistance to the developers starting from the beginner level to the advanced level.

Deployment: There are cost effective ways to deploy the application. CherryPy includes its own production-ready HTTP server to host your application. CherryPy can also be deployed on any WSGI-compliant gateway.

How To Installation Using Easy_install?

Python Enterprise Application Kit (PEAK) provides a python module named Easy Install. This facilitates deployment of the Python packages. This module simplifies the procedure of downloading, building and deploying Python application and products.

Easy Install needs to be installed in the system before installing CherryPy.

Step 1 − Download the ez_setup.py module from http://peak.telecommunity.com and run it using the administrative rights on the computer: python ez_setup.py.

Step 2 − The following command is used to install Easy Install.: easy_install product_name

Step 3 − easy_install will search the Python Package Index (PyPI) to find the given product. PyPI is a centralized repository of information for all Python products.

Use the following command to deploy the latest available version of CherryPy: easy_install cherrypy

Step 4 − easy_install will then download CherryPy, build, and install it globally to your Python environment.

How To Applying Ajax To The Application?

Consider the application which includes a folder named “media” with index.html and Jquery plugin, and a file with AJAX implementation. Let us consider the name of the file as “ajax_app.py”

ajax_app.py
import cherrypy
import webbrowser
import os
import simplejson
import sys

MEDIA_DIR = os.path.join(os.path.abspath("."), u"media")
class AjaxApp(object):
   @cherrypy.expose
   def index(self):
      return open(os.path.join(MEDIA_DIR, u'index.html'))

   @cherrypy.expose
   def submit(self, name):
      cherrypy.response.headers['Content-Type'] = 'application/json'
      return simplejson.dumps(dict(title="Hello, %s" % name))

config = {'/media':
   {'tools.staticdir.on': True,
   'tools.staticdir.dir': MEDIA_DIR,}
}

def open_page():
webbrowser.open("http://127.0.0.1:8080/")
cherrypy.engine.subscribe('start', open_page)
cherrypy.tree.mount(AjaxApp(), '/', config=config)
cherrypy.engine.start()

The class “AjaxApp” redirects to the web page of “index.html”, which is included in the media folder.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
   " http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<html xmlns = "http://www.w3.org/1999/xhtml" lang = "en" xml:lang = "en">
   <head>
      <title>AJAX with jQuery and cherrypy</title>
      <meta http-equiv = " Content-Type" content = " text/html; charset=utf-8" />
      <script type = " text/javascript" src = " /media/jquery-1.4.2.min.js"></script>

      <script type = " text/javascript">
         $(function() {
     
            // When the testform is submitted...
            $("#formtest").submit(function() {
 
               // post the form values via AJAX...
               $.post('/submit', {name: $("#name").val()}, function(data) {

                  // and set the title with the result
                  $("#title").html(data['title']) ;
               });
               return false ;
            });
         });
      </script>
   </head>
   <body>
      <h1 id = "title">What's your name?</h1>
      <form id = " formtest" action = " #" method = " post">
         <p>
            <label for = " name">Name:</label>
            <input type = " text" id = "name" /> <br />
            <input type = " submit" value = " Set" />
         </p>
      </form>
   </body>
</html>

The function for AJAX is included within <script> tags.

What Is Cherrypy Demo Application?

In this chapter, we will focus on how an application is created in CherryPy framework.

Consider Photoblog application for the demo application of CherryPy. A Photoblog application is a normal blog but the principal text will be photos in place of text. The main catch of Photoblog application is that the developer can focus more on design and implementation.

Basic Structure – Design of Entities

The entities design the basic structure of an application. The following are the entities for the Photoblog application −

Film
Photo
Album.

How To Installation Using Subversion?

Installation of CherryPy using Subversion is recommended in the following situations −

A feature exists or a bug has been fixed and is only available in code under development.
When the developer works on CherryPy itself.
When the user needs a branch from the main branch in the versioning control repository.
For bug fixing of the previous release.
The basic principle of subversioning is to register a repository and keep a track of each of the versions, which include a series of changes in them.

Follow these steps to understand the installation of CherryPy using Subversion

Step 1 − To use the most recent version of the project, it is necessary to check out the trunk folder found on the Subversion repository.

Step 2 − Enter the following command from a shell

Step 3 − Now, create a CherryPy directory and download the complete source code into it.

What Is Built-in Http Server & Internal Engine?

CherryPy comes with its own web (HTTP) server. That is why CherryPy is self-contained and allows users to run a CherryPy application within minutes of getting the library.

The web server acts as the gateway to the application with the help of which all the requests and responses are kept in track.

To start the web server, a user must make the following call:

cherryPy.server.quickstart()

The internal engine of CherryPy is responsible for the following activities:

Creation and management of request and response objects.
Controlling and managing the CherryPy process.

What Is Cherrypy Configuration?

The framework comes with its own configuration system allowing you to parameterize the HTTP server. The settings for the configuration can be stored either in a text file with syntax close to the INI format or as a complete Python dictionary.

To configure the CherryPy server instance, the developer needs to use the global section of the settings.

global_conf = {
   'global': {
      'server.socket_host': 'localhost',
      'server.socket_port': 8080,
   },
}
application_conf = {
   '/style.css': {
      'tools.staticfile.on': True,
      'tools.staticfile.filename': os.path.join(_curdir, 'style.css'),
   }
}
This could be represented in a file like this:
[global]
server.socket_host = "localhost"
server.socket_port = 8080
[/style.css]
tools.staticfile.on = True
tools.staticfile.filename = "/full/path/to.style.css"

What Is Http Compliance?

CherryPy has been evolving slowly but it includes the compilation of HTTP specifications with the support of HTTP/1.0 later transferring with the support of HTTP/1.1.

CherryPy is said to be conditionally compliant with HTTP/1.1 as it implements all the must and required levels but not all the should levels of the specification. Therefore, CherryPy supports the following features of HTTP/1.1 −

If a client claims to support HTTP/1.1, it must send a header field in any request made with the specified protocol version. If it is not done, CherryPy will immediately stop the processing of the request.
CherryPy generates a Date header field which is used in all configurations.
CherryPy can handle response status code (100) with the support of clients.
CherryPy's built-in HTTP server supports persistent connections that are the default in HTTP/1.1, through the use of the Connection: Keep-Alive header.
CherryPy handles correctly chunked requests and responses.
CherryPy supports requests in two distinct ways − If-Modified-Since and If-Unmodified-Since headers and sends responses as per the requests accordingly.
CherryPy allows any HTTP method.
CherryPy handles the combinations of HTTP versions between the client and the setting set for the server.

How Is Testing The Installation?

It needs to be verified whether the application has properly been installed in the system or not in the same way as we do for applications like Java.

You may choose any one of the three methods mentioned in the previous chapter to install and deploy CherryPy in your environment. CherryPy must be able to import from the Python shell as follows −

import cherrypy
cherrypy.__version__
'3.0.0'

If CherryPy is not installed globally to the local system’s Python environment, then you need to set the PYTHONPATH environment variable, else it will display an error in the following way −

import cherrypy
Traceback (most recent call last):

File "<stdin>", line 1, in ?

ImportError: No module named cherrypy

What Is Cherrypy Vocabulary?

There are a few important keywords which need to be defined in order to understand the working of CherryPy. The keywords and the definitions are as follows

Web Server: It is an interface dealing with the HTTP protocol. Its goal is to transform the HTTP requests to the application server so that they get the responses.
Application: It is a piece of software which gathers information.
Application server: It is the component holding one or more applications
Web application server: It is the combination of web server and application server.

What Is Rest (representational State Transfer)?

A type of remote access protocol, which, transfers state from client to server which can be used to manipulate state instead of calling remote procedures.

Does not define any specific encoding or structure and ways of returning useful error messages.
Uses HTTP "verbs" to perform state transfer operations.
The resources are uniquely identified using URL.
It is not an API but instead an API transport layer.
REST maintains the nomenclature of resources on a network and provides unified mechanism to perform operations on these resources. Each resource is identified by at least one identifier. If the REST infrastructure is implemented with the base of HTTP, then these identifiers are termed as Uniform Resource Identifiers (URIs).

The following are the two common subsets of the URI set:

URL--- Uniform Resource Locator

URN--- Uniform Resource Name--- urn:isbn:0-201-71088-9 urn:uuid:13e8cf26-2a25-11db-8693-000ae4ea7d46

Before understanding the implementation of CherryPy architecture, let’s focus on the architecture of CherryPy.

CherryPy includes the following three components

cherrypy.engine − It controls process startup/teardown and event handling.
cherrypy.server − It configures and controls the WSGI or HTTP server.
cherrypy.tools − A toolbox of utilities that are orthogonal to processing an HTTP request.

What Is Rest Interface Through Cherrypy?

RESTful web service implements each section of CherryPy architecture with the help of the following −

Authentication
Authorization
Structure
Encapsulation
Error Handling
Authentication: Authentication helps in validating the users with whom we are interacting. CherryPy includes tools to handle each authentication method.

def authenticate():
   if not hasattr(cherrypy.request, 'user') or cherrypy.request.user is None:
      # < Do stuff to look up your users >
      cherrypy.request.authorized = False # This only authenticates.
      Authz must be handled separately.
      cherrypy.request.unauthorized_reasons = []
      cherrypy.request.authorization_queries = []

cherrypy.tools.authenticate =
   cherrypy.Tool('before_handler', authenticate, priority=10)

The above function authenticate() will help to validate the existence of the clients or users. The built-in tools help to complete the process in a systematic way.

Authorization: Authorization helps in maintaining the sanity of the process via URI. The process also helps in morphing objects by user token leads.

def authorize_all():
   cherrypy.request.authorized = 'authorize_all'
cherrypy.tools.authorize_all = cherrypy.Tool('before_handler', authorize_all, priority=11)
def is_authorized():
   if not cherrypy.request.authorized:
      raise cherrypy.HTTPError("403 Forbidden",
         ','.join(cherrypy.request.unauthorized_reasons))

cherrypy.tools.is_authorized = cherrypy.Tool('before_handler', is_authorized,
priority = 49)

cherrypy.config.update({
   'tools.is_authorized.on': True,
   'tools.authorize_all.on': True
})

The built-in tools of authorization help in handling the routines in a systematic way, as mentioned in the previous example.

Structure: Maintaining a structure of API helps in reducing the work load of mapping the URI of application. It is always necessary to keep API discoverable and clean. The basic structure of API for CherryPy framework should have the following −

Accounts and User
Autoresponder
Contact
File
Folder
List and field
Message and Batch
Encapsulation: Encapsulation helps in creating API which is lightweight, human readable and accessible to various clients. The list of items along with Creation, Retrieval, Update and Deletion requires encapsulation of API.

Error Handling: This process manages errors, if any, if API fails to execute at the particular instinct. For example, 400 is for Bad Request and 403 is for unauthorized request.

What Is Cherrypy Toolbox?

Within CherryPy, built-in tools offer a single interface to call the CherryPy library. The tools defined in CherryPy can be implemented in the following ways −

From the configuration settings
As a Python decorator or via the special _cp_config attribute of a page handler
As a Python callable that can be applied from within any function

What Is Basic Authentication Tool?

The purpose of this tool is to provide basic authentication to the application designed in the application.

Arguments

This tool uses the following arguments −

realm: String defining the realm value.

users: Dictionary of the form − username:password or a Python callable function returning such a dictionary.

encrypt: Python callable used to encrypt the password returned by the client and compare it with the encrypted password provided in the users dictionary.

What Is Caching Tool?

The purpose of this tool is to provide memory caching of CherryPy generated content.

Arguments

This tool uses the following arguments:

invalid_methods--- ("POST", "PUT", "DELETE")--- Tuples of strings of HTTP methods not to be cached. These methods will also invalidate (delete) any cached copy of the resource.

cache_Class--- MemoryCache--- Class object to be used for caching

What Is Decoding Tool?

The purpose of this tool is to decode the incoming request parameters.

Arguments

This tool uses the following arguments:

encoding---- None--- It looks for the content-type header

Default_encoding--- "UTF-8"--- Default encoding to be used when none is provided or found.


What Is Cherrypy Working Application?

Full stack applications provide a facility to create a new application via some command or execution of the file.

Consider the Python applications like web2py framework; the entire project/application is created in terms of MVC framework. Likewise, CherryPy allows the user to set up and configure the layout of the code as per their requirements.

What Is Cherrypy Web Services?

A web service is a set of web-based components that helps in the exchange of data between the application or systems which also includes open protocols and standards. It can be published, used and found on the web.

What Is Http Methods?

The list of HTTP methods which operate on the resources are as follows:

HEAD: Retrieves the resource metadata.
GET: Retrieves the resource metadata and content.
POST: Requests the server to create a new resource using the data enclosed in the request body.
PUT: Requests the server to replace an existing resource with the one enclosed in the request body.
DELETE: Requests the server to remove the resource identified by that URI.
OPTIONS: Requests the server to return details about capabilities either globally or specifically towards a resource.

What Is Atom Publishing Protocol (app)?

APP has arisen from the Atom community as an application-level protocol on top of HTTP to allow the publishing and editing of web resources. The unit of messages between an APP server and a client is based on the Atom XML-document format.

The Atom Publishing Protocol defines a set of operations between an APP service and a user-agent using HTTP and its mechanisms and the Atom XML-document format as the unit of messages.

APP first defines a service document, which provides the user agent with the URI of the different collections served by the APP service.

What Is Cherrypy Presentation Layer?

The Presentation Layer ensures that the communication passing through it targets the intended recipients. CherryPy maintains the working of presentation layer by various template engines.

A template engine takes the input of the page with the help of business logic and then processes it to the final page which targets only the intended audience.

What Is Kid?

Kid is a simple template engine which includes the name of the template to be processed (which is mandatory) and input of the data to be passed when the template is rendered.

On creation of the template for the first time, Kid creates a Python module which can be served as a cached version of the template.

The kid.Template function returns an instance of the template class which can be used to render the output content.

The template class provides the following set of commands

serialize: It returns the output content as a string.
generate: It returns the output content as an iterator.
write: It dumps the output content into a file object.

What Is Cherrypy Use Of Ajax?

Till the year 2005, the pattern followed in all web applications was to manage one HTTP request per page. The navigation of one page to another page required loading the complete page. This would reduce the performance at a greater level.

Thus, there was a rise in rich client applications which used to embed AJAX, XML, and JSON with them.

AJAX: Asynchronous JavaScript and XML (AJAX) is a technique to create fast and dynamic web pages. AJAX allows web pages to be updated asynchronously by exchanging small amounts of data behind the scenes with the server. This means that it is possible to update parts of a web page, without reloading the whole page.

Google Maps, Gmail, YouTube, and Facebook are a few examples of AJAX applications.

Ajax is based on the idea of sending HTTP requests using JavaScript; more specifically AJAX relies on the XMLHttpRequest object and its API to perform those operations.

JSON: JSON is a way to carry serialized JavaScript objects in such a way that JavaScript application can evaluate them and transform them into JavaScript objects which can be manipulated later.

For instance, when the user requests the server for an album object formatted with the JSON format, the server would return the output as following:

{'description': 'This is a simple demo album for you to test', 'author': ‘xyz’}

Now the data is a JavaScript associative array and the description field can be accessed via: data ['description'];

https://mytecbooks.blogspot.com/2018/02/cherrypy-advanced-level-interview.html
Subscribe to get more Posts :