G S
G S

Reputation: 36838

Flask equivalent of Sinatra's "passing"

In my Flask application, I want to expose a URI like this:

http://<base_uri>/some_string

and I wish to handle requests to it differently depending on whether some_string is an integer or not.

With Sinatra I can achieve that via "passing" as shown below:

get '/:some_string' do
  if is_integer(:some_string)
    'Your URI contains an integer'
  else 
    pass # This will pass the request on the the method below which can handle it
end

get '/*' do
  'Your URI contains some string'
end

Here the call pass in the first route lets the second route process the request if :some_string is not an integer.

I couldn't find any equivalent functionality in Flask. Can someone please suggest a solution in Flask?

Upvotes: 4

Views: 636

Answers (1)

DazWorrall
DazWorrall

Reputation: 14210

Type conversion in url routes can do this for you:

from flask import Flask
import unittest

app = Flask(__name__)
app.debug = True

@app.route('/<int:thing>')
def num(thing):
    return 'INT'

@app.route('/<thing>')
def string(thing):
    return 'STR'


class TestDispatch(unittest.TestCase):

    def setUp(self):
        self.client = app.test_client()

    def test_int(self):
        resp = self.client.get('/10')
        self.assertEqual("INT", resp.data)

    def test_str(self):
        resp = self.client.get('/hello')
        self.assertEqual("STR", resp.data)


if __name__ == '__main__':
    unittest.main()

Upvotes: 6

Related Questions