Professional Documents
Culture Documents
DJANGO INTERVIEW QUESTIONS
DJANGO INTERVIEW QUESTIONS
Entry
Functions in Python are like first-class objects. It suggests you can assign
them to variables, return from other methods and pass them as arguments.
Developing using Python is quick but running it is often slower than compiled
languages.
Python has several usages like web-based applications, test automation, data
modeling, big data analytics, and much more.
Consider:
x = lambda a : a + 10
print(x(5)) # Output: 15
>>> s
['H', 'e', 'l', 'l', 'o', ' ', 'z', 'o', 'r', 'l', 'd']
>>> s
['H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd']
>>> "".join(s)
'Hello World'
To convert the string into a number the built-in functions are used like int() a
constructor. It is a data type that is used like int (‘1’) == 1 .
There is function eval() that can be used to convert a string into number but it
is a bit slower and present many security risks
def switch_demo(argument):
switcher = {
1: "January",
2: "February",
3: "March",
4: "April",
5: "May",
6: "June",
7: "July",
8: "August",
9: "September",
10: "October",
11: "November",
12: "December"
Python 3.10 (2021) introduced the match-case a statement that provides a first-class
implementation of a "switch" for Python. For example:
For example:
def f(x):
match x:
case 'a':
return 1
case 'b':
return 2
The match-case the statement is considerably more powerful than this simple
example.
Q. What are descriptors ?Junior
Descriptors were introduced to Python way back in version 2.2. They provide the
developer with the ability to add managed attributes to objects. The methods needed
to create a descriptor are __get__, __set__ and __delete__. If you define any of
these methods, then you have created a descriptor.
Descriptors power a lot of the magic of Python’s internals. They are what make
properties, methods and even the super function work. They are also used to
implement the new style classes that were also introduced in Python 2.2.
Q. What are Virtualenvs ?Mid
Monkey patching can only be done in dynamic languages, of which python is a good
example. In Monkey patching, we reopen the existing classes or methods in class at
runtime and alter the behavior, which should be used cautiously, or you should use it
only when you really need to. As Python is a dynamic programming language,
Classes are mutable so you can reopen them and modify or even replace them.
For example:
import datetime
Most of the time it's a pretty terrible idea - it is usually best if things act in a well-
defined way. One reason to monkey patch would be in testing. The mock package is
very useful to this end.
Q. What is Pickling and Unpickling?Mid
The pickle the module implements a fundamental, but powerful algorithm for
serializing and de-serializing a Python object structure.
Pickling - is the process whereby a Python object hierarchy is converted into a
byte stream,
>>> len(num_list)
10000
>>> num_list[:3]
... pickle.dump(num_list, f)
...
...
>>> copy_of_nums_list[:3]
If you write a function, and that function doesn't use an explicit return
statement, None is returned instead, for example.
Another example is to use None default values. it is good programming practice to not
use mutable objects as default values. Instead, use None it as the default value and
inside the function, check if the parameter is None and create a new
list/dictionary/whatever if it is.
Consider:
def foo(mydict=None):
if mydict is None:
Functions are objects; they can be referenced to, passed to a variable, and
returned from other functions as well.
Functions can be defined inside another function and can also be passed as
arguments to another function.
Now:
Decorators are a very powerful and useful tool in Python since it allows
programmers to modify the behavior of a function or class.
@gfg_decorator
def hello_decorator():
print("Gfg")
def hello_decorator():
print("Gfg")
hello_decorator = gfg_decorator(hello_decorator)'''
The key difference is that tuples are immutable. This means that you cannot
change the values in a tuple once you have created it.
Apart from tuples being immutable, there is also a semantic distinction that should
guide their usage. Tuples are heterogeneous data structures (i.e., their entries have
different meanings), while lists are homogeneous sequences. Tuples have structure,
and lists have been ordered.
One example of a tuple is pairs of the page and line number to reference locations in a
book, e.g.:
class MyClass(object):
def meth_a(self):
pass
def meth_b(self):
If you were to leave out the pass, the code wouldn't run and you'll get an error:
Testing that code runs properly for a few test values, without caring about the
results
Q. What's the difference between the list methods append() and extend()?Mid
Consider:
x = [1, 2, 3]
x.append([4, 5])
print (x)
x = [1, 2, 3]
x.extend([4, 5])
print (x)
# [1, 2, 3, 4, 5]
className.static_method_name()
Q. How does Python memory management work?Mid
Python - like C#, Java, and many other languages -- uses garbage collection rather
than manual memory management. You just freely create objects and the language's
memory manager periodically (or when you specifically direct it to) looks for any
objects that are no longer referenced by your program.
If you want to hold on to an object, just hold a reference to it. If you want the object to
be freed (eventually) remove any references to it.
def foo(names):
print name
Each of these calls to foo creates a Python list object initialized with three values.
For the duration of the foo call they are referenced by the variable names, but as soon
as that function exits no variable is holding a reference to them and they are fair game
for the garbage collector to delete.
Q. What is a Callable?Mid
A callable object allows you to use round parenthesis ( ) and eventually pass
some parameters, just like functions.
Every time you define a function python creates a callable object. In the example, you
could define the function func in these ways (it's the same):
class a(object):
print 'Hello'
func = a()
# or ...
def func(*args):
print 'Hello'
flat_list = []
for sublist in l:
flat_list.append(item)
print(flatten([[1],[2],[3],[4,5]]))
# Output: [1, 2, 3, 4, 5]
There is also the step value, which can be used with any of the above:
The key point to remember is that the :stop the value represents the first value that
is not in the selected slice. So, the difference between stop and start is the number
of elements selected (if step is 1, the default).
The ASCII art diagram is helpful too for remembering how slices work:
+---+---+---+---+---+---+
|P|y|t|h|o|n|
+---+---+---+---+---+---+
0 1 2 3 4 5 6
-6 -5 -4 -3 -2 -1
Q. What is the difference between range and xrange? How has this changed over
time?Mid
xrange returns the xrange object while range returns the list, and uses the same
memory and no matter what the range size is.
For the most part, xrange and range are the exact same in terms of
functionality. They both provide a way to generate a list of integers for you to
use, however you please.
The only difference is that range returns a Python list object and x range returns
an xrange object. This means that xrange doesn’t actually generate a static list
at run-time as range does. It creates the values as you need them with a special
technique called yielding. This technique is used with a type of object known as
generators. That means that if you have a really gigantic range you’d like to
generate a list for, say one billion, xrange is the function to use.
__init__ - constructor
For instance, the open the statement is a context manager in itself, which lets you
open a file, keep it open as long as the execution is in the context of the with a
statement where you used it, and close it as soon as you leave the context, no matter
whether you have left it because of an exception or during regular control flow.
data = foo_file.read()
OR
do_something()
OR (Python 3.1)
output_file.write(parse(line))
OR
lock = threading.Lock()
For shallow copy use copy.copy(). Shallow copies are just copies of the
outermost container.
Q. What does this stuff mean: *args, **kwargs? Why would we use it?Mid
Use *args when we aren't sure how many arguments are going to be passed to
a function, or if we want to pass a stored list or tuple of arguments to a
function.
...
0. apple
1. banana
2. cabbage
**kwargs is used when we don't know how many keyword arguments will be
passed to a function, or it can be used to pass the values of a dictionary as
keyword arguments.
...
cabbage = vegetable
apple = fruit
Let's say you have a class ClassA which contains a method methodA defined as:
chunks = []
for s in my_strings:
chunks.append(s)
result = ''.join(chunks)
Shallow copy is used when a new instance type gets created and it keeps the
values that are copied in the new instance. Whereas, a deep copy is used to
store the values that are already copied.
Shallow copy is used to copy the reference pointers just like it copies the
values. These references point to the original objects and the changes made in
any member of the class will also affect the original copy of it. Whereas, deep
copy doesn’t copy the reference pointers to the objects. Deep copy makes the
reference to an object and the new object that is pointed by some other object
gets stored. The changes made in the original copy won’t affect any other copy
that uses the object.
Shallow copy allows faster execution of the program and it depends on the size
of the data that is used. Whereas, deep copy makes it slower due to making
certain copies for each object that is been called.
class C:
@staticmethod
def f(arg1, arg2, ...): ...
A classmethod, on the other hand, is a method that gets passed the class it was called
on, or the class of the instance it was called on, as the first argument. Its definition
follows Sub class, not Parent class, via inheritance.
class C:
@classmethod
Python has a construct called the Global Interpreter Lock (GIL). The GIL makes sure
that only one of your 'threads' can execute at any one time. A thread acquires the GIL,
does a little work, then passes the GIL onto the next thread. This happens very quickly
so to the human eye it may seem like your threads are executing in parallel, but they
are really just taking turns using the same CPU core. All this GIL passing adds
overhead to execution.
Q. What is MRO in Python? How does it work?Senior
Method Resolution Order (MRO) it denotes the way a programming language
resolves a method or attribute. Python supports classes inheriting from other classes.
The class being inherited is called the Parent or Superclass, while the class that
inherits is called the Child or Subclass.
In Python, method resolution order defines the order in which the base classes are
searched when executing a method. First, the method or attribute is searched within a
class and then it follows the order we specified while inheriting. This order is also
called Linearization of a class and set of rules are called MRO (Method Resolution
Order). While inheriting from another class, the interpreter needs a way to resolve the
methods that are being called via an instance. Thus we need the method resolution
order.
Python resolves method and attribute lookups using the C3 linearisation of the class
and its parents. The C3 linearisation is neither depth-first nor breadth-first in
complex multiple inheritance hierarchies.
Q. Can you explain Closures (as they relate to Python)?Senior
Objects are data with methods attached, closures are functions with data attached.
The method of binding data to a function without actually passing them as parameters
is called closure.
def make_counter():
i=0
nonlocal i
i += 1
return i
return counter
c1 = make_counter()
c2 = make_counter()
# -> 1 2 1 2
def reversed_iterator(iter):
return reversed(list(iter))
2. For translation lookup in i18n (see the gettext documentation for example), as
in code like: raise forms.ValidationError(_("Please enter a correct
username"))
def makebold(fn):
@wraps(fn)
return wrapped
def makeitalic(fn):
@wraps(fn)
return wrapped
@makebold
@makeitalic
def hello():
@makebold
@makeitalic
def log(s):
return s
Consider:
def foo(mydict={}): # Danger: shared reference to one dict for all calls
mydict[key] = value
return mydict
The first time you call this function, mydict contains a single item. The second time,
mydict contains two items because when foo()begins executing, mydict starts out
with an item already in it.
Q. What is GIL?Expert
Python has a construct called the Global Interpreter Lock (GIL).
The GIL makes sure that only one of your threads can execute at any one time. A
thread acquires the GIL, does a little work, then passes the GIL onto the next thread.
This happens very quickly so to the human eye it may seem like your threads are
executing in parallel, but they are really just taking turns using the same CPU core.
All this GIL passing adds overhead to execution.
Q. Why would you use metaclasses?Expert
The main use case for a metaclass is creating an API. A typical example of this is the
Django ORM.
class Person(models.Model):
name = models.CharField(max_length=30)
age = models.IntegerField()
print(guy.age)
It won't return an IntegerField object. It will return an int, and can even take it
directly from the database.
Django makes something complex look simple by exposing a simple API and
using metaclasses, recreating code from this API to do the real job behind the scenes.
Q. Describe Python's Garbage Collection mechanism in briefExpert
A lot can be said here. There are a few main points that you should mention:
If you want to force Python to delete certain things on deallocation, you can use
the atexit module to register one or more exit functions to handle those deletions.
module = PyImport_ImportModule("mymodule");
You can then access the module’s attributes (i.e. any name defined in the module) as
follows:
do_something_with(line)
do_something_with(line)
Somewhat less frequently, assert is used to perform logic functions, rather than
merely declare the invariant expectations of a point in code, and so any code like that
would also break.
var a = "42";
var b = 42;
a == b; // true
a === b; // false
If either value (aka side) in comparison could be the true or false value,
avoid == and use ===.
In all other cases, you're safe to use ==. Not only is it safe, but in many cases, it
simplifies your code in a way that improves readability.
var obj = {
b: 42,
c: true
};
obj.b; // 42
obj.c; // true
obj["c"]; // true
Bracket notation is also useful if you want to access a property/key but the name is
stored in another variable, such as:
var obj = {
a: "hello world",
b: 42
};
var b = "a";
obj["b"]; // 42
A variable name has to be unique within the same scope. A scope can be nested inside
another scope. If one scope is nested inside another, code inside the innermost scope
can access variables from either scope.
Q. Explain arrays in JavaScriptEntry
An array is an object that holds values (of any type) not particularly in named
properties/keys, but rather in numerically indexed positions:
var arr = [
"hello world",
42,
true
];
arr[1]; // 42
arr[2]; // true
arr.length; // 3
var a;
typeof a; // "undefined"
a = "hello world";
typeof a; // "string"
a = 42;
typeof a; // "number"
a = true;
typeof a; // "boolean"
a = null;
a = undefined;
typeof a; // "undefined"
a = { b: "c" };
typeof a; // "object"
number
boolean
object
Host objects: objects like window, XmlHttpRequest , DOM nodes, and so on, which
are provided by the browser environment. They are distinct from the built-in objects
because not all environments will have the same host objects. If JavaScript runs
outside of the browser, for example as a server-side scripting language like in Node.js,
different host objects will be available
Q. What is the difference between == and === ?Junior
== is the abstract equality operator while === is the strict equality operator.
The == operator will compare for equality after doing any necessary type conversions.
The === operator will not do type conversion, so if two values are not the same
type === will simply return false. When using ==, funky things can happen, such as:
1 == '1'; // true
1 == [1]; // true
1 == true; // true
0 == ''; // true
0 == '0'; // true
0 == false; // true
My advice is never to use the == operator, except for convenience when comparing
against null or undefined, where a == null will
return true if a is null or undefined.
var a = null;
Q. What is a Polyfill?Junior
A polyfill is essentially the specific code (or plugin) that would allow you to have
some specific functionality that you expect in current or “modern” browsers to also
work in other browsers that do not have the support for that functionality built-in.
Object.getOwnPropertyNames() - Object.getOwnPropertyNames(obj).for
Each(function (property) { ... }) . Object.getOwnPropertyNames() is
a static method that will list all enumerable and non-enumerable properties of
the object that you pass it.
For arrays:
for loops - for (var i = 0; i < arr.length; i++) . The common pitfall
here is that var is in the function scope and not the block scope and most of the
time you would want a block-scoped iterator variable. ES2015
introduces let which has block scope and it is recommended to use that
instead. So this becomes: for (let i = 0; i < arr.length; i++) .
// ES5 Implementation
var array = [1, 2, 3, 5, 1, 5, 9, 1, 2, 8];
uniqueArray(array); // [1, 2, 3, 5, 9, 8]
function uniqueArray(array) {
var hashmap = {};
var unique = [];
return unique;
}
arr.push(100);
callback();
}
var arr = [1, 2, 3, 4, 5];
modifyArray(arr, function() {
});
For example, arrays are by default coerced to strings by simply joining all the values
with commas (,) in between. So two arrays with the same contents would not
be == equal:
var a = [1,2,3];
var b = [1,2,3];
var c = "1,2,3";
a == c; // true
b == c; // true
a == b; // false
For deep object comparison use external libs like deep-equal or implement your own
recursive equality algorithm.
Q. Explain Function.prototype.bindMid
The bind() the method creates a new function that, when called, has its this keyword
set to the provided value, with a given sequence of arguments preceding any provided
when the new function is called.
Q. Explain Closure in JavaScriptMid
Consider:
function makeAdder(x) {
function add(y) {
return y + x;
};
return add;
Reference to inner add the function returned is able to remember what x value was
passed to makeAdder function call.
In C and most other common languages, after a function returns, all the local variables
are no longer accessible because the stack frame is destroyed.
In JavaScript, if you declare a function within another function, then the local
variables can remain accessible after returning from the function you called.
A closure is a stack frame that is allocated when a function starts its execution, and
not freed after the function returns (as if a 'stack frame' were allocated on the heap
rather than the stack!). In JavaScript, you can think of a function reference variable as
having both a pointer to a function as well as a hidden pointer to a closure.
Q. What's the difference between .call and .apply?Mid
Both .call and .apply are used to invoke functions and the first parameter will be
used as the value this within the function. However, .call takes in comma-
separated arguments as the next argument while .apply taking in an array of
arguments as the next argument. An easy way to remember this is C for call comma-
separated and A for apply an array of arguments.
function add(a, b) {
return a + b;
console.log(add.call(null, 1, 2)); // 3
// Private method
};
// Public method
this.dispalyIncreasedSalary = function() {
increaseSalary();
console.log(this.salary);
};
};
Here each instance variable emp1, emp2, emp3 has own copy of increaseSalary private
method.
Q. Explain the differences on the usage of foo between function foo() {} and var
foo = function() {}Mid
The former is a function declaration while the latter is a function expression. The key
difference is that function declaration have its body hoisted but the bodies of function
expressions are not (they have the same hoisting behavior as variables). If you try to
invoke a function expression before it is defined, you will get an Uncaught
TypeError: XXX is not a function error.
Function Declaration
foo(); // 'FOOOOO'
function foo() {
console.log('FOOOOO');
Function Expression
console.log('FOOOOO');
};
A shim is a library that brings a new API to an older environment, using only the
means of that environment. Thus, a polyfill is a shim for a browser API.
Q. What is Coercion in JavaScript?Mid
In JavaScript conversion between different two build-in types called coercion.
Coercion comes in two forms in JavaScript: explicit and implicit.
var a = "42";
var b = Number( a );
a; // "42"
b; // 42 -- the number!
var a = "42";
a; // "42"
b; // 42 -- the number!
(function IIFE(){
console.log( "Hello!" );
})();
// "Hello!"
This pattern is often used when trying to avoid polluting the global namespace
because all the variables used inside the IIFE (like in any other normal function) are
not visible outside its scope.
Q. What's a typical use case for anonymous functions?Mid
They can be used in IIFEs to encapsulate some code within a local scope so that
variables declared in it do not leak to the global scope.
(function() {
})();
As a callback that is used once and does not need to be used anywhere else. The code
will seem more self-contained and readable when handlers are defined right inside the
code calling them, rather than having to search elsewhere to find the function body.
setTimeout(function() {
console.log('Hello world!');
}, 1000);
Arguments to functional programming constructs or Lodash (similar to callbacks).
return el * 2;
});
console.log(double); // [2, 4, 6]
// Return a function that accepts a word and looks it up in the trie structure
return function (word) {
var i = -1,
active = trie;
while (word[++i]) {
if (!active[word[i]]) { return []; }
active = active[word[i]];
}
return active.positions;
};
};
this.data = data;
this.next = next;
function Enqueue(element) {
Queue.back = N;
} else {
Queue.back.next = N;
Queue.back = Queue.back.next;
function Dequeue() {
Queue.front = Queue.front.next;
return first.data;
} else {
}
Enqueue('a');
Enqueue('b');
Enqueue('c');
Dequeue();
// Loop through all the remaining letters and recurse slicing the character
word + remaining[i],
remaining.substr(0, i) + remaining.substr(i + 1)
);
})('', string);
// Using the ES5 Object.keys to grab the all the keys as an array.
return Object.keys(result);
};
firstArray.forEach(function(element) {
hashmap[element] = 1;
});
// Since we only want to push unique elements in our case... we can implement a counter to keep track of what we
already added
secondArray.forEach(function(element) {
if (hashmap[element] === 1) {
intersectionArray.push(element);
hashmap[element]++;
}
});
return intersectionArray;
Q. Given an array of integers, find the largest product yielded from three of the
integersMid
var unsortedArray = [-10, 7, 29, 30, 5, -10, -70];
computeProduct(unsortedArray); // 21000
function sortIntegers(a, b) {
return a - b;
function computeProduct(unsorted) {
product1 = 1,
product2 = 1,
array_n_element = sortedArray.length - 1;
// Get the product of three largest integers in sorted array
return product2;
Before starting further discussion let's understand the difference between declaration
and definition.
var x is a declaration because you are not defining what value it holds yet, but you
are declaring its existence and the need of memory allocation.
var x; // declaring x
A variable that is declared but not define and when we try to access it, It will
result undefined.
var x; // Declaration
A variable that neither declared nor defined when we try to reference such variable
then It result not defined.
Map
Let say we have an array of names which we need to transform each string to
uppercase.
results.push(names[i].toUpperCase());
return results;
};
};
Scope safety: Until arrow functions, every new function defined its own value
(a new object in the case of a constructor, undefined in strict mode function
calls, the base object if the function is called as an "object method", etc.). An
arrow function does not create its own this, the this value of the enclosing
execution context is used.
Compactness: Arrow functions are easier to read and write.
The function can be called as many times as desired and returns a new Generator each
time, however, each Generator may only be iterated once.
let iterationCount = 0;
iterationCount++;
yield i;
return iterationCount;
Q. What is Currying?Mid
Currying is when you break down a function that takes multiple arguments into a
series of functions that take part in the arguments. Here's an example in JavaScript:
This is a function that takes two arguments, a and b, and returns their sum. We will
now curry this function:
return a + b;
In an algebra of functions, dealing with functions that take multiple arguments (or
equivalent one argument that's an N-tuple) is somewhat inelegant. So how do you deal
with something you'd naturally express as, say, f(x,y)? Well, you take that as
equivalent to f(x)(y) - f(x) , call it g, is a function, and you apply that function
to y. In other words, you only have functions that take one argument - but some of
those functions return other functions (which ALSO take one argument).
Q. Explain destructuring an object or an array in ES6?Senior
Destructuring is an expression available in ES6 which enables a succinct and
convenient way to extract values of Objects or Arrays and place them into distinct
variables.
Array destructuring
// Variable assignment.
console.log(one); // "one"
console.log(two); // "two"
console.log(three); // "three"
// Swapping variables
let a = 1;
let b = 3;
console.log(a); // 3
console.log(b); // 1
Object destructuring
// Variable assignment.
const { p, q } = o;
console.log(p); // 42
console.log(q); // true
Q. What is the new keyword in JavaScript?Senior
4. It executes the constructor function, using the newly created object whenever
this is mentioned.
5. It returns the newly created object, unless the constructor function returns a
non-null object reference. In this case, that object reference is returned instead.
Consider:
function New(func) {
res.__proto__ = func.prototype;
if ((typeof ret === "object" || typeof ret === "function") && ret !== null) {
return ret;
return res;
}
Q. What does the term Transpiling stand for?Senior
There's no way to polyfill new syntax that has been added to the language. So the
better option is to use a tool that converts your newer code into older code
equivalents. This process is commonly called transpiling, a term for transforming +
compiling.
Typically you insert the transpiler into your build process, similar to your code linter
or your minifier. There are quite a few great transpilers for you to choose from:
letterB = secondString[i];
// If the letter does not exist, create a map and map it to the value
letterMap[letterA] = letterB;
// Eles if letterA already exists in the map, but it does not map to
return false;
}
return true;
A good use of the bind function is when you have a particular function that you want
to call with a specific this value. You can then use bind to pass a specific object to a
function that uses a this reference.
function fullName() {
// create a person object and pass its values to the fullName function
Q. Explain how JSONP works (and how it's not really Ajax)Senior
JSONP (JSON with Padding) is a method commonly used to bypass the cross-domain
policies in web browsers because Ajax requests from the current page to a cross-
origin domain is not allowed.
JSONP works by making a request to a cross-origin domain via a <script> tag and
usually with a callback query parameter, for example: https://example.com?
callback=printData . The server will then wrap the data within a function
called printData and return it to the client.
<script>
function printData(data) {
</script>
<script src="https://example.com?callback=printData"></script>
The client has to have the printData function in its global scope and the function will
be executed by the client when the response from the cross-origin domain is received.
JSONP can be unsafe and has some security implications. As JSONP is really
JavaScript, it can do everything else JavaScript can do, so you need to trust the
provider of the JSONP data.
These days, CORS is the recommended approach and JSONP is seen as a hack.
Q. Explain Prototype Inheritance in JavaScript?Senior
In a language implementing classical inheritance like Java, C# or C++ you start by
creating a class--a blueprint for your objects - and then you can create new objects
from that class or you can extend the class, defining a new class that augments the
original class.
In JavaScript you first create an object (there is no concept of class), then you can
augment your own object or create new objects from it.
Constructor functions are the most used way in JavaScript to construct prototype
chains. When we use new, JavaScript injects an implicit reference to the new object
being created in the form of the this keyword. It also returns this reference implicitly
at the end of the function.
function Foo() {
this.kind = ‘foo’
var a = {
x: 12
};
var b = {
y: 12
};
map.set(a, 1);
weakmap.set(b, 2);
})()
The above IIFE is executed there is no way we can reference {x: 12} and {y:
12} anymore. Garbage collector goes ahead and deletes the key b pointer from
“WeakMap” and also removes {y: 12} from memory. But in case of “Map”, the
garbage collector doesn’t remove a pointer from “Map” and also doesn’t remove {x:
12} from memory.
WeakMap allows the garbage collectors to do its task but not Map. With manually
written maps, the array of keys would keep references to key objects, preventing them
from being garbage collected. In native WeakMaps, references to key objects are held
"weakly", which means that they do not prevent garbage collection in case there
would be no other reference to the object.
Q. Explain difference between the await keyword and the yield keyword?Expert
yield can be considered to be the building block of await. yield takes the value it's
given and passes it to the caller. The caller can then do whatever it wishes with that
value (1). Later the caller may give a value back to the generator
(via generator.next() ) which becomes the result of the yield expression (2), or an
error that will appear to be thrown by the yield expression (3).
async-await can be considered to use yield. At (1) the caller (i.e. the async-
await driver - similar to the function you posted) will wrap the value in a promise
using a similar algorithm to new Promise(r =>
r(value) (note, not Promise.resolve , but that's not a big deal). It then waits for the
promise to resolve. If it fulfills, it passes the fulfilled value back at (2). If it rejects, it
throws the rejection reason as an error at (3).
So the utility of async-await is this machinery that uses yield to unwrap the yielded
value as a promise and pass its resolved value back, repeating until the function
returns its final value.
Q. Is JavaScript a pass-by-reference or pass-by-value language?Expert
It's always pass by value, but for objects, the value of the variable is a reference.
Because of this, when you pass an object and change its members, those changes
persist outside of the function. This makes it look like pass-by reference. But if you
actually change the value of the object variable you will see that the change does not
persist, proving it's really passed by value.
Example:
function changeStuff(a, b, c)
a = a * 10;
b.item = "changed";
c = {item: "changed"};
console.log(num);
console.log(obj1.item);
console.log(obj2.item);
Output:
10
changed
unchanged
let person = {
name: "Leonardo",
profession: {
name: "developer"
};
Object.freeze(person); // make object immutable
person.profession.name = "doctor";
function deepFreeze(object) {
deepFreeze(value) : value;
return Object.freeze(object);
let person = {
name: "Leonardo",
profession: {
name: "developer"
};
deepFreeze(person);
Load More
Q. What is the difference between Data Definition Language (DDL) and Data
Manipulation Language (DML)?Entry
Data definition language (DDL) commands are the commands which are used
to define the database. CREATE, ALTER, DROP and TRUNCATE are
some common DDL commands.
PRIMARY KEY(`customerid`));
If we run the INSERT command as below, we will get an error as the country name is
not provided.
To fix this problem you can add a DEFAULT constraint using the command below.
Default value USA will be taken on running the INSERT command above.
Q. What is a VIEW in MySQL? How can you create and query a view?Junior
Views are virtual tables that are stored in SQL queries with a certain given
name. VIEW replaces a SELECT query with a given named view.
The SELECT query could be a complex SELECT query across different database
tables or a simple SELECT query. Once invoked, a view gives results using the query
stored in the view.
AS SELECT select_statement;
Unique key constraint ensures that values entered in a column are unique. Although
primary key values will be unique, you might want to ensure that some other column
also has non-duplicate entries.
For example, if we have multiple users and want to ensure that no two users with the
same email id are added to the table, we can put a UNIQUE key constraint on
the email_id column. NULL values are ignored in case of Unique key constraint which
means NULL is allowed value for email id in this case.
Q. What is self-referencing foreign key? Give an example.Junior
A foreign key that is stored in a table itself is called to be a self-referencing foreign
key.
For example, consider an Employee database table. It has employee_id as the primary
key as well as a manager_id which is the employee_id of his manager. If we create a
foreign key constraint, as a manager is also an employee, manager_id will refer
to empolyee_id in the same table.
The Employee table with self-referencing foreign key manager_id can be created
using the below statement.
PRIMARY KEY(`employee_id`),
);
Foreign key constraint ensures referential integrity. Foreign key columns need to be
indexed in MySQL, so an index is automatically created on a foreign key column if
the index is not created on the column while creating a table with a foreign key
constraint.
Q. What are different integer data types in MySQL? How can you use an
unsigned integer in MySQL?Junior
MySQL has different INT data types with different storage requirements including:
MEDIUMINT (3 bytes),
BIGINT (8 bytes).
All the INT types can be used as signed or unsigned. You can write UNSIGNED after
data type to tell if it is unsigned.
For example below command will create a Student table which can mark as an
unsigned SMALLINT value.
Q. How are VARCHAR and CHAR different? Mention the use case for
both.Junior
Both CHAR and VARCHAR data types store characters up to a specified length.
1. CHAR stores characters of fixed length while VARCHAR can store characters
of variable length.
3. CHAR internally takes fixed space, and if the stored character length is small,
it is padded by trailing space characters. VARCHAR has 1 or 2-byte prefixes
along with stored characters.
COUNT, SUM, AVG, MIN, MAX are examples of MySQL aggregate functions.
TINYTEXT,
TEXT,
MEDIUMTEXT and
LONGTEXT.
These data types have different maximum sizes. While TINYTEXT can hold strings
up to 255 characters, TEXT can hold up to 65,535 characters, MEDIUMTEXT can
hold up to 16,777,215 characters and LONGTEXT can hold up to 4,294,967,295
characters.
VARCHAR is also a variable text data type with some difference. VARCHAR is
stored inline in the database table while TEXT data types are stored elsewhere in
storage with its pointer stored in the table. A prefix length is a must for creating index
on TEXT data types. TEXT columns do not support default values,
unlike VARCHAR.
Q. What happens, If a parent row which is referenced by child row is being
deleted in case of foreign key constrain.Mid
The behavior of what happens depends upon set referential actions
including CASCADE, SET NULL, RESTRICT, NO ACTION which can be
provided while creating a foreign key constraint using ON UPDATE and ON
DELETE commands. If no such value is provided while creating a foreign key
constraint, RESTRICT will be the default action.
CASCADE - changes will be cascaded which means rows in the child table
referencing the parent table will be deleted.
Q. What are key constraints? What different types of constraints are there in
MySQL?Mid
Key constraints are rules which ensure that correct data is stored in the database. It
ensures the integrity of the data. MySQL constraints include:
BLOB data types are designed to store binary data like pictures or videos in a
database.
BLOB stores binary byte string while TEXT stores character string.
Although BLOB can be used for storing text data, TEXT data types support sorting
and comparison around text which is not supported by BLOB.
IN operator is used to select rows that have a column value in the provided list of
values. Below command lists all students with rollnumber 2, 4, and 7.
Q. What is Stored Function in MySQL. How are they different from Stored
Procedure?Mid
Stored function is a stored complex logic which can be executed like a function call
from any other statement. It returns a single value. It can be used to store business
logic and formulas in database. Stored functions can even run SELECT command or
table manipulation commands like INSERT and UPDATE.
The most general difference between procedures and functions is that they are
invoked differently and for different purposes:
3. You cannot invoke a function with a CALL statement, nor can you invoke a
procedure in an expression.
[characteristics]
routine_body
[characteristics]
routine_body
DELIMITER //
For example in a stored procedure, ";" is part of the actual stored procedure and not a
delimiter. So while writing a stored procedure, we can make something else like // as
a delimiter and afterward revert it back by calling the below command.
DELIMITER ;
A MySQL developer can interchangeably use both terms. For example, a database
called test can be created by using either of the CREATE statements below.
There are six types of events associated with a database table when a trigger can be
invoked. It includes:
BEFORE INSERT,
AFTER INSERT,
BEFORE UPDATE,
AFTER UPDATE,
BEFORE DELETE
AFTER DELETE.
For example, BEFORE UPDATE trigger will automatically be invoked and run
before the update is called on the table.
Q. What is mysqldump?Mid
mysqldump is a command line utility for backup and restoration of databases. It
can be run easily to generate a dump of stored databases using the command line.
mysqldump is very simple to use and comes with MySQL installation. It generates
statements to create tables as well as update data. As it does logical backup, backup,
and restore process can be very slow for large databases. The dump file generated
by mysqldump is human readable. A simple command like the below will dump the
database using mysqldump to a human-readable file that can be further compressed
or stored.
Q. How can VIEW be used to provide a security layer for your app?Mid
Views can be used to selectively show limited data to a user.
...
ENGINE=FEDERATED
CONNECTION='mysql://user@remote_hostname:port/federated_schema/table';
Q. What are Derived Columns? What possible problems can a derived column
pose?Mid
A derived column is a column in a database table whose value depends on one or
more columns.
For example consider a Customer table for a gym in which the date of birth, age,
height, weight, and BMI of a customer are stored. As the age of a person can be
derived from his date of birth, age is a derived variable. Similarly, as BMI can be
derived from the height and weight of the customer, BMI is a derived column.
The issue with derived columns is that it keeps redundant data. Redundant data
might further affect data accuracy and consistency. For example, if an update
changes the date of birth of a user but somehow fails to change his age, the data
stored in the table becomes inaccurate.
Q. What is MySQL Workbench?Mid
MySQL Workbench is a visual tool that database architects, developers, and
administrators can use. It can be used for data modeling, database development,
database administration, improving MySQL performance as well as database
migration.
Data Modeling - MySQL workbench provides data modeling features like
visual tool for ER modeling, and reverse and forward engineering to and from
SQL scripts.
FROM table_name;
The intermediate_table created can replace original table. Below statements drop
original table and replace it with the intermediate_table.
Q. What is the cursor used in MySQL? What are the properties of MySQL
cursor?Senior
The cursor is used in stored programs like stored procedures and stored
functions. The cursor is a type of loop that can iterate through the result of
a SELECT query inside stored programs. Here are some properties of the cursor in
MySQL.
Read-only - In MySQL, the cursor is read-only which means data of table
cannot be updated using cursor.
Asensitive - It is asensitive which means cursor will not make temporary copy
of the data rather use original data. One issue with cursor being asensitive is
that if some other process changes the data while cursor is using it, result might
not be predictable.
Consider:
BEGIN
DECLARE a CHAR(16);
DECLARE b, c INT;
OPEN cur1;
OPEN cur2;
read_loop: LOOP
FETCH cur1 INTO a, b;
IF done THEN
LEAVE read_loop;
END IF;
IF b < c THEN
ELSE
END IF;
END LOOP;
CLOSE cur1;
CLOSE cur2;
END;
As a large query can be saved using stored procedure, it helps reduce network
traffic as there is no need of repeated calls to same large query, instead the
database request will just make a call to stored procedure along with required
arguments.
Master slave replication can provide scalability as read operations can easily be
distributed among different servers thus providing load balancing.
As a slave server keeps a live copy of data. A slave can quickly be made master
in case the master server is down, thus it helps reduce downtime.
MySQL has better performance in the case of simple queries. It gets this
advantage as MySQL has fewer features in comparison
to PostgresSQL. PostgresSQL has better support for complex queries.
List partitioning - rows are partitioned based on if the column value is same as
value provided in a list.
Hash partitioning - rows are partitioned based on hash of column value. Hash
partitioning provides a more even partitioning. Hash is computed based on
user-defined hash function.
Key partitioning - rows are partitioned based on a hashing function provided
by MySQL like MD5 hash.
MyISAM was default storage engine before 5.5 while InnoDB is default
storage engine from 5.5 and later versions.
InnoDB has row level locking, which makes it faster in highly concurrent cases
in comparison to MyISAM which has locking at table level. With row level
locking multiple sessions can simultaneously write in a table.
Q. What are some major differences between MySQL and Oracle database?
Senior
Both Oracle and MySQL are relational database management systems supporting
SQL. Here are some major differences between Oracle and MySQL.
MySQL is open source and free. Oracle provides an express edition for free
but it comes with limited features. Oracle provides enterprise-level tools.
MySQL uses username, password, and host for security. Apart from the
username, password Oracle database provides features like profile validation
for security.
Overall MySQL is good for small and medium-sized websites and read-only
websites. Oracle is good for highly scalable enterprise-level applications.
Q. What is Memory Storage Engine in MySQL? What are heap tables?Senior
In MySQL, a Memory storage engine is used to store temporary data in memory. As
data is stored in memory, a memory storage engine can be used for high-performance
non-critical data.
A memory storage engine can be used for data which is updated very frequently. It
can be used for caching. Memory storage engine was called heap table in earlier
versions of MySQL, so sometimes both these terms are used interchangeably.
If the server restarts, the temporary data stored in the Memory storage engine is lost.
Some variable length data types like BLOB and TEXT data types are not supported by
the memory storage engine although VARCHAR is supported.
Q. What is autocommit in MySQL? Can you run a transaction without disabling
autocommit?Senior
In MySQL, if autocommit is disabled, any command you run will not be committed
automatically, which means changes made through these commands will become
permanent only if COMMIT is called. By default autocommit is enabled in MySQL,
which means any change we make is part of a single transaction, commit is done
automatically and it can not be rolled back.
If one of them fails, it causes the entire operation to fail and the subsequent operation
or trigger does not run. So say a BEFORE TRIGGER fails, the operation itself will
not execute and fail. If AFTER TRIGGER fails, the entire statement will fail.
Q. Why you should never use GUIDs as part of the clustered index?Expert
GUIDs are not sequential, thus if they are part of the clustered index, every time you
insert a new record, the database would need to rearrange all its memory pages to find
the right place for insertion, in the case with int(bigint) auto-increment, it would be
just last page.
Q. Which is better for JOIN & INSERT - PostgreSQL or MySQL?Expert
In PostgreSQL, all tables are heap tables. In MySQL, all InnoDB tables are btree
indexes with the tuple in the payload. This means that primary key lookups are faster
on MySQL but general queries are faster on PostgreSQL. It also means you typically
need more indexes on MySQL which will slow down writes.
For example, the following query I would expect to perform better on MySQL than
PostgreSQL:
FROM users u
Provided that both tables share the same primary key (u.id and p.user_id), there are
thousands of rows in both tables, and so forth.
On the other hand, I would expect the following query to perform better on
PostgreSQL than MySQL in a db too big to fit in memory, non-cached data, proper
indexes, decent-sized tables, etc:
FROM company c
In this case you are having to utilize other indexes, which means a lot of extra random
disk I/O on MySQL.
The second issue I would expect would be write performance. I would expect
PostgreSQL to generally win here due to the fact that heap tables allow inserts
wherever it is convenient, and fewer indexes maintained would be helpful too.
Q. What is the use of SAVEPOINT in MySQL?Expert
SAVEPOINT is like a bookmark while running statements in transaction mode. I
helps rolling back to a specific location in the transaction. Below command can be
used to create a save point while running MySQL in transaction mode.
SAVEPOINT savepointName;
And current transaction can be rolled back to desired saved save point location by
running below command.
ROLLBACK TO savepointName;
MySQL supports horizontal partitioning but does not support vertical partitioning.
----------------------------------------------------------------------------------------------------------------------------------------
django_interview_questions
Difference between Flask and Django?
Comparison
Django Flask
Factor
Templates,Admin,
Built in Needs to be installed
ORM
Bootstrapping-
Built-it Not available
tool
Nb: Batteries are libraries and tools that are required for common use cases and ORM is
the object relational mapping layer which is used to interact with other relational
databases.
What is Django?
Django is a Python-based free and open-source web framework that follows the model-
template-view architectural pattern.It was also named after Django Reinhardt who was a
jazz guitarist from the 1930s.
SEO Optimized -as from the name it means that adding your website to the search
engine such that it appears in the top results. This is because Django maintains the built
website through URLs rather than the IP addresses on the server, which makes it easy
for SEO engineers to add the website to the server while the web-developer doesn’t
have to convert the URL into some numeric code.
Rapid Development -Django was designed with the intention to make a framework
which takes less time to build web application. The project implementation phase is
takes time but Django creates it rapidly.
Fully loaded framework -Django includes various helping task modules and libraries
which can be used to handle common Web development tasks. Django takes care of
user authentication, content administration, site maps, RSS feeds etc.
High security -thereby helping developers avoid common security mistakes such as
cross-site request forgery (csrf), clickjacking, cross-site scripting, etc It is exceptionally
scalable which in turn helps meet the heaviest traffic demands
Versatile -The logical project structure and MVT architecture of Django provides us with
a solid foundation which can then be used to make whichever application we want to
create.
Scalability -Django is scalable in nature and has ability to quickly and flexibly switch
from small to large scale application project.
Django is called a loosely coupled framework because of its Model View Template
architecture. It helps in separating the server code from the client-related code.
Django’s models and views take care of the code that needs to be run on the server like
getting records from database, etc., and the templates are mostly HTML and CSS that
just need data from models passed in by the views to render them. Since these
components are independent of each other, Django is called a loosely coupled
framework.
Allows rapid development of websites.
Follows the DRY or the Don’t Repeat Yourself Principle which means, one concept or a
piece of data should live in just one place.
Consistent at low as well as high levels.
SQL statements are not executed too many times and are optimized internally.
Can easily drop into raw SQL whenever required.
Flexibility while using URL’s.
Django follows the MVT (Model View Template architecture) which is based on the MVC
(Model View Controller architecture). The main difference between these two is that
Django itself takes care of the controller part.
MVT separates the code into three parts.
Model, View, and Template.
The Model contains the system responsible for dealing with data and databases;
View deals with the design pattern; that is, it decides what data should be displayed,
Template specifies a structure for output.
Data can be populated in a template using placeholders. It defines how the information
is presented. An example is a Generic list view that we can use to display a set of records
from the database.
django-admin is the command-line utility of Django for administrative tasks. Using the
django-admin you can perform a number of tasks as shown below:
Task Command
django-admin help –
To display the list of available commands
command
Task Command
django-admin
To show all the migrations in your project
showmigrations
What are the various files that are created when you create a Django Project?
Explain briefly.
After you create a project using the startproject command, the following files will be
created:
manage.p A command-line utility that allows you to interact with your Django
y project
An empty file that tells Python that the current directory should be
init.py
considered as a Python package
This is an entry-point for the web servers to serve the project you
wsgi.py
have created
Models are a single and definitive source for information about your data. It consists of
all the essential fields and behaviors of the data you have stored. Often, each model will
map to a single specific database table.
In Django, models serve as the abstraction layer that is used for structuring and
manipulating your data.
Django models are a subclass of the django.db.models.Model class and the attributes in
the models represent database fields.
Inheritance
Description
style
Used when you want to use the parent class to hold information
Abstract base
that you don’t want to type for each child model. Here, the
classes
parent class is never used in solitude
Multi-table Used when you have to subclass an existing model and want
inheritance each model to have its own database table
Static files in Django are those files that serve the purpose of additional files such as the
CSS, images or JavaScript files. These files are managed by django.contrib.staticfiles.
These files are created within the project app directory by creating a subdirectory
named as static.
Django includes a “signal dispatcher” which helps allow decoupled applications get
notified when actions occur elsewhere in the framework.
Signals allow certain senders to notify a set of receivers that some action has taken
place. They’re especially useful when many pieces of code may be interested in the same
events.
Some of the signals are as follows:
Signal Description
Signals
To create a Django project, cd into the directory where you would like to create your
project and type the following command:
django-admin startproject Vee NOTE: Here, Vee is the name of the project. You can give
any name that you desire.
What is mixin?
Mixin is a type of multiple inheritance wherein you can combine behaviors and
attributes of more than one parent class.
Mixins provide an excellent way to reuse code from multiple classes. For example,
generic class-based views consist of a mixin called TemplateResponseMixin whose
purpose is to define render_to_response() method. When this is combined with a class
present in the View, the result will be a TemplateView class.
One drawback of using these mixins is that it becomes difficult to analyze what a child
class is doing and which methods to override in case of its code being too scattered
between multiple classes.
The session framework lets you store and retrieve arbitrary data on a per-site-visitor
basis. It stores data on the server side and abstracts the sending and receiving of
cookies. Cookies contain a session ID – not the data itself unless you’re using the cookie
based backend.
When you use a Django Template, it is compiled once (and only once) and stored for
future use, as an optimization. A template can have variable names in double curly
braces, such as {{ myvar1 }} and {{ myvar2 }}.
A Context is a dictionary with variable names as the key and their values as the value.
Hence, if your context for the above template looks like: {myvar1: 101, myvar2: 102},
when you pass this context to the template render method, {{ myvar1 }} would be
replaced with 101 and {{ myvar2 }} with 102 in your template. This is a simplistic
example, but really a Context object is the context in which the template is being
rendered.
As for a ContextProcessor, that is a slightly advanced concept. You can have in your
settings.py file listed a few Context Processors which take in an HttpRequest object and
return a dictionary (similar to the Context object above). The dictionary (context)
returned by the Context Processor is merged into the context passed in by you (the
user) by Django.
A use case for a Context Processor is when you always want to insert certain variables
inside your template (for example the location of the user could be a candidate). Instead
of writing code to insert it in each view, you could simply write a context processor for it
and add it to the TEMPLATE_CONTEXT_PROCESSORS settings in settings.py.
Caching basically means to save the output of an expensive calculation in order to avoid
performing the same calculation again.
Django provides a robust cache system which in turn helps you save dynamic web
pages so that they don’t have to be evaluated over and over again for each request.
Some of the caching strategies of Django are listed below:
Strategy Description
caching
This is actually the default cache in case you have not specified
Local-memory
any other. This type of cache is per-process and thread-safe as
caching
well
Database Cache data will be stored in the database and works very well if
caching you have a fast and well-indexed database server
Middleware is a framework that is light and low-level plugin system for altering Django’s
input and output globally.
It's a framework of hooks into the request/ response processing of Django.
Each component in middleware has some particular task. For example, the
AuthenticationMiddleware is used to associate users with requests using sessions.
Django provides many other middlewares such as cache middleware to enable site-wide
cache, common middleware that performs many tasks such as forbidding access to user
agents, URL rewriting, etc, GZip middleware which is used to compress the content for
browsers, etc.
In order to view all the items from your database, you can make use of the ‘all()’ function
in your interactive shell as follows: XYZ.objects.all() where XYZ is some class that you
have created in your models.
To filter out some element from your database, you either use the get() method or the
filter method as follows:
XYZ.objects.filter(pk=1) XYZ.objects.get(id=1)
In case a user requests a page from some Django powered site, the system follows an
algorithm that determines which Python code needs to be executed.
Here are the steps that sum up the algorithm:
-Django first determines which root URLconf or URL configuration module is to be used
-Then, that particular Python module is loaded and then Django looks for the variable
urlpatterns
-These URL patterns are then run by Django, and it stops at the first match of the
requested URL
-Once that is done, the Django then imports and calls the given view
-In case none of the URLs match the requested URL, Django invokes an error-handling
view
Django basically grew from a very practical need. World Online developers namely
Adrian Holovaty and Simon Willison started using Python to develop its websites. As
they went on building intensive, richly interactive sites, they began to pull out a generic
Web development framework that allowed them to build Web applications more and
more quickly. In summer 2005, World Online decided to open-source the resulting
software, which is, Django.
Django allows you to design your own URLs however you like. The aim is to maintain a
clean URL scheme without any framework limitations.
In order to create URLs for your app, you will need to create a Python module informally
called the URLconf or URL configuration which is pure Python code and is also a
mapping between the URL path expressions to the Python methods.
The length of this mapping can be as long or short as required and can also reference
other mappings.
When processing a request, the requested URL is matched with the URLs present in the
urls.py file and the corresponding view is retrieved.
Django uses its own exceptions as well as those present in Python. Django core
exceptions are present in django.core.exceptions class some of which are mentioned in
the below:
Exception Description
Raised when you try to use your models before the app
AppRegistryNotReady
loading process (initializes the ORM) is completed.
Yes. Hardware is much cheaper when compared to the development time and this is
why Django is designed to make full use of any amount of hardware that you can
provide it.
Django makes use of a “shared-nothing” architecture meaning you can add hardware at
any level i.e database servers, caching servers or Web/ application servers.
Is Django a CMS?
NoSQL basically stands for “not only SQL”. This is considered as an alternative to the
traditional RDBMS or the relational Databases.
Officially, Django does not support NoSQL databases. However, there are third-party
projects, such as Django non-rel, that allow NoSQL functionality in Django. Currently,
you can use MongoDB and Google App Engine.
How can you customize the functionality of the Django admin interface?
You can piggyback on top of an add/ change form that is automatically generated by
Django, you can add JavaScript modules using the js parameter.
This parameter is basically a list of URLs that point to the JavaScript modules that are to
be included in your project within a <script> tag. In case you want to do more rather
than just playing around with from, you can exclusively write views for the admin.
#### What should be done in case you get a message saying “Please enter the correct
username and password” even after entering the right details to log in to the admin
section? In case you have entered the right details and still not able to login to the
admin site, cross verify if the user account has is_active and is_staff attributes set to True.
What should be done in case you are not able to log in even after entering the
right details and you get no error message?
In this case, the login cookie is not being set rightly. This happens if the domain of the
cookie sent out by Django does not match the domain in your browser. For this, you
must change the SESSION_COOKIE_DOMAIN setting to match that of your browser.
How can you limit admin access so that the objects can only be edited by those
users who have created them?
Django’s ModelAdmin class provides customization hooks using which, you can control
the visibility and editability of objects in the admin. To do this, you can use the
get_queryset() and has_change_permission().
What to do when you don’t see all objects appearing on the admin site?
Inconsistent row counts are a result of missing Foreign Key values or if the Foreign Key
field is set to null=False. If the ForeignKey points to a record that does not exist and if
that foreign is present in the list_display method, the record will not be shown the
admin changelist.
The csrf_token is used for protection against Cross-Site Request Forgeries. This kind of
attack takes place when a malicious website consists of a link, some JavaScript or a form
whose aim is to perform some action on your website by using the login credentials of a
genuine user.
First, make sure that your DEBUG setting is set to True. Then, type the following
commands:
#### Is it mandatory to use the model/ database layer? No. The model/ database layer
is actually decoupled from the rest of the framework.
You can make use of the RequestContext in case all your templates require the same
objects, such as, in the case of menus. This method takes an HttpRequest as its first
parameter and it automatically populates the context with a few variables, according to
the engine’s context_processors configuration option.
#Q1. What
is the
differenc
e between
shallow
copy and
deep copy
?
Ans : Shallow copy is used when a new instance type gets created and it keeps
the values that are copied in the new instance.
Shallow copy is used to copy the reference pointers just like it copies the
values. These references point to the original objects
and the changes made in any member of the class will also affect the original
copy of it. Shallow copy allows faster execution of the program
and it depends on the size of the data that is used.
[Shallow copy doesn't copy the admin structure, just copies the top level
references and the original values ]
Deep copy is used to store the values that are already copied. Deep copy
doesn’t copy the reference pointers to the objects.
It makes the reference to an object and the new object that is pointed by some
other object gets stored.
The changes made in the original copy won’t affect any other copy that uses
the object.
Deep copy makes execution of the program slower due to making certain copies
for each object that is been called.
[Deep copy has to copy all the references , all the admin structures , all the
values each and everything]
l1= [1,2,3,4]
l2 = l1
l2.append(10)
l2
[1,2,3,4,10]
l1
[1,2,3,4,10]
import copy
l1
[1,2,3,4,10]
l3 = copy.copy(l1)
l3
[1,2,3,4,10]
l3.append(11)
l1
[1,2,3,4,10]
l2
[1,2,3,4,10]
l3
[1,2,3,4,10,11]
l4 = copy.deepcopy(l2)
l4
[1,2,3,4,10]
#Q2. What is the difference between list and tuples?
Ans: Lists are mutable i.e they can be edited. Tuples are immutable (tuples
are lists which can’t be edited).
Lists are slower than tuples.
List Syntax: list_1 = [10, ‘Chelsea’, 20]
Tuple Syntax: tup_1 = (10, ‘Chelsea’ , 20)
l1= [1,2,3,4]
l1.append(40) // is possible
t1= (1,2,3,4)
t1.append(40) // is NOT possible
import multiprocessing
import threading
Ans: The Ternary operator is the operator that is used to show the conditional
statements.
This consists of the true or false values with a statement that has to be
evaluated for it.
x,y = 23,50
big = x if x>y else y
big
50
#Q5. What is monkey patching in Python?
Ans: In Python, the term monkey patch only refers to dynamic modifications of
a class or module at run-time.
# m.py
class MyClass:
def f(self):
print "f()"
import m
def monkey_f(self):
print "monkey_f()"
m.MyClass.f = monkey_f
obj = m.MyClass()
obj.f()
The output will be as below:
monkey_f()
As we can see, we did make some changes in the behavior of f() in MyClass
using the function we defined, monkey_f(), outside of the module m.
#Q6. How can you randomize the items of a list in place in Python?
Ans:
from random import shuffle
x = ['Keep', 'The', 'Blue', 'Flag', 'Flying', 'High']
shuffle(x)
print(x)
['Flying', 'Keep', 'Blue', 'High', 'The', 'Flag']
Ans:
#Q8. Looking at the below code, write down the final values of A0, A1, …An.
A0 = dict(zip(('a','b','c','d','e'),(1,2,3,4,5)))
A1 = range(10)A2 = sorted([i for i in A1 if i in A0])
A3 = sorted([A0[s] for s in A0])
A4 = [i for i in A1 if i in A3]
A5 = {i:i*i for i in A1}
A6 = [[i,i*i] for i in A1]
print(A0,A1,A2,A3,A4,A5,A6)
Ans: To modify the strings, Python’s “re” module is providing 3 methods. They
are:
Ans: Inheritance allows One class to gain all the members(say attributes and
methods) of another class. Inheritance provides code reusability,
makes it easier to create and maintain an application. The class from which we
are inheriting is called super-class and the class
that is inherited is called a derived / child class.
Ans. The developer provides the Model, the view and the template then just
maps it to a URL and Django does the magic to serve it to the user.
It follows the MTV (Model template view pattern).
Ans: You can use the command edit mysite/setting.py , it is a normal python
module with module level representing Django settings.
Django uses SQLite by default; it is easy for Django users as such it won’t
require any other type of installation.
In the case your database choice is different that you have to the
following keys in the DATABASE ‘default’ item to match your database
connection settings.
DATABASES = {
'default': {
'ENGINE' : 'django.db.backends.sqlite3',
'NAME' : os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
def Current_datetime(request):
now = datetime.datetime.now()
html = "<html><body>It is now %s</body></html>" % now
return HttpResponse(html)
Returns the current date and time, as an HTML document
Ans: The template is a simple text file. It can create any text-based
format like XML, CSV, HTML, etc.
A template contains variables that get replaced with values when the
template is evaluated and tags (% tag %)
that controls the logic of the template.
Ans: Django provides session that lets you store and retrieve data on a
per-site-visitor basis.
Django abstracts the process of sending and receiving cookies, by placing a
session ID cookie on the client side,
and storing all the related data on the server side.
So the data itself is not stored client side. This is nice from a security
perspective.
#Q6. List out the inheritance styles in Django.
i. Abstract Base Classes: This style is used when you only wants parent’s
class to hold information that you don’t want to type out for each child
model.
ii. Multi-table Inheritance: This style is used If you are sub-classing an
existing model and need each model to have its own database table.
iii. Proxy models: You can use this model, If you only want to modify the
Python level behavior of the model, without changing the model’s fields.
Ans: It allows you to divide code modules into logical groups to make it
flexible to change
To ease the website administration, it provides auto-generated web admin
It provides pre-packaged API for common user tasks
It gives you template system to define HTML template for your web page to
avoid code duplication
It enables you to define what URL be for a given function
It enables you to separate business logic from the HTML
Everything is in python
Ans: There are three main things required to set up static files in Django
#Q13. Explain the migration in Django and how you can do in SQL?
Migrate
Makemigrations
Sqlmigrate
To do the migration in SQL, you have to print the SQL statement for
resetting sequences for a given app name.
django-admin.py sqlsequencreset
Use this command to generate SQL that will fix cases where a sequence is
out sync with its automatically incremented field data.
#Q14. Mention what command line can be used to load data into Django?
Ans: To load data into Django you have to use the command line Django-
admin.py loaddata.
The command line will searches the data and loads the contents of the named
fixtures into the database.
This command line executes over the entire source tree of the current
directory and abstracts all the strings marked for translation.
It makes a message file in the locale directory.
Ans:
Below are the usage of middlewares in Django-
•Session management
•Cross-site request forgery protection
•Use authentication
•Content Gzipping
Ans: Yes, Django is quite stable. Many companies like Disqus, Instagram,
Pinterest, and Mozilla have been using Django for many years.
Ans: Few caching strategies that are available in Django are as follows:-
Ans: Signals are pieces of code which contain information about what is
happening.
A dispatcher is used to sending the signals and listen for those signals.
#Q24. What is the role of Cookie in Django?
The set_cookie() method is used to set a cookie and get() method is used to
get the cookie.
Django Interview
Basics
Q What is django? What do you like about it (Can be re-phrased as what are the
features of django?)
Ans - Django is a high-level Python web framework that encourages rapid development
and clean, pragmatic design.
Features :
Benefits :
Speed: Its slogan is ‘The Web framework for perfectionists with deadlines‘, so it is
focused on web-dev tasks made fast. Django was created with the helpful mindset of
allowing devs to realize ideas as quickly as possible, with less code.
Security: Avoid common security mistakes with its user authentication system and secure
password management.
Scalable: Meet heavy traffic demands with its “shared-nothing” architecture. Add
hardware at any level, including database servers.
Out of the box features: Without any extra downloads, Django handles user
authentication, content administration, site maps, RSS feeds, and more.
Q. What is the latest version of Django and which one you are uisng?
Ans - The latest version of django is, Django - 3.0. I am using Django 2.2 which is LTS
(Long term support) release.
Ans - Django follows MVC pattern very closely but it uses slightly different terminology.
Django is essentially an MTV (Model-Template-View) framework. Django uses the term
Templates for Views and Views for Controller. In other words, in Django views are called
templates and controllers are called views. Hence our HTML code will be in templates
and Python code will be in views and models.
That’s why Django is a rapid development framework and this level of code reusability is
not there in other frameworks.
|── manage.py
└─┬ ProjectFolder
├── settings.py
├── init.py
├── urls.py
└─┬ wsgi.py
The last four files are inside a directory, which is at the same level of manage.py.
Here the structure is very logical, and the names of these files and their purpose should
remain intact.
manage.py is the command line utility of your Django project and this file is used to
control your Django project on the server or even to begin one.
When Django server is started, the manage.py file searches for settings.py file, which
contains information of all the applications installed in the project, middleware used,
database connections and path to the main urls config.
The urls.py file is like a map of your whole web-project, this file examines URL and calls
the right view function or transports the URL to another application specific urls-config
file. This is like the main URL linker and any app installed in the settings.py which you
wish to be searched by the URL should have a link here.
The init.py file is an empty file which is there to make the python interpreter understand
that the directory consisting settings.py is a module/ package.
The wsgi.py file is for the server format WSGI, which Django supports natively. We can
customize that for other server formats.
Ans. When a user enters a URL in the browser the same request is received by the
Django Server. The server then looks for the match of the requested URL in its URL-
config and if the URL matches, it returns the corresponding view function. It will then
request the data from the Model of that application, if any data is required and pass it
to the corresponding template which is then rendered in the browser, otherwise, a 404
error is returned.
Ans. Django is called a loosely coupled framework because of the MTV architecture it’s
based on. Django’s architecture is a variant of MVC architecture and MTV is useful
because it completely separates server code from the client’s machine.
Django’s Models and Views are present on the client machine and only templates return
to the client, which are essentially HTML, CSS code and contains the required data from
the models.
These components are totally different from each other and therefore, front-end
developers and backend developers can work simultaneously on the project as these
two parts changing will have little to no effect on each other when changed.
Q. Explain the importance of settings.py file and what data/ settings it contains.
Ans. When Django server starts, it first looks for settings.py. As the name settings, it is
the main settings file of your web application. Everything inside your Django project like
databases, backend engines, middlewares, installed applications, main URL
configurations, static file addresses, templating engines, allowed hosts and servers and
security key stores in this file as a list or dictionary.
So, when your Django server starts it executes settings.py file and then loads particular
engines and databases so that when a request is given it can serve the same quickly.
Ans - You can use the command edit mysite/setting.py , it is a normal python module
with module level representing Django settings.
DATABASES = {
'default': {
# 'ENGINE': 'django.db.backends.sqlite3',
# 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
# 'OPTIONS': {
# 'timeout': 20,
# }
'ENGINE': 'django.db.backends.postgresql',
'NAME': 'name_of_database',
'USER': 'postgres',
'PASSWORD': 'password',
'HOST': 'localhost',
'PORT': 5432,
}
}
Django uses SQLite by default; it is easy for Django users as such it won’t require any
other type of installation. In the case your database choice is different that you have to
the following keys in the DATABASE ‘default’ item to match your database connection
settings
Ans. Django ORM is one of the special feature-rich tools in Django. ORM is an acronym
for Object-Relational Mapper. This ORM enables a developer to interact with a database
in a pythonic way.
Django ORM is the abstraction between models (web application data-structure) and
the database where the data is stored. It makes possible to retrieve, save, delete and
perform other operations over the database without ever writing any SQL code.
It also covers many loopholes and takes all the field attributes and gives you more
control over your code in Python rather than any database language.
Q. Mention what does the Django templates consists of? How does Django
Templating work?
Ans - The template is a simple text file. It can create any text-based format like XML,
CSV, HTML, etc. A template contains variables that get replaced with values when the
template is evaluated and tags (% tag %) that controls the logic of the template.
Django templating engine handles templating in the Django framework. There are some
template syntaxes which declares variables, control logic, filters, and comments. After
putting these inside the HTML structure, when the web page is requested and called
upon by the view function, the Django Template engine gets two things, the HTML
structure with variables in place and the data to replace with those variables. It replaces
the variables with data while also executing the control logic and generating filters. It
renders the required HTML and sends it to the browser when all the work gets
complete.
Ans - In Django, the session framework enables you to store and retrieve arbitrary data
on a per-site-visitor basis. It stores data on the server side and abstracts the receiving
and sending of cookies. Session can be implemented through a piece of middleware.
Ans - Migration in Django is to make changes to your models like deleting a model,
adding a field, etc. into your database schema. There are several commands you use to
interact with migrations.
Migrate Makemigrations Sqlmigrate To do the migration in SQL, you have to print the
SQL statement for resetting sequences for a given app name.
./manage.py sqlsequencreset
Use this command to generate SQL that will fix cases where a sequence is out sync with
its automatically incremented field data.
Ans - Unicode is an international encoding standard that works with different languages
and scripts. It consists of letters, digits or symbols representing characters from across
the world. UTF-8 is a type of encoding, a way of storing the code points of Unicode in a
byte form, so you can send Unicode strings over the network or store them in files.”
Proxy models: You can use this model, If you only want to modify the Python level
behavior of the model, without changing the model’s fields
Intermediate
Q. What is WSGI?
Ans - Django, being a web framework, needs a web server in order to operate. And since
most web servers don’t natively speak Python, we need an interface to make that
communication happen. This is where WSGI comes.
WSGI is the main Python standard for communicating between Web servers and
applications, but it only supports synchronous code.
Note - Django begins its path towards asynchronous code capability. With djnago 3.0, it
now supports running as an ASGI (Asynchronous Server Gateway Interface) application.
ASGI provides an interface between asynchronous Python web servers and frameworks.
This is major benefit for web programming. Instead of running 10 queries one after the
other and waiting for each one to come back, you can run 10 queries at the same time,
while hitting your cache and making a HTTP request simultaneously on a single thread.
Ans - it’s sometimes useful to pre-populate your database with hard-coded data when
you’re first setting up an app. You can provide initial data with fixtures.
As an example, though, here’s what a fixture for a Person model might look like in JSON:
[
{
"model": "myapp.person",
"pk": 1,
"fields": {
"first_name": "John",
"last_name": "Lennon"
}
},
{
"model": "myapp.person",
"pk": 2,
"fields": {
"first_name": "Paul",
"last_name": "McCartney"
}
}
]
You can load data by calling
Ans - Middlewares are hooks to modify Django request or response object. It’s a light,
low-level “plugin” system for globally altering Django’s input or output.
You can use middleware if you want to modify the request i.e HttpRequest object which
is sent to the view. Or you might want to modify the HttpResponse object returned from
the view.
An example middleware
class BookMiddleware(object):
def process_request(self, request):
print "Middleware executed"
Add this middleware in MIDDLEWARE_CLASSES
MIDDLEWARE_CLASSES = (
'books.middleware.BookMiddleware',
...
)
Make request to any url. This should get printed on runserver console
Middleware executed
**Q. What are decorators? Name some useful built-in django decorators.
Ans - By definition, a decorator is a function that takes another function and extends the
behavior of the latter function without explicitly modifying it.
Example:
def login_required(function):
def wrap(request, *args, **kwargs):
user = request.user
if user.is_authenticated():
return function(request, *args, **kwargs)
else:
raise PermissionDenied
wrap.__doc__ = function.__doc__
wrap.__name__ = function.__name__
return wrap
Some useful built-in decorators
login_required
@group_required(‘admins’, ‘seller’)
def my_view(request, pk)
ajax_required: checks if the request is an AJAX request.
timeit: This decorator is very helpful if you need to improve the response time of one of
then our views or if you just want to know how long it takes to run.
**Q. What are mixins?? Name some useful built-in django mixins.
Ans - Python supports a simple type of multiple inheritence which allows the creation of
Mixins, which are sort of class that is used to mix-in extra properties and methods into a
class.This allows you to create class in a compositional style.
Example:
class Mixin1(object):
def test(self):
print "Mixin1"
class Mixin2(object):
def test(self):
print "Mixin2"
Q. What is signals and how to use it? What are two important parameter in
signals?
Ans - Signals allow certain senders to notify a set of receivers that some action has
taken place. They’re especially useful when many pieces of code may be interested in
the same events.
Connecting Signals
@receiver(post_save, sender=MyModel)
def my_function_post_save(sender, **kwargs):
# do the action…
Every time that a MyModel’s instance ends to run its save() method, the
my_function_post_save will start to work.
Ans - First, You’ll need to tell Django what your database connection parameters are,
and what the name of the database is. Do that by editing the DATABASES setting and
assigning values to the following keys for the 'default' connection.
Django comes with a utility called inspectdb that can create models by introspecting an
existing database. Create models.py file based on output of same command
Example - models.py
# Action description
change_rating.short_description = "Mark Selected Products as Excellent"
class ProductA(admin.ModelAdmin):
list_display = ('name', 'description', 'mfg_date', 'rating')
list_filter = ('mfg_date', )
actions = [change_rating]
admin.site.register(Product, ProductA)
admin.site.unregister(Group)
Ans - Serving the site and your static files from the same server:
Serving the site and your static files from dedicated server
Since your static file server won’t be running Django, you’ll need to modify the
deployment strategy to look something like:
There’s any number of ways you might do this, but if the provider has an API, you can
use a custom file storage backend to integrate the CDN with your Django project. If
you’ve written or are using a 3rd party custom storage backend, you can tell collectstatic
to use it by setting STATICFILES_STORAGE to the storage engine.
STATICFILES_STORAGE = 'myproject.storage.S3Storage'
Once that’s done, all you have to do is run collectstatic and your static files would be
pushed through your storage package up to S3. If you later needed to switch to a
different storage provider, you may only have to change your STATICFILES_STORAGE
setting.
Ans. Django supports many popular templating engines and by default, it comes with
one very powerful templating engine. Jinja Templating is a very popular templating
engine for Python, the latest version in the market is Jinja 2. There are some features of
Jinja templating which makes it a better option then the default template system in
Django.
Sandbox Execution – This is like a sandbox or a protected framework for automating the
testing process. HTML Escaping – Jinja 2 provides automatic HTML Escaping, as <, >, &
characters have special values in templates and if used as regular text, these symbols
can lead to XSS Attacks which Jinja deals with automatically. Template Inheritance
Generates HTML templates much faster than default engine Easier to debug, compared
to default engine.
Advanced
Ans - For this, you can query the Session model for non-expired sessions, then turn the
session data into users.
from django.contrib.auth.models import User
from django.contrib.sessions.models import Session
from django.utils import timezone
def get_all_logged_in_users():
# Query all non-expired sessions
# use timezone.now() instead of datetime.now() in latest versions of Django
sessions = Session.objects.filter(expire_date__gte=timezone.now())
uid_list = []
Django interview question that I've been asked. ##Django - Interview Questions
Q#1. What do you like about django? Or the same question can be re-phrased as what
are the features of django?
Q#2. What architecture does Django follow? Or Is Django an MVC framework? Answer:
Django follows MTV pattern/architecture. MTV stands for Model, Template, View.
Q#3. How to write views in django? Answer. There are 2 primary methods to write views
in django. First is the django function based views and second is django’s class based
views. Function based views are simple and are better option to go for if you know that
you have to create less than 8-10 views.
Q#4. What’s the current version of Django? Or (What django version are you currently
working with)? Answer. Django 2.2
Q#5. How to create a model in Django? Or Can you name some model fields that you’ve
created before during your projects? Answer. Models in django inherit from the models
class. The class offers multiple fields to work with. Fields that I’ve used and are used
extensively in any project are:
Q#6. How would you check your django version? Answer. Python -m django –version
Q#7. Can you use MySQL with Django? Answer. Yes, you can. You can use, mysql, sqlite,
oracle, postgresql etc
Q#9. What does makemigrations command do? Answer. It creates migrations for the
models that you define in models.py file.
Q#10. What popular websites use django? Can you name some? Answer. Disqus,
Instagram, Mozilla, NASA, The Washington Post etc.
Q#11. So you said, django follows MTV pattern. You mean django doesn’t follow MVC
right? Answer. MTV closely resembles MVC. Because, the framework handles the
controller part itself so most things happen only in models, views and templates.
Q#13. Think of this scenario. You’re a django developer here. A big company, take Tesla
as example, wants us to make them a website where the website handles all the
feedback from the clients that are currently using tesla as their primary vehicle of
transport. How would you make that type of website, sometimes, you might get 1000
reviews/feedbacks in an hour. How would you design the database too. Also tell about
the security. If you know about front-end, what front-end technology would you prefer?
Anwer. Start by asking further questions and remove any doubt or question you have.
Tell them how you would make it. When it comes to database design, explain all the
fields that you are going to use. If the feedback is coming from unregistered clients than
you might not know their location. In that case, you will determine the location using ip-
location services and store the ip-address in GenericIPAddressField() field. Continue with
more explanation and if you know any front-end technology than explain why would
you prefer that particular technology instead of certain other technologies available in
the market
FLASK:
Quickstart
Installation
pip install flask
Minimal app
Code Here
app = Flask(__name__)
@app.route("/")
def hello_world():
return "<p>Hello, World!</p>"
if __name__=="__main__":
app.run()
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.
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.
Debug Mode
Code Here
app = Flask(__name__)
@app.route("/")
def hello_world():
return "<p>Hello, World!</p>"
Warning The debugger allows executing arbitrary Python code from the browser. It is
protected by a pin, but still represents a major security risk. Do not run the development
server or debugger in a production environment.
Routing
Code Here
app = Flask(__name__)
@app.route('/')
def index():
return 'This is Index Page'
@app.route('/login')
def login():
return 'This is Login Page'
@app.route('/hello')
def hello():
return 'Hello, World'
if __name__=="__main__":
app.run(debug=True)
Modern web applications use meaningful URLs to help users. Users are more likely to
like a page and come back if the page uses a meaningful URL they can remember and
use to directly visit a page.
Use the route() decorator to bind a function to a URL.
Rendering Templates
Code Here
app = Flask(__name__)
@app.route("/")
def index():
return render_template('index.html')
@app.route("/")
def about():
return render_template('about.html')
if __name__=="__main__":
app.run()
In flask, html file are served from the 'templates' folder by default and all the
static file; images, css, js, etc are served from the 'static' folder.
These folders should be present in the root directly of your python application
URL Variables
Code Here
app = Flask(__name__)
@app.route('/')
def index():
return render_template('index.html')
# string
@app.route('/string/<string:value>')
def string(value):
return f"<p>Hi this is a string value {value}</p>"
# int
@app.route('/int/<int:value>')
def int(value):
return f"<p>Hi this is a int value {value}</p>"
# float
@app.route('/float/<float:value>')
def float(value):
return f"<p>Hi this is a float value {value}</p>"
# path
@app.route('/path/<path:value>')
def path(value):
return f"<p>Hi this is a path value {value}</p>"
# uuid
@app.route('/uuid/<uuid:value>')
def uuid(value):
return f"<p>Hi this is a uuid value {value}</p>"
if __name__=="__main__":
app.run(debug=True)
You can add variable sections to a URL by marking sections with <variable_name>. Your
function then receives the <variable_name> as a keyword argument. Optionally, you can
use a converter to specify the type of the argument like converter:variable_name.
Type Value Use
string (default) accepts any text without a slash string:value
Redirection
Code Here
app = Flask(__name__)
@app.route('/about')
def about():
return "This is about"
@app.route('/result/<name>/<age>')
def result(name, age):
return render_template('result.html', name=name, age=age)
app.run()
The canonical URL for the projects endpoint has a trailing slash. It’s similar to a folder in
a file system. If you access the URL without a trailing slash (/about), Flask redirects you
to the canonical URL with the trailing slash (/about/).
Message Flashing
Code Here
app = Flask(__name__)
app.secret_key = b'_5#y2L"F4Q8z\n\xec]/'
@app.route('/')
def index():
return render_template('index.html')
if __name__=="__main__":
app.run(debug=True)
Good applications and user interfaces are all about feedback. If the user does not get
enough feedback they will probably end up hating the application. Flask provides a
really simple way to give feedback to a user with the flashing system. The flashing
system basically makes it possible to record a message at the end of a request and
access it next request and only next request. This is usually combined with a layout
template that does this. Note that browsers and sometimes web servers enforce a limit
on cookie sizes. This means that flashing messages that are too large for session cookies
causes message flashing to fail silently.
JAVA INTERVIEW QUESTIONS
Each Java source file is compiled into a bytecode file, which is executed by the JVM.
Java was designed to allow application programs to be built that could be run on any
platform, without having to be rewritten or recompiled by the programmer for each
separate platform.
A Java virtual machine makes this possible because it is aware of the specific
instruction lengths and other particularities of the underlying hardware platform.
Q. What is a Java Applet?Entry
A Java Applet is a program that can be included in an HTML page and be executed in
a java enabled client browser. Applets are used for creating dynamic and interactive
web applications.
Q. What is JDBC?Entry
JDBC is an abstraction layer that allows users to choose between databases. JDBC
enables developers to write database applications in Java without having to concern
themselves with the underlying details of a particular database.
Q. What is a JSP Page?Entry
A Java Server Page (JSP) is a text document that contains two types of text:
Static data can be expressed in any text-based format, such as HTML or XML. JSP is
a technology that mixes static content with dynamically-generated content.
Q. What is the difference between an Applet and a Java Application?Entry
The Java Runtime Environment (JRE) is basically the Java Virtual Machine
(JVM) where your Java programs are being executed. It also includes browser
plugins for applet execution.
The Java Development Kit (JDK) is the full-featured Software Development
Kit for Java, including the JRE, the compilers, and tools (like JavaDoc, and
Java Debugger), in order for a user to develop, compile and execute Java
applications.
Q. What is a Servlet?Entry
The servlet is a Java programming language class used to process client requests and
generate dynamic web content.
Servlets are mostly used to process or store data submitted by an HTML form,
provide dynamic content and manage state information that does not exist in the
stateless HTTP protocol.
Q. What are the two types of Exceptions in Java? Which are the differences
between them?Entry
Java has two types of exceptions: checked exceptions and unchecked exceptions.
Finally, each servlet is able to serve multiple requests in parallel using multithreading.
Q. What’s the difference between sendRedirect and forward methods?Junior
The sendRedirect method creates a new request, while the forward method just
forwards a request to a new target. The previous request scope objects are not
available after a redirect, because it results in a new request.
On the other hand, the previous request scope objects are available after forwarding.
FInally, in general, the sendRedirect method is considered to be slower compared to
the forward method.
Q. What are Declarations?Junior
Declarations are similar to variable declarations in Java. Declarations are used to
declare variables for subsequent use in expressions or scriptlets. To add a declaration,
you must use the sequences to enclose your declarations.
Q. What is the purpose of Garbage Collection in Java, and when is it used?Junior
The purpose of garbage collection is to identify and discard those objects that are no
longer needed by the application, in order for the resources to be reclaimed and
reused.
Q. What is the reflection and why is it useful?Junior
The name reflection is used to describe code which is able to inspect other code in the
same system (or itself) and to make modifications at runtime.
For example, say you have an object of an unknown type in Java, and you would like
to call a 'doSomething' method on it if one exists. Java's static typing system isn't
really designed to support this unless the object conforms to a known interface, but
using reflection, your code can look at the object and find out if it has a method called
'doSomething' and then calls it if you want to.
method.invoke(foo, null);
Q. What is the design pattern that Java uses for all Swing components?Junior
The design pattern used by Java for all Swing components is the Model View
Controller (MVC) pattern.
Q. What is the purpose Class.forName method?Junior
The java.lang.Class.forName(String name, boolean initialize, ClassLoader loader)
the method returns the Class object associated with the class or interfaces with the
given string name, using the given class loader.
Q. What is Function Overriding and Overloading in Java?Junior
Method overloading in Java occurs when two or more methods in the same
class have the exact same name, but different parameters.
class Dog{
System.out.println("woof ");
//overloading method
System.out.println("woof ");
}
}
On the other hand, method overriding is defined as the case when a child class
redefines the same method as a parent class. Overridden methods must have the
same name, argument list, and return type. The overriding method may not
limit the access of the method it overrides.
class Dog{
System.out.println("woof ");
System.out.println("sniff ");
System.out.println("bowl");
}
public class OverridingTest{
dog.bark();
The generated servlet class is invoked, in order to handle the browser’s request. Once
the execution of the request is over, the servlet sends a response back to the client.
Q. What are Expressions?Junior
A JSP expression is used to insert the value of a scripting language expression,
converted into a string, into the data stream returned to the client, by the web server.
Expressions are defined between <% = and %> tags.
Q. How does Garbage Collection prevent a Java application from going out of
memory?Junior
It doesn’t! Garbage Collection simply cleans up unused memory when an object goes
out of scope and is no longer needed. However, an application could create a huge
number of large objects that causes an OutOfMemoryError .
Q. Explain Serialization and Deserialization.Junior
Java provides a mechanism, called object serialization where an object can be
represented as a sequence of bytes and includes the object’s data, as well as
information about the object’s type, and the types of data stored in the object.
Include directive: it is used to include a file and merges the content of the file
with the current page.
Page directive: it is used to define specific attributes in the JSP page, like the
error page and buffer.
Taglib: it is used to declare a custom tag library that is used on the page.
Q. What are the Data Types supported by Java? What are Autoboxing and
Unboxing?Junior
The eight primitive data types supported by the Java programming language are:
byte
short
int
long
float
double
boolean
char
Autoboxing is the automatic conversion made by the Java compiler between the
primitive types and their corresponding object wrapper classes. If the conversion goes
the other way, this operation is called unboxing.
Q. What is the difference between processes and threads?Junior
The main difference between them is that
a Process is a program which is executing some code and
a Thread is an independent path of execution in the process.
A process can have more than one thread for doing independent task e.g. a thread for
reading data from disk, a thread for processing that data and another thread for
sending that data over the network.
Q. What will happen to the Exception object after exception handling?Junior
The exception object will be garbage collected in the next garbage collection.
Q. What does the static keyword mean? Can you override the private or static
methods in Java?Junior
The static keyword denotes that a member variable or method can be
accessed, without requiring an instantiation of the class to which it belongs.
A user cannot override static methods in Java, because method overriding is based
upon dynamic binding at runtime and static methods are statically binded at compile
time. A static method is not associated with any instance of a class so the concept is
not applicable.
Q. What is the difference between Exception and Error in Java?Junior
The Last thing to mention is that the finally block is used to release resources like I/O
buffers, database connections, etc.
Q. What is an Iterator?Junior
The Iterator provides a number of methods that are able to iterate over any Collection.
Each Java Collection contains the Iterator method that returns an Iterator instance.
Iterators are capable of removing elements from the underlying collection during the
iteration.
Q. When does an Object become eligible for Garbage Collection in Java?Junior
A Java object is subject to garbage collection when it becomes unreachable to the
program in which it is currently used.
Q. What is pass by reference and pass by value?Junior
When an object is passed by value, this means that a copy of the object is
passed. Thus, even if changes are made to that object, it doesn’t affect the
original value.
When an object is passed by reference, this means that the actual object is not
passed, rather a reference of the object is passed. Thus, any changes made by
the external method, are also reflected in all places.
Each method must explicitly specify which exceptions do not handle, so the callers of
that method can guard against possible exceptions. Finally, multiple exceptions are
separated by a comma.
Q. What happens when an Applet is loaded?Mid
First of all, an instance of the applet’s controlling class is created. Then, the applet
initializes itself and finally, it starts running.
Q. Explain the life cycle of a Servlet.Mid
At every client’s request, the Servlet Engine loads the servlets and invokes its init
methods, in order for the servlet to be initialized.
Then, the Servlet object handles all subsequent requests coming from that client, by
invoking the service method for each request separately.
Heap memory consists of live and dead objects. Live objects are accessible by the
application and will not be a subject of garbage collection. Dead objects are those
which will never be accessible by the application but have not been collected by the
garbage collector yet. Such objects occupy the heap memory space until they are
eventually collected by the garbage collector.
Q. What differences exist between Iterator and ListIterator?Mid
An Iterator can be used to traverse the Set and List collections, while
the ListIterator can be used to iterate only over List .
The Iterator can traverse a collection only in the forward direction, while
the ListIterator can traverse a List in both directions.
The ListIterator implements the Iterator interface and contains extra
functionality, such as adding an element, replacing an element, getting the
index position for previous and next elements, etc
Q. What is the difference between doGet() and doPost()?Mid
doGET: The GET method appends the name-value pairs on the request’s URL.
Thus, there is a limit on the number of characters and subsequently on the
number of values that can be used in a client’s request. Furthermore, the values
of the request are made visible and thus, sensitive information must not be
passed in that way.
doPOST: The POST method overcomes the limit imposed by the GET request,
by sending the values of the request inside its body. Also, there is no limitations
on the number of values to be sent across. Finally, the sensitive information
passed through a POST request is not visible to an external client.
Those servlets extending the GenericServlet class shall override the service method.
Finally, in order to develop an HTTP servlet for use on the Web that serves requests
using the HTTP protocol, your servlet must extend the HttpServlet instead.
Q. What is a Constructor, Constructor Overloading, and Copy-Constructor in
Java?Mid
A constructor gets invoked when a new object is created. Every class has a
constructor In case the programmer does not provide a constructor for a class, the Java
compiler (Javac) creates a default constructor for that class.
The constructor overloading is similar to method overloading in Java. Different
constructors can be created for a single class.
Each constructor must have its own unique parameter list. Finally, Java does support
copy constructors like C++, but the difference lies in the fact that Java doesn’t create a
default copy constructor if you don’t write your own.