Skip to main content

URL shortener with python and flask - Chapter 3 - Let's play with flask

In this chapter, we will look at some of the important concepts of flask. I am assuming that you know what flask is all about and what you can do with flask. If not then visit Flask
I am also assuming that you have a solid understanding of python programming language. If not just google python tutorial and you will see a lot of tutorials. But Python docs is the best way to learn python.
In this chapter, we will be creating a lot of scripts or python files which we will run from the command prompt.
To create a script you can open your favourite text editor and then type the python code, save it with a file extension .py. Now open the command prompt in the folder you have saved python and then type python your_file_name.py
Then command prompt will run the script and gives the expected output.

In this chapter, as there is a lot of content to cover, I am using IPython notebook. Assume that each and every input is a script file. Create one and fire up the command prompt or terminal, you will get a message stating that the server is running at http://localhost:5000.
If in any case you are not able to use your command prompt, then open the script in IDLE editor and then run the code by hitting F5 or Run > Run Module.
More information from here: Python central
A video:
You may also find the following video helpful if you are facing any problem.

A hello world application

We will start with a simple and easy hello world application, which will show Hello world in the web browser.
In [ ]:
# app.py
from flask import Flask

app = Flask(__name__)

@app.route('/hello')
def hello_world():
    return "Hello world"

if __name__ == "__main__":
    app.run()
Save the above file as app.py somewhere on your local computer. Open the command prompt in that location and type python app.py, you will get "* Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)". Open http://127.0.0.1:500/hello or http://localhost:5000/hello and you should see something like this Basic Hello world application with flask
Now that we are sure that it is running, we will try to make sense of the code that we have written.
  • We have imported Flask class from flask module.
  • We have created an instance (app) of the class so that we can use it in our code.
  • For URL's we are using the route decorator, so that when you type 127.0.0.1/hello in the web browser then the function hello_world is called which will obviously return Hello world.
  • This if statement is checking if the source file name is same as the one which we are executing and the app is started. Further Reading: What does if __name__ == “__main__”: do?

Adding HTML in return statement

We can even add HTML tags in our return statement and the browser will render the tags. Lets make a simple web page.
In [ ]:
# app.py
from flask import Flask

app = Flask(__name__)

@app.route('/hello')
def hello_world():
    html = """
        <h1>Anivarth Peesapati</h1>
        <p>Hello there,<br />
            I am Anivarth Peesapati. I love {}
        </p>
    """.format("Python")
    return html

if __name__ == "__main__":
    app.run()
After the app is running, you should see something like this: Embed HTML in flask application Just with the help of the above example we can explain many things.
  • We can return variable values also.
  • HTML can also be added to the return strings.
  • To embed some variables in the strings we can use [format](https://docs.python.org/2/library/stdtypes.html#str.format) function.

Dynamic URL's

If you have ever noticed, facebook has URL's like http://facebook.com/anivarth. Depending on your name the URL will change. And depending on the URL the output of the web page will change. In flask we can create similar variable URL's also called as Variable rules. We will see an example to understand it better.
In [ ]:
# app.py
from flask import Flask

app = Flask(__name__)

@app.route('/<name>')
def hello_world(name):
    return "<h1>{}</h1>".format(name)

if __name__ == "__main__":
    app.run()
As you can see, the way we define the URL also has changed. It is compulsory that we will give this variable as input to the function(hello_world(name)) that we are defining. Otherwise, you will see an error. Restart the app(Restarting the terminal always is boring there is a solution for it and we will see it later) and go to http://127.0.0.1/Anivarth and you should see something like this: Flask Variable rules If you change my name to your name, you should see your name in the browser. But the h1 tags are not replaced in any case. Facebook works in a similar way. They have created all the basic HTML and only the content(Your name, friends etc.) varies according to the URL.
Sometimes, it is necessary to restrict the user to enter only numbers in the variable URL. Then you can add int: in front of the variable name. Lets see an example.
In [ ]:
# app.py
from flask import Flask

app = Flask(__name__)

@app.route('/<int:ph_no>')
def phone_number(ph_no):
    return "Your phone number is {}".format(ph_no)

if __name__ == "__main__":
    app.run()
Restart the app and when you visit http://localhost:5000/12345, you will see something like this:

Variable Rules in flask - integer constraint
Variable URL's in flask
In a similar way you can constrain the variable. You can use the following depending on your requirement.
Constraint Remarks
string accepts any text without a slash (the default)
int accepts integers
float like int but for floating point values
path like the default but also accepts slashes
any matches one of the items provided
uuid accepts UUID strings

Debug Mode

If you have observed, till now we have been restarting the server everytime there was a change in the script. But this is not really necessary. Flask can sense the changes in the script and will automatically reload the script for you. You can do that using app.run(debug=True) at the end. You can see the usage in the next example.

HTTP methods

When you open a web page using a URL, python will serve the webpage using a method called as GET. But this is not always the same case. Most of the times when you submit a form, the browser will POST the data and based on the data, the server will respond with the GET method. If you have observed your command prompt or terminal, after you have opened a page, you should see some GET methods.
You can read more about HTTP requests from here: HTTP/1.1: Method Definitions, HTTP, HTTP requests Methods
HTTP GET method in Flask
HTTP GET Method in Flask
We can also use POST method in flask. Lets implement a simple form to create a POST request on flask.
In [ ]:
# app.py
from flask import Flask, request

app = Flask(__name__)


@app.route('/form', methods = ['GET', 'POST'])
def form():
    if request.method == 'POST':
        return request.form['flask']
    else:
        return "<form method='POST'><input type='text' name='flask'/>\
        <input type='submit' value='submit' /></form>"

if __name__ == "__main__":
    app.run(debug=True)
If you run the file above, then you should see a page something like this:

Form implementation with flask
Form implementation with flask
Submit the form in flask and data entered in form
Extracting the data entered in the form using Flask

Before we proceed further we will understand the above program. In the decorator we have added methods = ['GET', 'POST']. This means that we are telling python to accept both GET, POST methods from the browser. In the function, we are checking if the methods are POST and if it is POST method, then we will return the value(request.form['flask'], where flask is the name of the input tag.) that has been entered in the form.
Else, we will just show the user a form in which he/she can enter the value. In the else statement we have added the HTML code which I am assuming that you are already familiar with it.
In the run command we have also added debug = True which means that, from the next time you make changes to the script they are automatically loaded.

Templates

Till now we only had few HTML tags in our website pages. But what if you have a very big HTML file? Of course you can add that to the return command, but don't you think that it will make the code look messy? Yes, it will. For this reason we can use templates in Flask. We will see the code first and then make sense of it.
In [2]:
# app.py
from flask import Flask, render_template

app = Flask(__name__)

@app.route('/test-template')
def testing_template():
    return render_template('test.html')

if __name__ == "__main__":
    app.run(debug = True)
Before we save the above file, we will have to create 'test.html' file. To do that create a new folder with name templates in the folder where the app.py file resides. to make it simple, your folder structure will look as follows:

├── app.py
└── templates
    ├── test.html
We will start with something very simple. Save the test.html file with the following code in it.

<!doctype html>
<html lang='en'>
<head>
  <title>Radius of Circle</title>
</head>
<body>
  <h1>Radius of Circle</h1>
</body></html>
After you have saved the HTML file, go ahead and save changes to the app.py. If you editing the code in the old app.py file, then flask will automatically reload the changes for you. Otherwise you should start the server.
If there are no errors then go ahead an open http://127.0.0.1:5000/test-template and you should see something similar to this:

using templates in flask
Templates in flask

The only changes that we made are, we have added render_template function with the HTML file name and it took care of everything else for us.

Using Variables in templates

I don't think that the templates are really useful if they just serve the same file everytime. There should be a change to the file either based on the url or based on input or based on time and so on. To do this we can use python variables in templates. We will see an example.
The app.py file is as follows:
In [ ]:
# app.py
from flask import Flask, render_template

app = Flask(__name__)

@app.route('/test')
def test():
    return render_template('test.html', name = "<h1>Anivarth Peesapati</h1>")

if __name__ == "__main__":
    app.run(debug = True)
Now the HTML file will be as follows:
<!doctype html>
<html lang='en'>
<head>
    <title>Radius of Circle</title>
</head>
<body>
    {{ name }}
</body></html>
Remember to save the file in the templates folder. I am saving the file as test.html. But if you save the file with a different name, then make sure that you will also update the file name in the python script.
If you run the file you will see something like this:

Using variables in flask templates(Jinja Templates)
Using variables in flask templates(Jinja2 Templates)

In HTML files, we will refer to the variables using {{ variable_name }} syntax. When we are rendering the template, we will refer to variable_name to assign a value. In our example as you can see, we are using the name variable which we have used in the HTML file and using the same variable we have assigned a value in the python script.
But there is a problem! If you have observed, the value that we have given to the name variable is <h1>Anivarth Peesapati</h1>, and we are expecting python to render the template with a heading. But this didn't happen, becase jinja by default will assume that the value that we are giving as input are not safe and will escape the characters.
For example if you will give < as input it will convert it to &lt;. You can read more about escaping from here: Using character escaping in HTML and the HTML escape characters
Now to overcome this problem, we will have to append |safe to the variable name - Like {{ variable_name|safe }}. This will not do the character escaping for you. You can read more about the Character escaping in Jinja from here: Controlling Escaping
Let's modify the HTML file and the python script will remain the same.
<!doctype html>
<html lang='en'>
<head>
  <title>Radius of Circle</title>
</head>
<body>
  {{ name|safe }}
</body>
</html>
After the changes the output in the browser will be as follows:

Using the |safe for controlling escaping
Using |safe to control escaping

As we have got familiar with the python variabls, we will do something a little bit complex. We will print the calendar for a year based on the URL of the user.
In [ ]:
# app.py
from flask import Flask, render_template

from calendar import HTMLCalendar

app = Flask(__name__)

@app.route('/<int:year>')
def calendar(year):
    html_calendar = HTMLCalendar()
    year_calendar = html_calendar.formatyear(year)
    return render_template('test.html', calendar = year_calendar, year = year)


if __name__ == "__main__":
    app.run(debug = True)
We are using Variable URL and python [Calendar](https://docs.python.org/2/library/calendar.html#calendar.HTMLCalendar) module to generate HTML calendar for us. Now the HTML file will be as follows:
<!doctype html>
<html lang='en'>
<head>
  <title>Radius of Circle</title>
</head>
<body>
  <center><h1>Calendar for the Year {{ year }}</h1></center>
  <center>{{ calendar|safe }}</center>
</body>
</html>
If your server is running go to http://localhost:5000/2017 and then you will see something like this:

2017 calendar using Flask and Python
2017 calendar using Flask and Python
. If you change the number in the URL you will see the calendar for that year. It should be noted that the maximum number that you can enter is 9999.
More about Jinja Templating from here: Jinja2

Building URL's

Till now we have created many webpages. But what if, we had to link from one page to another? To solve this problem we will use the url_for function. We will see a small example for that:
In [ ]:
# app.py
from flask import Flask, render_template, url_for

from calendar import HTMLCalendar

app = Flask(__name__)

@app.route('/index')
def index():
    return "This is an index page"

@app.route('/flask/<int:number>')
def flask(number):
    return "This is flask page - {}".format(number)

@app.route('/links')
def urls():
    return "<a href='{}'>Index</a><br /><a href='{}'>Flask</a>".format(url_for('index'), url_for('flask', number = 10))


if __name__ == "__main__":
    app.run(debug = True)
If you run the script and open http://127.0.0.1/links then you will see something like this:
url_for function in flask
url_for function in Flask

As you can see we have used url_for function and flask will build the links for you. url_for will take the name of the function which you are referencing. If the URL has variable rules, then you will add the value after the name of the function. This function is also available in the jinja templates also. url_for function can also do more things. If you want to know more, then you can see: url_for API.
format function that we have used can be seen here: str.format

static files

In the calendar example we have seen, eventhough we were able to show the calendar it was not looking great. I mean it was missing styling information. There are many options for us to add the style information.
  • External Style sheet
  • Internal Syle Sheet
  • Inline Style
Of the three options above the External Style sheet is the recommended option. We can use the url_for function to use the static files. But before we do that first create a folder with name static in the folder where app.py file resides.
Now in the static folder create a file and name it style.css. At the end of this operation your folder structure will look as follows:
├── app.py
├── static
│   ├── style.css
└── templates
    ├── test.html

Now the code in the style.css will be as follows:
table, td, tr, th{
font-family: 'Lora', serif;
border: 1px solid red;
padding: 5px;
}

Don't forget to save the file in the static folder.
Now test.html file will contain the following code:
<!doctype html>
<html lang='en'>
<head>
  <title>Radius of Circle</title>
  <link href="https://fonts.googleapis.com/css?family=Lora"" rel="stylesheet">
  <link type="text/css" rel="stylesheet" href="{{ url_for('static', filename = 'style.css') }}" />
</head>
<body>
  <center><h1>Calendar for the Year {{ year }}</h1></center>
  <center>{{ calendar|safe }}</center>
</body>
</html>

Note that you should save the file in the templates folder. There are two things to note from this HTML page:
  • url_for function has been used for getting the static files
  • I have also added a link to google fonts to get the font family.
app.py file will not have any changes.
Now open the browser and type the year for which you want the calendar. I want to see the calendar for 2017 and so I will type: http://localhost:5000/2017 . You should see something similar to this:
2017 calendar using python and flask
2017 Calendar using Flask and Python with external stylesheet
Remember that you should store all the static files in the static directory only. Of course you can make subfolders in the static directory.

for loop in templates

We can use for loop in jinja templates. Lets see an example:
app.py will have the following code:
In [ ]:
# app.py
from flask import Flask, render_template

app = Flask(__name__)

@app.route('/')
def looping():
    return render_template('test.html', loop = xrange(10))


if __name__ == "__main__":
    app.run(debug = True)
test.html file will have the following code(I am not following any Web standards, you can add them if you want).
{% for i in loop %}
We are looping {{ i }}<br />
{% endfor %}
Now run the server and you should see something similar to this:
For loop in flask(jinja) templates
For loop in templates

I am assuming that you are able to understand the code directly because it is mostly similar to python code and direct. It should be noted that, there is no need for indentation in the HTML code.

if-else-elif in templates

We have for loop to loop through the templates, but we also need some if conditions to make decisions. Yes, Jinja(templates) also have if statements. We will print the multiples of 3, 5 below 10 on the webpage.
test.html is as follows:
{% for i in loop %}
  {% if i%3 == 0 %}
    {{ i }} is a multiple of 3<br />
  {% elif i%5 == 0%}
    {{ i }} is a multiple of 5<br />
  {% else %}
    {{ i }} is neither a multiple of 3 not 5 <br />
  {% endif %}
{% endfor %}

There is no change in the app.py file. Run the server and you should see something similar to the following:
Multiples of 3 or 5 using jinja templates syntax
Multiples of 3 or 5 using Jinja templates syntax

You can do more things with Jinja Templates. For more details visit: Synopsis, List of Control Structures

Request data

Few sections ago, in the HTTP methods section, we have seen a little bit about the POST method. But in this section we will see more of this in detail.
For example we will continue with the calendar app that we were creating.
Now the app.py file is as follows:
In [ ]:
# app.py
from flask import Flask, render_template, url_for, request

from calendar import HTMLCalendar

app = Flask(__name__)

@app.route('/', methods = ['GET', 'POST'])
def calendar():
    if request.method == "POST":
        year = int(request.form['year'])
        year_html = HTMLCalendar().formatyear(year)
        return render_template('test.html', calendar = year_html, year = year)
    else:
        return """
        <form method = "POST">
            <input type="test" name = "year" /><br />
            <input type = "submit" value = "Submit" />
        </form>"""

if __name__ == "__main__":
    app.run(debug = True)
In the code, we are telling python that the present webpage can have both POST, GET methods(methods = ['GET', 'POST']). The if statement checks if the method is POST. If the method is POST, then the html of the calendar is returned. Else the form is returned. So that if the user submits the form the value is sent as POST and the calendar for the year is shown.
test.html file is as follows(I am assuming that you already have style.css):
<!doctype html>
<html lang='en'>
<head>
  <title>Radius of Circle</title>
  <link href="https://fonts.googleapis.com/css?family=Lora&quot;" rel="stylesheet">
  <link type="text/css" rel="stylesheet" href="{{ url_for('static', filename = 'style.css') }}" />
</head>
<body>
  <center><h1>Calendar for the Year {{ year }}</h1></center>
  <center>{{ calendar|safe }}</center>
</body>
</html>

If you run the server, then you will see something similar to these:
form to ask the user to submit the year
Form to submit the year
calendar after the user submits the form
Calendar after the user submits the form

You can see more about the form data from here: Accessing Request Data, File Uploads

Cookies


Cookies are small files which are stored on a user's computer. They are designed to hold a modest amount of data specific to a particular client and website, and can be accessed either by the web server or the client computer.
We can also create and store cookies in a client browser. Let's see an example. app.py as follows:
In [ ]:
# app.py
from flask import Flask, render_template, make_response

app = Flask(__name__)

@app.route('/cookie')
def cookie():
    response = make_response(render_template("test.html"))
    response.set_cookie('website', 'Radius of Circle')
    response.set_cookie('author', 'Anivarth Peesapati')
    return response

if __name__ == "__main__":
    app.run(debug = True)
Here in the cookie function we are storing two cookies. You can store any number of cookies.
You can create a new HTML file or change the test.html file with the following code:
<!doctype html>
<html lang='en'>
<head>
  <title>Radius of Circle</title>
  <link href="https://fonts.googleapis.com/css?family=Lora&quot;" rel="stylesheet">
  <link type="text/css" rel="stylesheet" href="{{ url_for('static', filename = 'style.css') }}" />
</head>
<body>
    <p>This page has a cookie</p>
</body>
</html>
Run the server and you will just see a "The page has a cookie". Now to check if the cookie has been set, we can do as follows:
How to check cookies in chrome browser
How to check cookies on chrome browser
How to check cookies in mozilla browser
How to check cookies in mozilla browser

If you can help me with the browser in your OS, then you are welcome.
To access the cookie, we can use the request.cookies attribute.
app.py is as follows:
In [ ]:
from flask import Flask, render_template, make_response, request

app = Flask(__name__)

@app.route('/cookie')
def cookie():
    response = make_response(render_template("test.html"))
    response.set_cookie('website', 'Radius of Circle')
    response.set_cookie('author', 'Anivarth Peesapati')
    return response

@app.route('/')
def index():
    website = request.cookies.get('website')
    return render_template('test.html', website = website)

if __name__ == "__main__":
    app.run(debug = True)
In the above file, we have also added an index function which we will take read the cookies and the data is sent to the HTML file as a variable. Rest of the code is same.
The update test.html is as follows:
<!doctype html>
<html lang='en'>
<head>
  <title>Radius of Circle</title>
  <link href="https://fonts.googleapis.com/css?family=Lora&quot;" rel="stylesheet">
  <link type="text/css" rel="stylesheet" href="{{ url_for('static', filename = 'style.css') }}" />
</head>
<body>
    {% if website %}
    Website is {{ website }}
    {% else %}
    <p>This page has a cookie</p>
    {% endif %}
</body>
</html>
Now run the file and visit http://localhost:5000 . You will see a text stating "Website is Radius of Circle". If you don't believe me, open a Private browsing window or Incognito tag and visit the same URL, you will see something else.

Redirect

I think that everyone is aware of what redirect is and we will directly see an example for that. app.py file is as follows:
In [ ]:
# app.py
from flask import Flask, redirect, url_for

app = Flask(__name__)

@app.route('/')
def index():
    return "This is an index page"

@app.route('/redirect')
def redirect_this_page():
    return redirect(url_for('index'))

if __name__ == "__main__":
    app.run(debug = True)
redirect takes the url of the page to which it has to redirect. To make our work simple I have used url_for function. Rest of the thing is simple.
Now run the file and visit http://localhost:5000/redirect and it will automatically redirect you to index page.

handling errors

Sometimes when we browse a website, we will see a 404 Not found error. This is because there is no page for such URL. For example on google you will see a page like this:
404 Error Page - Google
In flask when you open an Unknown URL then you will see something like this:
404 Not found error in flask
Not Found Error in flask
But you can add some style sheets or add custom template to this kind of pages. For this we will use something called as error handlers. Lets see an example.
In [ ]:
# app.py
from flask import Flask

app = Flask(__name__)

@app.route('/')
def index():
    return "This is an index page"

@app.errorhandler(404)
def error_404(error):
    return "<h1>Hello users, sorry there is no page with this url!</h1>"

if __name__ == "__main__":
    app.run(debug = True)
When you visit some url other than the index page you will see something similar to this:
Custom 404 not found page with flask
Custom 404 not found page with flask

Remember that the function will take some variable_name as input and it can be further used as variable in the function. You can also create custom pages for 500, 400 etc. If you want to know the status codes, then you can see from here: List of HTTP Status Code

abort

Sometimes, you deliberately will be in need of aborting a function with error pages. Then you can use this function. For example, if the user has entered a wrong data in the text input and you want to terminate the program execution, then you can show the user 500 error instead of the error that happened in your program.
Our app.py file is as follows:
In [ ]:
# app.py
from flask import Flask, abort

app = Flask(__name__)

@app.route('/')
def index():
    return "This is an index page"

@app.errorhandler(404)
def error_404(e):
    return "<h1>Hello users, sorry there is no page with this url!</h1>"

@app.route('/error')
def create_error():
    # this page will show 404 error
    abort(404)

if __name__ == "__main__":
    app.run(debug = True)
Run the server and visit the error page and you will see the custom 404 error page.

sessions

Even though you can use cookies for storing the user login data, they are not really secure. For this reason flask has sessions. These are far better and very much secure when compared to simple cookies. You can create cookies in the following way:
In [ ]:
# app.py
from flask import Flask, session, url_for

app = Flask(__name__)

app.secret_key = "some secret key you want"

@app.route('/')
def index():
    if 'name' in session:
        return "Welcome back {}. To logout <a href\
        ='{}'>Click Here</a>".format(session['name'], url_for('logout'))
    return "Welcome guest.\
     To login <a href='{}'>Click here</a>".format(url_for('login'))

@app.route('/login')
def login():
    session['name'] = "Anivarth"
    return "You are now logged in. To logout \
    <a href='{}'>Click here</a>".format(url_for('logout'))

@app.route('/logout')
def logout():
    session.pop('name')
    return "Logged out!"

if __name__ == "__main__":
    app.run(debug = True)
We have to create a secret key for the session to work. Value of secret key can be anything. It is recommended that the value is something random.
Now in the code, when the user visits the index page - if a session exists, then the user is welcomed with their name, else, they are asked to login by visiting the login page.
In the login page we will create a session object which will save name of the user.
In the logout page we will remove the name of the user from the session and will notify the user with Logged out! message.
Of course, login and logout will not be as primitive as this one. This is the core concept. You can add forms and many other things to make it more secure.
Now run the server and you will see something like this:
Sessions in flask
Sessions in flask
You can read more about sessions from here: Flask Sessions

flashes

If you have ever entered a wrong username and password on a webpage, then you should have got a message stating, you have entered a wrong username or password. In a similar way when you have added a product to the cart there will be a message stating that the product has been added to the cart. These are some of the endless examples.
In a similar way you can flash the messages to the user without changing the data in the return function. You can do that as follows: app.py
In [ ]:
# app.py
from flask import Flask, flash, render_template

app = Flask(__name__)

app.secret_key = "dasdf"

@app.route('/')
def flash_message():
    flash('This is a flash message')
    return render_template('test.html')

if __name__ == "__main__":
    app.run(debug = True)
The only thing that is unfamiliar to you is the flash function, which will flash the message in the user's browser. If you use bootstrap, then usually you will show flashes using Alerts
Now the test.html file will be as follows:
<!doctype html>
<html lang='en'>
<head>
  <title>Radius of Circle</title>
  <link href="https://fonts.googleapis.com/css?family=Lora&quot;" rel="stylesheet">
  <link type="text/css" rel="stylesheet" href="{{ url_for('static', filename = 'style.css') }}" />
</head>
<body>
  {% with flashes = get_flashed_messages() %}
    {% if flashes %}
      <ul>
        {% for message in flashes %}
          <li>{{ message }}</li>
        {% endfor %}
      </ul>
    {% endif %}
  {% endwith %}
  <p>This page features flashes.</p>
</body>
</html>
Run the server and you will see the message flashed.
This tutorial is not yet complete. If you are comfortable with using flask from now, then you should first read Quickstart before you proceed further.
As always if you have any doubt or didn't understand anything then comment in the comment box and I will be happy to help you.
If you have any suggestions or feedback or if you have found any typo in this post, Please do comment in the comment box and I will be very happy to see your message.
You can also contact me.
Thank you. Have a nice day😃.

Popular posts from this blog

Making a quiz web app with python and flask

Edit : When you are creating a web app with h tml templates, then y ou will have to sa ve the html file in templates folder in the Current Wor ki ng Directory( CWD). If you save the file in the C W D directl y you will get a TemplateNotFound error. Thank you Udhay for pointing it out.   In this post we will create a quiz website using python . I will be using the flask framework . After reading this tutorial you will learn form submission , flask templates , python code in flask templates , shuffling the questions and options with the random module and few others.  Please note that this tutorial is not big as it seems to be. Some of the code has been rewritten to maintain consistency and also font size is somewhat big so that your eyes won't get stressed reading this tutorial. Also the content has not occupied the full width of the page. In this tutorial I am assuming that you are having a very basic understanding of the flask framework . Please refer the documentation

Problem 11 Project Euler Solution with python

Largest product in a grid In the 20×20 grid below, four numbers along a diagonal line have been marked in red. 08 02 22 97 38 15 00 40 00 75 04 05 07 78 52 12 50 77 91 08 49 49 99 40 17 81 18 57 60 87 17 40 98 43 69 48 04 56 62 00 81 49 31 73 55 79 14 29 93 71 40 67 53 88 30 03 49 13 36 65 52 70 95 23 04 60 11 42 69 24 68 56 01 32 56 71 37 02 36 91 22 31 16 71 51 67 63 89 41 92 36 54 22 40 40 28 66 33 13 80 24 47 32 60 99 03 45 02 44 75 33 53 78 36 84 20 35 17 12 50 32 98 81 28 64 23 67 10 26 38 40 67 59 54 70 66 18 38 64 70 67 26 20 68 02 62 12 20 95 63 94 39 63 08 40 91 66 49 94 21 24 55 58 05 66 73 99 26 97 17 78 78 96 83 14 88 34 89 63 72 21 36 23 09 75 00 76 44 20 45 35 14 00 61 33 97 34 31 33 95 78 17 53 28 22 75 31 67 15 94 03 80 04 62 16 14 09 53 56 92 16 39 05 42 96 35 31 47 55 58 88 24 00 17 54 24 36 29 85 57 86 56 00 48 35 71 89 07 05 44 44 37 44 60 21 58 51 54 17 58 19 80 81 68 05 94 47 69 28 73 92 13 86 52 17 77 04 89 55 40 04 52 08 83 97 35 99 16 07

Problem 60 Project Euler Solution with python

Prime pair sets The primes 3, 7, 109, and 673, are quite remarkable. By taking any two primes and concatenating them in any order the result will always be prime. For example, taking 7 and 109, both 7109 and 1097 are prime. The sum of these four primes, 792, represents the lowest sum for a set of four primes with this property. Find the lowest sum for a set of five primes for which any two primes concatenate to produce another prime. This problem is j u st a brute force problem. If you have come here because you don't know the limit upto which you will h ave to gener ate the prime numbers t hen go ahe ad and t r y with 10,000 . When I first start ed solving the problem I chose 1 million(beca use most of the problem s on project E uler have this limit ), but it took very long for the computer to fin d the solution. After searching on the internet then I found many people choosing 10, 000 so I have changed my in put f rom 1 million to 10000 and the output was f ast. He