Route's with a leading/traling slash and without slashes - python

Could you please explain to me the diffference between:
#app.route( '/something' )
compared to:
#app.route( 'something/' )
and also compared to:
#app.route( 'something' )
So i can better distinguish them?

In a word, /foo was the normal use case, /foo/ was used when you want to make the URL looks like a path/folder, foo was wrong. If I'm wrong, please correct me.
The URL rule should start with a slash(/).
/foo and /foo/ was two different URL rule, see the details in the docs:
The following two rules differ in their use of a trailing slash.
#app.route('/projects/')
def projects():
return 'The project page'
#app.route('/about')
def about():
return 'The about page'
The canonical URL for the projects endpoint has a trailing slash. It’s similar to a folder in a file
system. If you access the URL without a trailing slash, Flask
redirects you to the canonical URL with the trailing slash.
The canonical URL for the about endpoint does not have a trailing
slash. It’s similar to the pathname of a file. Accessing the URL with
a trailing slash produces a 404 “Not Found” error. This helps keep
URLs unique for these resources, which helps search engines avoid
indexing the same page twice.
Link: http://flask.pocoo.org/docs/1.0/quickstart/#unique-urls-redirection-behavior

Related

No trailing slash results in a 404 error in Flask app

-- Resolved without changing anything. Will update when I know what caused it to temporally not work --
I made a route to a URL without a trailing slash on Flask. This should work according to the docs:
timestamp = "temptime"
#app.route('/js/searchindex<time>.js')
def searchindex(time):
return render_template('searchindex.js')
What happens is that the URL gets redirected to the URL with trailing slash, which obviously results in a 404 error. So http://127.0.0.1:5000/js/searchindextemptime.js becomes http://127.0.0.1:5000/js/searchindextemptime.js/.
I am aware that I can set the slashes to not-strict to avoid the 404, but I really want without trailing slash.

Django url warning urls.W002

Sorry in advance if this question look a bit superfluous but is something that is really bothering me.
I have a set of API's written in Django defined by the following urls.
# urls.py
import ...
urlpatterns = [
url(r"^api/v1/account", include(profile.urls))
]
and
# profile/urls.py
import ...
urlpatterns = [
url(r"^$", AccountAPI.as_view()),
url(r"^/login$", LoginAPI.as_view()),
url(r"^/logout$", LogoutAPI.as_view())
]
This configuration should allow only the urls:
/api/v1/account
/api/v1/account/login
/api/v1/account/logout
This work for my purpose but I keep having warnings like(I have several API defined with this rule and the warning list is way bigger):
?: (urls.W002) Your URL pattern '^/login$' has a regex beginning with a '/'. Remove this slash as it is unnecessary.
?: (urls.W002) Your URL pattern '^/logout$' has a regex beginning with a '/'. Remove this slash as it is unnecessary.
If I remove the slash the server will not validate the urls I defined. For that I have to had a slash to the first level of the urls like:
# urls.py
import ...
urlpatterns = [
url(r"^api/v1/account/", include(profile.urls))
]
And this will make the account call to end with a slash, something I don't want to.
I feel that I have defined the urls the most elegant way I found to serve my purpose and I keep having this sad warnings in my logs.
Am I doing something wrong? Is there a right way to define the url's without compromising the structure I choose for them? Or there's a way of turning this warnings off?
You can turn the warning(s) off using SILENCED_SYSTEM_CHECKS option.
Example:
SILENCED_SYSTEM_CHECKS = ['urls.W002', 'security.W019']
When I wrote the check, I incorrectly assumed urls with trailing slashes, like /api/v1/account/ and /api/v1/account/login/.
If you do not use trailing slashes, then starting an included url pattern with ^/ can be correct, and the W002 check gives a false positive.
As of Django 1.10.2, the check is disabled if you have APPEND_SLASH=False in your settings. See ticket 27238 for the discussion.
this will make the account call to end with a slash, something I don't want to.
Why? Is there any specific reason?
As far as Django is concerned, there's nothing incorrect in ending a url with a slash. Moreover, Django's admin urls end in a slash. Django polls tutorial also appends slash to root URLconfs.
If you read URL Dispacher example, it says:
There’s no need to add a leading slash, because every URL has that. For example, it’s ^articles, not ^/articles.

Twisted, how to "putChild()" with trailing slash?

Im using twisted, and made a webserver, but when i try to request a page with a trailing slash i get
"No Such Resource - No such child resource."
I tried all of these
self.putChild('login', Login(self))
self.putChild('/login/', Login(self))
self.putChild('/login', Login(self))
self.putChild('login/', Login(self))
Even tried overriding the 'getChildWithDefault' method, and tried requesting pages with both slashes and no slash, and it always say the path is 'login', no slashes, so it should always match the first line, but doesn't for w.e reason.
Anyone know how to add a child resource with the trailing slash?
You can't pass a slash to putChild; it will be escaped by the URL traversal logic, because the argument is a single path segment.
Assuming that Login is itself a Resource though, you can put itself onto itself, so that both /login and /login/ will work, like so:
l = Login(self)
l.putChild("", l)
self.putChild("login", l)
You can of course make /login without the trailing slash a resource of your own design, or a twisted.web.util.Redirect that adds a slash; assemble your resources in whichever configuration you prefer :).

Urls.py unable to pass #(pound) character to a view in Django,

I used to pass data through django URL while passing #character is not able to pass through urls.py, I am using pattern as
url(r'^pass/(?P<sentence>[\w|\W]*)/$',pass)
I tried with these pattern also
url(r'^pass/(?P<sentence>[a-zA-Z0-9-/:-?##{-~!^_\'\[\]*]*)/$',pass)
Thanks in advance.
The "#" character marks inline anchors (links within the same page) in a URL, so the browser will never send it to Django.
For example, if the URL is /something/pass/#test/something-else/ the browser will sent only /something/pass/ to the server. You can try /something/pass/%23test/something-else/ instead, 23 is the hexadecimal ascii code for # - not pretty (ugly by ugly just pass it as a get variable instead).
There is nothing you can do on the Django side - you better avoid characters with special meanings in the URL path when designing your routes - of course it is a matter of taste, but I really think that strings passed in the URL path should be "slugfied" in order to remove any funny character.
Browsers won't send the url fragment part (ends with "#") to servers. Why not converting your data to base64 first, then pass the data via url.
RFC 1808 (Relative Uniform Resource Locators) : Note that the fragment identifier (and the "#" that precedes it) is
not considered part of the URL. However, since it is commonly used
within the same string context as a URL, a parser must be able to
recognize the fragment when it is present and set it aside as part of
the parsing process.

Flask route with URI encoded component

It seems Flask doesn't support routes with a URI encoded component. I'm curious if I'm doing something wrong, or if there is a special flag I need to include.
My route looks something like this:
#app.route('/foo/<encoded>/bar/')
def foo(encoded):
# ...
pass
The URL that this should match can look like these:
http://foobar.com/foo/xxx/bar/ # matched correctly, no URI component
http://foobar.com/foo/x%2Fx%2Fx%2F/bar/ # not matched correctly, URI component
Former URL works, latter spits out a lovely 404.
Thanks!
Add path to your url rule:
#app.route('/foo/<path:encoded>/bar/')
Update per comment: The route API docs are here: http://flask.pocoo.org/docs/api/#flask.Flask.route. The underlying classes that implement the path style route converter are here: http://werkzeug.pocoo.org/docs/routing/#custom-converters (this is one of the really nice parts of pocoostan.) As far as the trailing slashes, there are special rules that amount to:
If a rule ends with a slash and is requested without a slash by the
user, the user is automatically redirected to the same page with a
trailing slash attached.
If a rule does not end with a trailing slash and the user request the
page with a trailing slash, a 404 not found is raised.
Also keep in mind that if you are on Apache and are expecting a slash-trailed url, ie a bookmarklet that submits to http://ex.com/foo/<path:encoded>/bar and encoded gets something with double slashes, Apache will convert multiple slashes to a single one.

Categories