PythonAnyWhere is a nice place

PythonAnyWhere is a real cool place to create your Python web application – absolutely free – and share with the world.



And I have very recently created a simple Python Tutorials for Beginners up there. The design is quite simple and I think not attractive. It is for the beginners. It looks like this:



I would also like the DropBox share link of the file and taste how it works!
The HTML Design at DropBox

Loops in Python

‘While loop’ is the simplest form of loop in Python. But you need to understand it properly. Otherwise it can end up in eating up your memory running the infinity loop. Usually most of the jobs are done by ‘for loop’. But in some special cases, you need to use ‘while loop’. A basic understanding is important.

While Loops

In plain English we often say – ‘While it is true it keeps on running. While it is not true it stops.’ Logically same thing happens here. While a statement is true, the process is going on. You need a mechanism to stop that process. That is important. Otherwise that statement will eat up your memory.
Consider this code:

b = 1
while b < 50:
    b = b + 1

What does it mean? It means, the statement ‘b is less than 50’ is true until the suite or block of code is true inside it. Inside the block we wrote ‘b = b + 1’ and before the beginning of the while loop we defined the value of b as 1.
So in each step b progresses by adding 1 in its value and finishes at 49. In the output you will get 1 to 49.

Continue reading “Loops in Python”

Does the book cover really matter?

Does the book cover really matter? The question simply haunts me. As a child I was attracted to good illustrations and most of the time, it was the cover of the book that would usually attract me first.
The point of attraction could have been simply a man with a gun or a kind of ghostly atmosphere. But it mattered. I must admit.
I changed one of the covers of my Laravel book.
I don’t know whether it would attract the programmers! 🙂

Eloquent Relations in Laravel 5

It is a sample from Chapter Twelve of the book : Laravel 5 : Learn Easy: Computer Programming For Everybody and
Laravel 5 : Learn Easy: Computer Programming For Everybody
Now we have learned to create tables through Migration and Tinker. We can also use Eloquent ORM to do the same. We also have learned to update or edit our database records. And I hope by this time you have already been able to build up a database consisting three tables : ‘users’, ‘songs’ and ‘singers’. Now in our ‘songs’ table we have two table­cells, you should have probably noticed. One is ‘user_id’ and the other is ‘singer_id’. So presumably, a user inserts a song. And he has an ID. In my database I have inserted three users: first, second and third. So the have user IDs like 1,2 and 3 respectively.

Continue reading “Eloquent Relations in Laravel 5”

Write Your Own Game in Python3

Good VS Bad Game
So far we have learned many things. I hope you have written the codes and tested them and it executed perfectly. Now the time has come to write a simple game in Python. It is a game called “Good Vs Bad”. The game is simple. But as a beginner you may find this code a bit longer. Write them down. Try to add more features.
If you are in Linux environment, save this file as ‘’ and change the file executable by running this command:
Sudo chmod +x
And then run it on your terminal like this:
If you are in Windows, run the IDLE and save the file as ‘’. Press F5 and play the game.

Continue reading “Write Your Own Game in Python3”

Python and Object Oriented Methodology

If you are a complete beginner, you probably for the first time hear about “Object Oriented Programming and Class.” Let us give a brief introduction to Object Oriented Programming (OOP).

10.1 – Object Oriented Methodology
It is based on real world programming. An object is a representation of a real world entity. If there is an object, there must be a class or blueprint behind it. In that class the behaviour of that object is designed or described in detail. These details consist of all the properties and actions that the object performs. There could be many types of objects coming from different classes and they might have relationships. It could be very complicated but you can always break those objects from one another and make some changes. The advantage of Object Orientation is that when you work on a part of a big, complicated project the other part remains unaffected. Our goal is simple. We want to join different objects to create big, complicated software. At the same time we want to make the relations of those objects as loose as possible.
A car object is built of many other objects like tyre, wheel, engine, accelerator etcetera. If you get a flat tyre does the engine stop? It is interrelated and depends on one another. But finally you can work on them individually without affecting other. That is Object Orientation.
Consider an object ‘GoodHuman’. This object must be different from another object ‘BadHuman’. Both come from ‘Human’ class. Now these two objects might have interrelationships and data interactions. Can you imagine how many kinds of properties and methods are there in ‘Human’ class? It could be very complex. Imagine a situation where a ‘BadHuman’ does something ugly. At the same time a ‘GoodHuman’ does some good thing. Whoever does whatever thing the life goes on and that is also Object Orientation.

The Foundation of Object Orientation
Object Orientation is a type of methodology used for building software applications. An Object Oriented program consists of classes, objects and methods. The Object Oriented methodology in software development revolves around a single concept called the object. You can develop software by breaking the application into component objects. These objects interact with each other when the whole application is put together. An object is a combination of messages and data. The object receives and sends messages and those messages contain data or information.
You (an object) interact with your Television (another object) via messages sent through a remote controller (another object).
Consider another real world example of a football. A football has a boundary. It has a specific defined property like bouncing. You can direct or apply few specific actions by kicking it or throwing it.
An object has a state. It may display behaviour. It has a unique ID.
The difference between an object and class is subtle but important. Whereas a class is an abstract concept, an object is a concrete entity. From a class objects with specific properties can be created or instantiated. That is why an object is often called an instance of a class.
One of the major feature of Object Oriented Programming is ‘Polymorphism’. Polymorphism is the capability of something to assume different forms. In Object Oriented Programming polymorphism is the property that a message can mean different things depending on the objects receiving it. The message ‘Accelerate’ means one thing if it sent to an object “OldCar”. But it means different thing to if it is sent to the object “NewCar”. It is a natural concept that can be applied to objects. It also means that similar objects often accept the same message but do different things.
Consider a web page. It is an object. There are billions of such objects around us. When you send a request to an object like web page you actually apply a verb “GET” to a noun “WebPage”. Now every “WebPage” object does not behave the same way when the “GET” verb is applied. Someone open up a PDF file, someone simply shows some texts and pictures and someone may harm your computer. When you double-click a file. It may execute if it is an executable file. Or it may opens up in a text editor if it is a text file. The message is same. That is “Double Click”. But the behaviour displayed by the file object depends on the object itself.
This is Polymorphism. You will learn it heart as you progress through this chapter.
The advantage of Python classes is that it provides all the standard features of Object Oriented Programming. It has the class inheritance mechanism. That allows multiple base classes, a derived class can override any methods of its base class or classes, and a method can call the method of a base class with the same name. Objects can contain arbitrary amounts and kinds of data.
Finally remember, in Python everything is an object. It means there is an abstraction or encapsulation behind it. Your first job is understand that avstraction and the final job is create your own abstraction.

Middleware, Layer Filter And Extra Security in Laravel 5

HTTP Middleware is one of the best facilities Laravel 5 ships with. It not only adds extra security to your application but also gives you enough freedom to create your own security mechanism alongside the default Laravel Authentication mechanism. As you know already, when a user requests for a page, the browser sends the request and the server responds. Sometimes, this request­response mechanism is simple and sometimes it is fairly complicated. But at the end of the day whenever a user requests for a page a HTTP request enters your application. Most of the time it is innocuous but as the proverb goes you can not and should not rely on user’s input or request so it needs to filtered. It has to be filtered when your application needs extra bit of authentication or security measures to be taken. Middleware does this thing out of the box.
Laravel 5 ships with ‘Authenticate’ middleware. It is default so that you need not tweak it to add some extra security to your application. The mechanism is very simple. It verifies the user’s credentials and permits it to enter your application and proceed further. But besides this default Middleware we can add our own functionalities. We will check it very soon. But before doing that let us check the default one and see how it works. Got to the ‘app/Http/Middleware’ folder and open up the ‘Authenticate.php’ page. This part of code looks interesting.

3.namespace App\Http\Middleware;
5.use Closure;
6.use Illuminate\Contracts\Auth\Guard;
8.class Authenticate
10. /**
11. * The Guard implementation.
12. *
13. * @var Guard
14. */
15. protected $auth;
17. /**
18. * Create a new filter instance.
19. *
20. * @param Guard $auth
21. * @return void
22. */
23. public function __construct(Guard $auth)
24. {
25. $this­->auth = $auth;
26. }
28. /**
29. * Handle an incoming request.
30. *
31. * @param \Illuminate\Http\Request $request
32. * @param \Closure $next
33. * @return mixed
34. */
35. public function handle($request, Closure $next)
36. {
37. if ($this-­>auth-­>guest()) {
38. if ($request­->ajax()) {
39. return response('Unauthorized.', 401);
40. } else {
41. return redirect()­->guest('auth/login');
42. }
43. }
45. return $next($request);
46. }

Here the line number sixth is very important. The class uses this line:
use Illuminate\Contracts\Auth\Guard;
Next, in the construct level it instantiates this ‘auth’ so that in the handle function it can check whther the user is a guest or an authenticated user. Fairly simple task. But there is something more. In that folder, there is another file ‘RedirectIfAuthenticated.php’. Let us see its code also:

namespace App\Http\Middleware;
use Closure;
use Illuminate\Contracts\Auth\Guard;
class RedirectIfAuthenticated
* The Guard implementation.
* @var Guard
protected $auth;
* Create a new filter instance.
* @param Guard $auth
* @return void
public function __construct(Guard $auth)
$this­>auth = $auth;
* Handle an incoming request.
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
public function handle($request, Closure $next)
if ($this­>auth­>check()) {
return redirect('/home');
return $next($request);

It does almost same thing. It is checking user’s authentication and permits it to go to the desired location. Here it is
1.if ($this­->auth-­>check()) {
2. return redirect('/home');
3. }

Now, question is, how it works out of the box? To find out our answer, we need to go to our ‘routes.php’ page. Here we have already seen how we can use the ‘log in, log out and register’ process using default authentication mechanism. Doing that we had to write a piece of code like this:

1.Route::group(['middleware' => 'auth'], function () {
2. Route::get('home', function () {
3. return view('auth.home');
4. });
6. Route::get('dashboard', function () {
7. return view('auth.dashboard');
8. });
9. });

You go through the first line and hopefully it now makes sense with the default Middleware logic. In our Route Group, we used
['middleware' => 'auth']
And it distantly connects with the in built Authentication Middleware. Actually it is defined in ‘app/Kernel.php’ as a protected property like this:

2. * The application's route middleware.
3. *
4. * @var array
5. */
6. protected $routeMiddleware = [
7. 'auth' =>
8. 'auth.basic' =>
9. 'guest' =>
10. ];

How the default Authenticate Middleware works is now clear­compiled. How about adding some our own functionalities? So far we have seen in our Authentication Chapter, a user logs in and she goes to the ‘/dashboard’. Well we need to add some extra functionalities in our ‘users’ table first. So that one of the users will be the administrator and only she can check into a ‘blog’ page.
Since we need to test our own Middleware at the ground lavel, we have decided to make it the simplest one. So we keep a link to that ‘Blog’ page in our ‘Dashboard’ page. Now every user logs in and clicks that link. But our Middleware will check whether that user is administrator or not. If she is an administrator, she can land up to the ‘Blog’ page with special Administrative power and if she is not that, she will sent back to the home page for general users. This is our simple administrator Middleware building procedural step. Let us start.
First, we need to set up one extra column in our ‘users’ table­cell. We need to migrate for that. You can do it manually in your PHPMyAdmin or directly use Tinker to add that column. But migration is simpler.
Open up the terminal and go to our laravel application and issue this command:
php artisan make:migration add_is_admin_to_user_table –table=users
Go to the ‘database’ folder and see that your new migration has been created. Now before migrating starts we need to tweak the up() and down() method like this:

3.use Illuminate\Database\Schema\Blueprint;
4.use Illuminate\Database\Migrations\Migration;
6.class AddIsAdminToUserTable extends Migration
8. /**
9. * Run the migrations.
10. *
11. * @return void
12. */
13. public function up()
14. {
15. Schema::table('users', function (Blueprint $table) {
16. $table­->boolean('is_admin')­->default(false);
17. });
18. }
20. /**
21. * Reverse the migrations.
22. *
23. * @return void
24. */
25. public function down()
26. {
27. Schema::table('users', function (Blueprint
$table) {
28. $table­->dropColumn('is_admin');
29. });
30. }

Now we are ready to migrate, so issue this command:
php artisan migrate
Check your ‘users’ table and see there is one extra column has already been added and each one is false. So you choose any one user and make her the administrator so that when we check the authentication it comes out true. Our database set up is ready. Now we can proceed for the next step. This step involves creating our own Middleware logic which will check whether the user is administrator or not. If she is the administrator, she can go the ‘Blog’ page. Otherwise she will sent back to the Home page for general users. We can create our custom Middleware through the console. In our terminal, we issue this command:
php artisan make:middleware RoleMiddleware
As you see, we name our Middleware ‘RoleMiddleware’. You can name it differently. No problem. It will immediately shots back with a prompt that says, your middleware has been successfully created. Let us go to the ‘app/Http/Middleware’ folder and check it. Yes, it has been created. It comes up with a handle() method as usual. Now all we need, is to add this line of code on top of the page first:
use Illuminate\Contracts\Auth\Guard;
Because we need to check the user’s authenticity.
The full code looks like this:

3.namespace App\Http\Middleware;
4.use Closure;
5.use Illuminate\Contracts\Auth\Guard;
6.use Illuminate\Http\RedirectResponse;
7.//use App\User;
9.class RoleMiddleware
11. protected $auth;

13. public function __construct(Guard $auth) {
14. $this­->auth = $auth;
15. }
18. /**
19. * Handle an incoming request.
20. *
21. * @param \Illuminate\Http\Request $request
22. * @param \Closure $next
23. * @return mixed
24. */
25. public function handle($request, Closure $next)
26. {
27. if ($this-­>auth-­>check())
28. {
29. if ($this­>auth­>user()-­>is_admin == TRUE)
30. {
31. return $next($request);
32. }
33. }

35. return new
36. }
38. }

Line 27 and line 29 are very important and you take the note that it ultimately plays the crucial part in our own Middleware.
The logic is fairly simple. Our ‘RoleMiddleware’ class whenever is called up an instance of ‘Guard’ is created and that will take care of further authentication process. So in our handle() method that passes two parameters ‘request’ and ‘Closure $next’, we will add some extra spices so that when it is checked the credentials of the user, it looks up and asks is she administrator? If not it sends her back to the log in page. So if someone just type the URL and try to enter into our ‘Blog’ page she will be sent back to the log in page. Now if she is a registered user she can log in but ends up at the ‘Dashboard’ page. To facilitate this ‘RoleMiddleware’ we need to add an extra Route Group in our ‘routes.php’ file like this:

1.Route::group(['middleware' => 'auth'], function () {
2. Route::get('home', function () {
3. return view('auth.home');
4. });
6. Route::get('dashboard', function () {
7. return view('auth.dashboard');
8. });
9. });
Route::group(['middleware' => 'role'], function ()

12. Route::get('blog', function () {
13. return view('blog.index');
14. });

16. });

You see at line number 10, we add an extra Route Group Middleware, ‘role’. But question is how our application will learn about it? Okay, our step is incomplete till now. We need to register it to ‘app/Kernel’ so the ‘app/Kernel.php’ code looks like this:

1.protected $routeMiddleware = [
2. 'auth' => \App\Http\Middleware\Authenticate::class,
3. 'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth:
4. 'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
5. 'iplog' => \App\Http\Middleware\RequestLogger::class,
6. 'role' => \App\Http\Middleware\RoleMiddleware::class,
7. ];

Watch out for the line number 6. We have registered our
'role' => \App\Http\Middleware\RoleMiddleware::class,
And it will now work like a breeze. The next steps are left to create one Controller and View page. That you can do. In the next chapter we will officially launch a administrator facility and will create a Administrative dashboard where an administrator can create, edit and delete users.
So far you have seen how we can control access to the users by using various types of Middleware. Use your imagination to build up all the crazy Middleware and the procedure is not very complex enough. You can handle it by yourself. Suppose, we want to check users point earned in a forum. We can do some more weird staff like checking whether a user’s name consists of any particular alphabet etcetera. We can use ‘before’ and ‘after’ Middleware so that our application will handle something beforehand and execute something after.
Suppose, we want to check the forum points of a user. We can create a Middleware like this:

1.namespace App\Http\Middleware;
3. use Closure;
5. class PointMiddleware
6. {
7. /**
8. * Run the request filter.
9. *
10. * @param
\Illuminate\Http\Request $request
11. * @param \Closure $next
12. * @return mixed
13. */
14. public function handle($request, Closure $next)
15. {
16. if ($request­->input('point') <= 500) {
17. return redirect('home');
18. }
20. return $next($request);
21. }

Now we can also handle this before and after like this:

1.namespace App\Http\Middleware;
3. use Closure;
5. class BeforeMiddleware
6. {
7. public function handle($request, Closure
8. {
9. // Perform action

11. return $next($request);
12. }
13. }
namespace App\Http\Middleware;
16. use Closure;
18. class AfterMiddleware
19. {
20. public function handle($request, Closure
21. {
22. $response = $next($request);

24. // Perform action
26. return $response;
27. }
28. }

So there are lot of actions waiting to explored inside this Middleware section. We will conclude with a logging Middleware that will log every request coming to your application. A very simple and elegant one. You have learned how to create a MiddleWare. So create a ‘IPLogger’ Middleware first. And add a one line of code in your handle() method like this:

19. return $next($request);
20. }

Next in your ‘routes.php’ add this Middleware
Group like this:

1.Route::get('/', ['middleware' => 'iplog', function ()
2. return view('index');
3. }]);

So that each time a user sends request to the index page, his ‘ip address’ will be stored in the ‘storage/logs/laravel.log’ like this:
1. [2015­08­22 18:16:14] local.INFO: ::ip­address
2. [2015­08­22 18:16:55] local.INFO: ::ip­address
//output is incomplete
I forgot to mention, you should have registered your ‘IPMiddleware’ in ‘app/Http/Kernel.php’ like this:
‘iplog’ => \App\Http\Middleware\IPLogger::class,
And it is done!
Please have a look into the documentation for more valuable inputs like Middleware parameters and Terminable Middleware where you start a session and stores it your storage and terminates it after your task has been accomplished.

Contracts Vs Facades in Laravel 5

The total Laravel 5 framework depends on many blocks of Interfaces, classes and other packaged versions that package developers have developed so far. Laravel 5 has happily used them and encourage you to do the same by following the SOLID principle and loose coupling. To master the Framework properly, you need to understand the core services that run Laravel 5. What are the main resources behind the scene? Basically, Contracts come in between regarding this scenario. Contracts are interfaces that provide this core services. Like ‘Illuminate\Contracts\Mail\Mailer’ defines the process of sending mails and doing that this interface simply pools in the implementation of mailer classes powered by the SwiftMailer. Now what are the ‘Facades’. Our chapter headline reads as ‘Contracts Vs Facades’. Do they have any similarity or relationship or anything else? Let me tell something about Facades first.
Facades are also interfaces. But it has a distinct difference with Contracts. First of all Facades are static interfaces that supply methods to the classes of service container. You have already seen a lot of Facades already. Remember ‘App’, ‘Route’, ‘DB’, ‘View’ etcetera. The main quality of Facades is, you can use it without type­hinting. Like in your ‘routes.php’ file you can write this code:

Route::bind('books', function ($id){
return App\Book::where('id', $id)-­>first();

and this ‘Route’ Facade directly resolves the contracts out of service container. Though Facades are static interfaces, they have more expressive syntaxes and provide more testability and flexibility than traditional static methodology. But the advantage of ‘Contracts’ is, you can define explicit dependencies for your classes and make your application more loosely coupled. Of course for most of the applications Facades work fine. But in some cases if you want to innovate something more, you need to use Contracts. How you could implement a contract? It is extremely simple and one example can illuminate the whole conception. Actually you have used it already! Suppose you have a ‘BookController’ through which you want to maintain a long list of your favorite books. To do that you need to store books in database. To do that you can bind your ‘Book’ Model in your ‘routes.php’ first, and then using resource you can do all kind of CRUD operations. In doing so, you need to log in.
Consider this code:

public function store(Request $request)
if (Auth::check()) {
// The user is logged in...

You can check whether the user is logged in or not. And depending on that you can only add your favorite books. For checking you use ‘Auth’ Facade. And it is fine. As long as you don’t want more decoupled state it works fine. But if you rather want to follow the SOLID principle and want a more decoupled state then instead of depending on concretion you love to adopt a more robust abstract approach. And in that case Contract comes to your rescue. Taylor Otwell himself keeps git­hub repositories on Contracts so you would better have a look around it. All of the Laravel Contracts live there:
Now let us go back to our previous topic. So we can either use our ‘Auth’ Facade. But try to understand one thing, when you use facade it assumes the framework and very tightly coupled with a concretion. But considering SOLID principle you want a decoupled state. What to do? Let us consider another scenario. We can inject our ‘Auth’ Facade through constructor like this and rewrite our whole code this way:

use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use Illuminate\Auth\Guard as Auth;
class BooksController extends Controller
* Display a listing of the resource.
* @return Response
protected $auth;
public function __construct(Auth $auth) {
$this­->auth = $auth;
public function store(Request $request)

Now you might opine that it is much better as we have injected ‘Auth’ instance through our constructor. Yes, it is better than before but still it lacks the SOLID design principle. It depends upon a concrete class like:

namespace Illuminate\Auth;
use RuntimeException;
use Illuminate\Support\Str;
use Illuminate\Contracts\Events\Dispatcher;
use Illuminate\Contracts\Auth\UserProvider;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Illuminate\Contracts\Auth\Guard as GuardContract;
use Illuminate\Contracts\Cookie\QueueingFactory as CookieJar;
use Illuminate\Contracts\Auth\Authenticatable as UserContract;
use Symfony\Component\HttpFoundation\Session\SessionInterface;
class Guard implements GuardContract {....}
//code is incomplete for brevity

As you see, when we use this line of code in our ‘BookController’: use Illuminate\Auth\Guard as Auth; We actually inject an instance based on concretion not abstraction. When we will unit test our code we will have to rewrite our codes. Moreover whenever you call any methods through this instance it is aware of your framework. But we need to make it completely unaware of our Framework and become loosely coupled. To do that we just have to change one line of code in our ‘BookController’.
Instead of that line of code:
use Illuminate\Auth\Guard as Auth;
We write this line of code:
use Illuminate\Contracts\Auth\Guard as Auth;
And that is it! Now our ‘Auth’ instance is completely loosely coupled. And now we can change that line of code in store() method:
if (Auth::check()) {
// The user is logged in...

to this line of code:
And it is done. Now your application has achieved more sophistication by following the SOLID design principle and becomes completely loosely coupled. Finally if check the interface Illuminate\Contracts\Auth\Guard what we see? Just have a look so that you can understand what happens behind the scene. The code of that interface is pretty big so for brevity we just cut the attempt() method out of it. The interface looks like this:

namespace Illuminate\Contracts\Auth;
interface Guard
* Attempt to authenticate a user using the
given credentials.
* @param array $credentials
* @param bool $remember
* @param bool $login
* @return bool
public function attempt(array $credentials = [], $remember = false, $login = true);
//this code is incomplete

Now your code is not coupled to any vendor or even to Laravel. You are not compelled to follow a strict methodology by a concrete class. You can simply implement your own, alternative methodology out of any contract.
I hope this comparison between ‘contract’ and ‘facade’ makes sense.

Play with Python

You can do some funny staff with Python. it simply amuses.
Issue this command in your Linux terminal:
sudo apt-get install python3-tk
It will install the necessary packages. Now it is time to write some code:


import turtle

pen = turtle.Pen()
colors =['red', 'orange', 'yellow', 'blue', 'pink', 'white', 'purple', 'green', 'light blue']
sides = 8

for x in range(360):
    pen.pencolor(colors[x % sides])
    pen.forward(x * sides / 3 + x)
    pen.left(360 / sides + 1)
    pen.width(x * sides / 100)

If you run this program, you will see something like this:

Python with turtle module

Python with turtle module