Let's say I have a route '/foo/bar/baz'.
I would also like to have another view corresponding to '/foo' or '/foo/'.
But I don't want to systematically append trailing slashes for other routes, only for /foo and a few others (/buz but not /biz)
From what I saw I cannot simply define two routes with the same route_name.
I currently do this:
config.add_route('foo', '/foo')
config.add_route('foo_slash', '/foo/')
config.add_view(lambda _,__: HTTPFound('/foo'), route_name='foo_slash')
Is there something more elegant in Pyramid to do this ?
Pyramid has a way for HTTPNotFound views to automatically append a slash and test the routes again for a match (the way Django's APPEND_SLASH=True works). Take a look at:
http://docs.pylonsproject.org/projects/pyramid/en/latest/narr/urldispatch.html#redirecting-to-slash-appended-routes
As per this example, you can use config.add_notfound_view(notfound, append_slash=True), where notfound is a function that defines your HTTPNotFound view. If a view is not found (because it didn't match due to a missing slash), the HTTPNotFound view will append a slash and try again. The example shown in the link above is pretty informative, but let me know if you have any additional questions.
Also, heed the warning that this should not be used with POST requests.
There are also many ways to skin a cat in Pyramid, so you can play around and achieve this in different ways too, but you have the concept now.
Found this solution when I was looking for the same thing for my project
def add_auto_route(config,name, pattern, **kw):
config.add_route(name, pattern, **kw)
if not pattern.endswith('/'):
config.add_route(name + '_auto', pattern + '/')
def redirector(request):
return HTTPMovedPermanently(request.route_url(name))
config.add_view(redirector, route_name=name + '_auto')
And then during route configuration,
add_auto_route(config,'events','/events')
Rather than doing config.add_route('events','/events')
Basically it is a hybrid of your methods. A new route with name ending in _auto is defined and its view redirects to the original route.
EDIT
The solution does not take into account dynamic URL components and GET parameters. For a URL like /abc/{def}?m=aasa, using add_auto_route() will throw a key error because the redirector function does not take into account request.matchdict. The below code does that. To access GET parameters it also uses _query=request.GET
def add_auto_route(config,name, pattern, **kw):
config.add_route(name, pattern, **kw)
if not pattern.endswith('/'):
config.add_route(name + '_auto', pattern + '/')
def redirector(request):
return HTTPMovedPermanently(request.route_url(name,_query=request.GET,**request.matchdict))
config.add_view(redirector, route_name=name + '_auto')
I found another solution. It looks like we can chain two #view_config. So this solution is possible:
#view_config(route_name='foo_slash', renderer='myproject:templates/foo.mako')
#view_config(route_name='foo', renderer='myproject:templates/foo.mako')
def foo(request):
#do something
Its behavior is also different from the question. The solution from the question performs a redirect, so the url changes in the browser. In the second form both /foo and /foo/ can appear in the browser, depending on what the user entered. I don't really mind, but repeating the renderer path is also awkward.
Related
I have a Flask app that handles a range of URLs. I'm splitting it up into multiple handler modules, where the handler depends on the first element of the path. The mapping between path/URL prefixes and handlers is a bit like this:
/one/... => Handler A
/two/... => Handler A
/three/... => Handler B
/four/... => Handler B
Calling a given URL under /one/... gets you something very similar (though not identical) to the same URL under /two/ - hence the desire to use the same handler for both those sets of URLs. At the same time Handler A does something very different to Handler B, therefore the desire to implement a clear separation, with separate modules for each.
Blueprints seem to be a great way to do this - and for the most part appear to work well. Where I'm struggling is in setting up differentiated behavior for /one/ vs /two/ (and /three/ vs /four/). In other words, exposing the actual URL prefix to the handler.
As an example handler A looks like
# handler_A.py
from flask import Blueprint
handler_A = Blueprint('handler_A', __name__)
#handler_A('/somepage', methods=['GET'])
def get_page():
return "You've reached somepage provided to you by handler A"
And handler B has a similar structure (but does something very different).
Then the app looks like
# app.py
from flask import Flask
from handler_A import handler_A
from handler_B import handler_B
app = Flask(__name__)
app.register_blueprint(handler_A, url_prefix='/one')
app.register_blueprint(handler_A, url_prefix='/two')
app.register_blueprint(handler_B, url_prefix='/three')
app.register_blueprint(handler_B, url_prefix='/four')
The part that I can't seem to do "nicely" is figuring out whether an endpoint within Handler A (for example) was called from a URL prefixed with /one/ or /two/. This is an important distinction for me, though as soon as the handler is called that information is obscured. I've looked through the docs but can't find a clean way to do this.
The following are the options I've thought of/attempted so far:
Grabbing request.path from within the handler and pulling out the prefix from the string. This is simple and it works, but seems awkward
Setting up a separate blueprint for each top-level path, and "merging" the execution flow from four blueprints into the two handlers I have
Making the top-level of the URL be a parameter that's recorded in the context (like in https://flask.palletsprojects.com/en/1.1.x/patterns/urlprocessors/#internationalized-blueprint-urls). However I think this also requires me to write a custom URL processor, if I want "one" and "two" to match one url_prefix, while "two" and "three" match another.
Is there smart way to do this that I'm missing?
To me the request.path is a good solution. It's awkward in that it's an implicit parameter of the function; the only difference between this and the solution you're looking for is this explicit vs. implicit parameters. I think this method albeit imperfect is more readable than the complexities required to make this explicit.
If you want, you could extract the core function and pass it the results of the request.path s.t. it's more explicit.
#handler_A('/somepage', methods=['GET'])
def getPage():
return pageForPath(request.path)
def pageForPath(path):
return '<html> .... path ... </html>
Code:
class Telegram(tornado.web.RequestHandler):
def my_f(self,number):
return number
def get(self,number):
self.write( self.my_f(number))
application = tornado.web.Application([
(r"/number/(.*?)", Telegram),
])
Using this piece of code, i can trigger Telegram, providing it with something from the (.*?) part.
Question is: i need to make POST queries like:
/number/messenger=telegram&phone=3332223332211
so that I can grab messenger parameter and phone parameter, and trigger the right class with provided phone number (like Telegram with 3332223332211)
POST requests (usually) have a body, so if you want everything in the URL you probably want a GET instead of a POST.
The normal way to pass arguments is by form-encoding them. That starts with a ? and looks like this: /number?messenger=telegram&phone=12345. To use arguments like this in Tornado, you use self.get_argument("messenger") instead of an argument to the get() method.
A second way of passing parameters is to put them in the "path" part of the URL, without a question mark. This is when you use (.*?) in your routing pattern and an argument to get(). Use this when you want to avoid the question mark for some reason (usually aesthetics).
You can also combine the two: pass the messenger parameter in the URL as you've done here, and add ?number=12345 and use get_argument. But unless you really care about what your URLs look like, I recommend the first form.
This is a relatively straightforward question.
Is if possible for a method in views.py to dynamically throw back a URL that it caught in err and let a later handler process it. For example:
urls.py
urlpatterns = patterns('myapp.views',
url(r'^foo/(?P<fiz>\d+)/?$', too_broad_method,name="foo"),
url(r'^foo/bar/?$', just_right_method,name="foo"),
)
views.py
def too_broad_method(request,fiz=None):
if fiz == some_dynamic_value:
# under some runtime conditions fiz can equal bar
# Throw some exception to give the URL back??
else:
return process_it()
Lets say for example, /foo/bar should be caught and processed by too_broad_method if an item has the name bar but otherwise it should be processed by just_right_method.
For extra context, I am trying to catch urls of the form app_label/model_name, which doesn't follow any pattern. I'd like these to be caught first, before anything else, which means using a very broad regex.
(Edited since the entire premise of the question changed)
If you need to catch app_name/model_name URLs, my suggestion is that you generate your URL patterns dynamically. There's no reason you couldn't iterate through INSTALLED_APPS, get all available classes that inherit from models.Model, and create URL patterns in a list accordingly. Then you can feed that into the patterns function at the end.
Trying to inform the URL dispatcher that it was somehow "wrong" is misguided, as I've already explained, and you're solving the wrong problem. Instead, you should focus on configuring the URL patterns how you actually need them.
How do I make a catch-all url route with Flask that ignores static files like favicon.ico and image.png?
Examples:
I want to catch /bZdFFek and ignore /favicon.ico.
I want to catch /of9WfXz and ignore /style.css.
Flask / Werkzeug will generally do the right thing. Routes are sorted in order of complexity, so the least complex routes (like "/favicon.ico") should always match before catch-all routes:
#app.route("/<short_id>")
def view_data(short_id):
return "You are viewing short ID: {}".format(short_id)
#app.route("/favicon.ico")
def favicon():
return send_static_file(FAVICON_PATH)
I think the best way to go would be to use regex in your routing parameters. This answer to another question has a great example of how to do that: https://stackoverflow.com/a/5872904/64266
In my Pylons app, some content is located at URLs that look like http://mysite/data/31415. Users can go to that URL directly, or search for "31415" via the search page. My constraints, however, mean that http://mysite/data/000031415 should go to the same page as the above, as should searches for "0000000000031415." Can I strip leading zeroes from that string in Routes itself, or do I need to do that substitution in the controller file? If it's possible to do it in routing.py, I'd rather do it there - but I can't quite figure it out from the documentation that I'm reading.
You can actually do that via conditional functions, since they let you modify the variables from the URL in place.
I know I am cheating by introducing a different routing library, since I haven't used Routes, but here's how this is done with Werkzeug's routing package. It lets you specify that a given fragment of the path is an integer. You can also implement a more specialized "converter" by inheriting werkzeug.routing.BaseConverter, if you wanted to parse something more interesting (e.g. a UUID).
Perhaps, Routes has a similar mechanism in place for specialized path-fragment-parsing needs.
import unittest
from werkzeug.routing import Map, Rule
class RoutingWithInts(unittest.TestCase):
m = Map([Rule('/data/<int:record_locator>', endpoint='data_getter')])
def test_without_leading_zeros(self):
urls = self.m.bind('localhost')
endpoint, urlvars = urls.match('/data/31415')
self.assertEquals({'record_locator': 31415}, urlvars)
def test_with_leading_zeros(self):
urls = self.m.bind('localhost')
endpoint, urlvars = urls.match('/data/000031415')
self.assertEquals({'record_locator': 31415}, urlvars)
unittest.main()