Lab 2: Build your own server

Let’s build your first server!

Some prerequisites:

  1. Be sure to run pip3 install flask in the terminal to ensure that flask is installed

Let’s build a webserver:

You are tasked to build a webserver (called webserver.py) that has three endpoints:

If someone goes to http://localhost:5000/, the server returns the string

<h1>Hello!</h1><p>Congrats on building your own server!</p><br /></br /><a href="/page2">Go to the next page</a>

If someone goes to http://localhost:5000/page2the server should return the string:

<h1>This is page 2!</h1><p>let us move to page three</p><br /></br /><a href="/page3">Go to the next page</a>

If someone goes to http://localhost:5000/page3 the server should return the string:

<h1>This is page 3!</h1><p>And of end of our journey!</p>

Please be sure to return the responses listed exactly as shown. If not then the unit tests will not function correctly.

How to test:

Please run the following commands in your terminal to install the requests package to your Python installation.

pip3 install requests pip3 install pytest

Requests is a python library that makes making HTTP requests (e.g. when you type “http://www.facebook.com”, you are making an http request) from within Python easier. We will be using this library a lot in this class, so this unit test is an introduction to the package.a

Pytest is a functional testing framework that’s popularly used in industry. It also eliminates the need to write classes in order to write tests.

Please save the below file as test_webserver.py and run the following unit test using the command pytest test_webserver.py

import requests 
def test_home(): 
    page = requests.get('http://localhost:5000') 
    true_content = '<h1>Hello!</h1><p>Congrats on building your own server!' +\
        '</p><br /></br /><a href="/page2">Go to the next page</a>' 
    assert str(page.text) == true_content 

def test_page2(): 
    page = requests.get('http://localhost:5000/page2') 
    true_content = '<h1>This is page 2!</h1><p>let us move to page three</p>' +\
        '<br /></br /><a href="/page3">Go to the next page</a>' 
    assert str(page.text) == true_content 

def test_page3(): 
    page = requests.get('http://localhost:5000/page3') true_content = '<h1>This is page 3!</h1><p>And of end of our journey!</p>' assert str(page.text) == true_content

When it all passes your are done! The unit test is sending HTTP requests to your server and determining if it is returning the right content.