Flask

This Workshop

We’ll build a URL shortener service (like bit.ly)

[1] Hello World

Create a web server that return "Hello Flask!" when you issue a GET request.

$ curl localhost:5000
Hello Flask!
$

Tips

  • pip install Flask

[2] Template

Have the web server return a page for submitting URL.

form.png

Tips

  • Enable debugging mode in the server so you won’t need to restart it
  • By default, flaks looks for templates in the templates directory
  • You can grab the template HTML from here
    • If you don’t want to write it yourself

[3] Static Files

Serve static files from static directory.

Tips

  • To test you can place style.css there and make the header blue.
  • You might want to use url_for in the template

[4] JavaScript

Have a click on the [+] button submit the form.

Tips

[5] Database

We’ll use SQLAlchemy and flask-sqlalchemy extension.

Schema:

Add a line to the output HTML showing how many links we’ve shortened so far.

Tips

  • pip install flask-sqlalchemy
  • count example

[6] Handling Form Data

Handle the form data and store and short URL in the database.

For short URLs, we store a global counter and base62 to encode it as the short URL.

Tips

[7] Redirecting Short Links

Redirect to original URL from short links. Increment the counter in the database for each hit.

Tips

[8] Dynamically Loading Data

Add a list of the 10 most populate links at the bottom of the page. Populate the list by AJAX call the get JSON object back.

top10.png

Tips

References

This presentation was made with asciidoc using the slidy backend and Pygments syntax highlighter.

Thank You

question.svg