Does Flask Support Regular Expressions in Its Url Routing

Does Flask support regular expressions in its URL routing?

Even though Armin beat me to the punch with an accepted answer I thought I'd show an abbreviated example of how I implemented a regex matcher in Flask just in case anyone wants a working example of how this could be done.

from flask import Flask
from werkzeug.routing import BaseConverter

app = Flask(__name__)

class RegexConverter(BaseConverter):
def __init__(self, url_map, *items):
super(RegexConverter, self).__init__(url_map)
self.regex = items[0]

app.url_map.converters['regex'] = RegexConverter

@app.route('/<regex("[abcABC0-9]{4,6}"):uid>-<slug>/')
def example(uid, slug):
return "uid: %s, slug: %s" % (uid, slug)

if __name__ == '__main__':
app.run(debug=True, host='0.0.0.0', port=5000)

this URL should return with 200: http://localhost:5000/abc0-foo/

this URL should will return with 404: http://localhost:5000/abcd-foo/

Use regular expressions to extract information from a URL

Adapted from this answer. You can also use this example from the documentation of Werkzeug.

from flask import Flask
from werkzeug.routing import BaseConverter

class RegexConverter(BaseConverter):
def __init__(self, url_map, *items):
super().__init__(url_map)
self.regex = items[0]

app = Flask(__name__)
app.url_map.converters['regex'] = RegexConverter

@app.route('/page<regex("\d+"):page_id>/')
def page(page_id):
return f"Page ID: {page_id}"

if __name__ == '__main__':
app.run()

Sample Image

Trouble understanding flask url routing with input from form

ATTRIBUTE ERROR

I think the way you are trying to get the td's is the issue,
something like this may be easier to do:

match = soup.findAll('table', {'class':'fullview-news-outer'})
rows = match.findAll('tr')
for row in rows:
k = row.findAll('td') #This (k) is the td

ROUTING

You are missing one main thing that I think could solve your problem.
When defining a route and it's methods like POST or GET, you need to cater for them.

@app.route('/', methods=['GET', 'POST'])
def index():
if request.method == "POST":
ticker = request.form['ticker']
#data processing or loading tables etc.
return render_template('index.html', ticker=ticker)
else:
#Normal Page Load
return render_template("index.html", ticker=None)

You also may want to allow for the none type of ticker using an if statemen in your html:

{% if ticker == None %} No news {% endif %}

Can you make a dynamic route with / in the middle of the dynamic part in Flask?

From the Flask documentation on URL variables:

from flask import Flask

app = Flask(__name__)

@app.route('/')
def hello_world():
return 'Hello, World!\n'

@app.route('/path/<path:subpath>')
def show_subpath(subpath):
return 'Subpath %s\n' % subpath

Example requests from the command line:

$ curl http://127.0.0.1:5000
Hello, World!
$ curl http://127.0.0.1:5000/path/test/page
Subpath test/page

If you wanted to do something similar with regular expressions, the common solution seems to be adding a regex 'converter', but the path URL variable appears to exist for exactly what you're asking about.

Python flask app routing in cpanel: can only access root url

A member of our team worked this out by adding a new subdomain and setting the url there.

So instead of mydomain.com/backend the app is running now at backend.mydomain.com/backend and working just fine.

Cheers

Flask app route for paths that start with X

I would do a catch-all url and then, try to use a wildcard with it from inside the view:

@app.route('/<path:text>', methods=['GET', 'POST'])
def all_routes(text):
if text.startswith('favicon'):
#do stuff
else:
return redirect(url_for('404_error'))

you can use string too:

@app.route('/<string:text>', methods=['GET'])

but using string wouldn't catch / strings. so if string is used, url's containing something like favicon/buzz wouldn't be cached by it, path in the other hand would catch /'s too. so you should go with first option.

you can look at routing documentation in flask site. and you should create a better conditional than if x in Y because it will fail if you were passed something like /thingfavicon



Related Topics



Leave a reply



Submit