Flask Delicious Tutorial : Building a Library Management System Part 3 - Routes
Previous: Part 2: Start With A Loaded Skeleton
I have configured what we need in this repo: DeliciousFlask-3.1. Download it, and run app.py (If you are new to python see Part2).
In this part we explore some concepts related to routes.
If you run the above, app and go to http://127.0.0.1:5000/
you should see
abcd
why? because we said so in app.py:
@app.route('/')
def index():
return 'abcd'
Let's try http://127.0.0.1:5000/test
we get test ok
As we configured it:
@app.route('/test')
def route_test():
return 'test ok'
Adding Parameters
if you do http://127.0.0.1:5000/greet/bob
you will get:
hi bob
whatever you put after greet, it will always return hi
+ what you put
That's because Flask allows you to specify parameters. Here's how you do it:
Operations using parameters
Let's say you want to do:
/add/2/3
and you want to get 5
in app.py you will see a function:
@app.route('/add/<a>/<b>')
def add(a, b):
return '{}'.format(a+b)
But, if you run it, you'll get ... 23
That's because a and b are strings
If you want to get 5, you must convert before adding.
@app.route('/real-add/<a>/<b>')
def real_add(a, b):
return '{}'.format(int(a) + int(b))
Specifying types in parameters
If you want to get a and b as integers directly, you can do so by specifying the type at the begining:
@app.route('/converted-add/<int:a>/<int:b>')
def converted_add(a, b):
return '{}'.format(a+b) # no need to convert
If you try converted-add/5/abc
you will get errors.
# AssertionError: View function mapping is overwriting an existing endpoint function: <name here>
?
Why do i get That's because if you do for example:
@app.route('/')
def index():
return 'abcd'
@app.route('/test')
def index():
return 'test ok'
The first and second functions have the same name. You must change the second function's name to something else.
TODO
Add a snippet so that when we do
/multiply/5/3
we get 15
Stay tuned for the next part!
My mail if you don't understand something: arj.python at gmail dot com