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
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.
I'm using this syntax for my API urls:
http://myhost/myapiname/X-Y-Z/web-service-name/
In Django urls.py, it looks like this:
url(r'api_s/2-0-0/get_client_profile/$', GetClientProfile.as_detail(), name='get_client_profile'),
Now, I'd like to redirect all 1-0-0 urls (deprecated webservices) to a specific view.
I tried something like url(r'api_t/1-0-0*$', Deprecated.as_list(), name='deprecated') but it can't be catch. I'm not used to REGEX so I'm missing something here. Thanks.
Add a dot before *:
url(r'api_t/1-0-0.*$', Deprecated.as_list(), name='deprecated')
The asterisk * sign means "repeat previous symbol zere or more times". The dot . means "any char". So .* will match any string.
I'm having some trouble sending along more than one variable to the view.
my urls.py is as follows:
urlpatterns = patterns('',
url(r'^rss/(?P<anything>[^/]+)/$', 'rss.rssama.views.makerss', name='anything'),
url(r'^$', 'rss.rssama.views.home'),
)
views.py
def maakrss(request, anything):
So now it takes from www.mydomain.com/rss/[anything]/ and sends 'anything' to my view. However I also want it to send along another string to views.py, like:
www.mydomain.com/rss/[anynumber]/[anystring]/
I tried this but that didn't work:
url(r'^rss/(?P<anynumber>[^/]+)/(?P<anystring>[^/]+)/$', 'rss.rssama.views.makerss', name='anynumber', name2='anystring'),
But this doesn't work, it gives this error: keyword argument repeated (urls.py, line 17)
So my question: How can I make it to give along two string from the url?
To begin with, the regex part should look like this:
r'^/rss/(?P<anynumber>\d+)/(?P<anystring>.+)/$'
Those strings inside the <...> parts allow you to give a name to whatever the regex matches. Django will then use that name to pass the value to your function. Therefore your function must have an argument with the same name. In this case, Django will take the value called anynumber and use that value for the parameter of your function that is called anynumber. The same goes for anystring, and this system frees you from worrying about what order the arguments of your function are in.
\d+ will match one or more numeric characters (digits). It's good practice to limit the regex to match only numbers if that's what you intend to catch, rather than any character and hope that only numbers appear. If you wanted to limit the digits part to a certain number of digits, you could use \d{1,4} to take from one to four digits.
The next part, (?P<anystring>.+) will catch a string consisting of one or more of any characters. This would actually match something like 'letters/moreletters', including the slash. There are a number of "special sequences" in Python regex that might help. To match only digits, letters, and the underscore character, use \w, as in (?P<anystring>\w+). To be more lax but ignore whitespace or any other non-sense, (?P<anystring>[a-zA-Z1-9:;_{}\[\]] to catch a whole slew of characters. Make sure to escape anything that might be a special character in a regex. However, be conservative. If you allow too many options who knows what sorts of bugs you'll have to work out later.
Now onto name parameter of the url function. That name is not what it will pass the caught patterns to your functions as. It's a name for a particular class of invocation of your view function that can be used as a short-hand in other contexts like, the template tag {% url view-name arg1 arg2 %}. So, the name you have already, "anything", refers to a call to your view function, passing it one keyword argument that happens to be called anything. For the case where you want to pass two strings, give that a name like "rss-number-string" to signify the arguments you want to take, or a name that refers to the special function your view will be performing with that combination.
I use multiple names for the same function all the time, and the key is this:
def makerss(request, anystring=None, anynumber=None):
By giving the parameters default values, it allows you to use the same function in different ways. In this case, the function can be used when you only want to pass a value for anystring, or when anystring and anynumber should have values.
I know this is a lot of different points, so I'll try to put it all together so you can see how it might work. To have two urls, one which catch a string and passes it on, and another which catches a number, a slash, and then a string, but both point to the same view function, you could use this:
urlpatterns = patterns('',
url(r'^rss/(?P<anystring>\w+)/$', 'rss.rssama.views.makerss', name='rss-anystring'),
url(r'^rss/(?P<anynumber>\d+)/(?P<anystring>\w+)/$', 'rss.rssama.views.makerss', name='rss-number-string'),
url(r'^$', 'rss.rssama.views.home'),
)
With a view function something like this:
def makerss(request, anystring=None, anynumber=None):
if anystring:
if anynumber:
#Do something with the string and the number
else:
#Do something with just the string
Please let me know if this helps. Also, Django rocks, so kudos!
Python Regex Library Docs
You don't really need to give two name arguments for this. I mean, you already have the variable names inside regex. The actual problem is, you cannot give two name arguments, so you can do this instead:
url(r'^rss/(?P<anynumber>[^/]+)/(?P<anystring>[^/]+)/$', 'rss.rssama.views.makerss',name='something'),
EDIT:
using the urlConf above you can create corresponding view as:
def makerss(request, anynumber, anystring):
What is name2 supposed to be? The url function takes a name parameter, which is the name of the URL when you reverse it, but you can't put random extra functions.
Otherwise, you have the right syntax for sending two elements to a view. Of course, since you've masked the variable names and not provided the actual error or traceback, we have no way of knowing what really is going wrong.
Is there a way in Django to accept 'n' parameters which are delimited by a '/' (forward slash)?
I was thinking this may work, but it does not. Django still recognizes forward slashes as delimiters.
(r'^(?P<path>[-\w]+/)$', 'some.view', {}),
Add the right url to your urlpatterns:
# ...
("^foo/(.*)$", "foo"), # or whatever
# ...
And process it in your view, like AlbertoPL said:
fields = paramPassedInAccordingToThatUrl.split('/')
Certainly, Django can accept any URL which can be described by a regular expression - including one which has a prefix followed by a '/' followed by a variable number of segments separated by '/'. The exact regular expression will depend on what you want to accept - but an example in Django is given by /admin URLs which parse the suffix of the URL in the view.