Django Url Dispatcher regex - python

I want SOMETHING to be non mandatory so basically I want www.site.com/endpoint to redirect to www.site.com/something/endpoint automatically. I there a way to do it on one line?
Right now I am doing:
url(r'^SOMETHING/endpoint$', 'endpoint', name='endpoint'),
url(r'^endpoint$', RedirectView.as_view(url='SOMETHING/endpoint')),
Cheers.

Why do you want to do this on one line? You're talking about two different URLs that do two different things—one is doing an HTTP redirect and the other is rendering a view. Two lines is the right way to go.
Writing a broader regex to cover both URLs will allow you to use the same view for both, but will not cause a redirect (that is, it will not change the URL to SOMETHING/endpoint).

I believe you are asking to let any url ending in "endpoint" to redirect.
To accomplish this change your redirect url regex to r"endpoint$". The caret operator in regex essentially says from the start of the string.
This regex will match for any url ending in "endpoint", eg. foo/endpoint, bar/endpoint

Related

Is it possible to use multiple slash Django URL as one variable in Django?

I'm new to Django. I'm now creating a project. In that project, I've links like this:
https://localhost:8000/example.com/example/path/
In the URL the example.com/example/path/ can be dynamically long as like this
example.com
or
example.com/asset/css/style.css
or
domain.com/core/content/auth/assets/js/vendor/jquery.js
I've used <str:domainurl> But is not working. As it has multiple forward slashes. And the forward slashes URL length generated while web scraping.
So is there is a way to use the full URL as one variable?
You want to be using the path path converter [Django docs]:
path('<path:domainurl>/', some_view)
Quoting Django docs:
path - Matches any non-empty string, including the path separator, '/'. This allows you to match against a complete URL path rather than a segment of a URL path as with str.
Note: Design your url patterns and order them carefully if you are going to use this. Django uses the first matching url pattern to
serve any request.
If you want Django to match some custom strings take a look at re_path (https://docs.djangoproject.com/en/3.1/ref/urls/#django.urls.re_path) function. It basically allows you to pass a regular expression.
For the urls samples you provided you would probably want an expression like this (in your urls.py):
re_path(r'^(?P<my_url>[a-z0-9/\.]+)$', your_view_function)
This will pass a my_url kwarg to your view which you can then process as you want.

URL Encoding/Decoding in python (whole url, not just the path)

I have done a lot of search and experimentation, and I havent been able to find the solution. So, if there is something trivial I missed, I appologize ahead of time.
Problem:
I have a python turbogears app that is downloading url resources. It is being given a URL to download by clients.
One client in particular sends unescaped urls. For eg, 'http://www.foo.com/file with space.txt'
When I try to download it, the download fails, because the server does not recognize this url. It needs to have the spaces escaped to be a valid url.
I know that there are methods ( urllib.urlencode/urllib.quote etc) that will encode strings. However they assume that the strings they work on are not urls. If you give a URL to these methods, they escape the scheme of the url, and make it even more invalid.
So, the summary is: How do I unescape a whole fully qualified url in python?
NOTE: I have tried using urlparse to parse out the url components to get at the path. However sometimes the url will have query parameters, fragments etc. So, I do not want to write code that splits the url into its parts, escapes whatever is required only from the path+query+fragment, and then reconstructs the url.
Is there any helper function that directly takes the url, and escapes it?
Also, note that sometimes I get valid escaped urls from clients. So, I want to handle them as well, without double escaping them.
Ok, I found the following on pypi. This seems to solve the problem.
https://github.com/seomoz/url-py/
This is the url egg from seomoz. Seems to do the job very well.
You can use regular expressions to separate the domain name and the file path, then only urlencode the path. Here's the regex documentation, here's a tutorial.

How can I write the regex for those urls

I'm trying to build a small wiki, but I'm having problems writing the regex rules for them.
What I'm trying to do is that every page should have an edit page of its own, and when I press submit on the edit page, it should redirect me to the wiki page.
I want to have the following urls in my application:
http://example.com/<page_name>
http://example.com/_edit/<page_name>
My URLConf has the following rules:
url(r'(_edit/?P<page_name>(?:[a-zA-Z0-9_-]+/?)*)', views.edit),
url(r'(?P<page_name>(^(?:_edit?)?:[a-zA-Z0-9_-]+/?)*)', views.page),
But they're not working for some reason.
How can I make this work?
It seems that one - or both - match the same things.
Following a more concise approach I'd really define the edit URL as:
http://example.com/<pagename>/edit
This is more clear and guessable in my humble opinion.
Then, remember that Django loops your url patterns, in the same order you defined them, and stops on the first one matching the incoming request. So the order they are defined with is really important.
Coming with the answer to your question:
^(?P<page_name>[\w]+)$ matches a request to any /PageName
Please always remember the starting caret and the final dollar signs, that are saying we expect the URL to start and stop respectively right before and after our regexp, otherwise any leading or trailing symbol/character would make the regexp match as well (while you likely want to show up a 404 in that case).
^_edit/(?P<page_name>[\w]+)$ matches the edit URL (or ^(?P<page_name>[\w]+)/edit$ if you like the user-friendly URL commonly referred to as REST urls, while RESTfullnes is a concept that has nothing to do with URL style).
Summarizing put the following in your urls:
url(r'^(?P<page_name>[\w]+)$', views.page)
url(r'^_edit/(?P<page_name>[\w]+)$', views.edit)
You can easily force URLs not to have some particular character by changing \w with a set defined by yourself.
To learn more about Django URL Dispatching read here.
Note: Regexp's are as powerful as dangerous, especially when coming on network. Keep it simple, and be sure to really understand what are you defining, otherwise your web application may be exposed to several security issues.
Some people, when confronted with a problem, think "I know, I'll use regular expressions." Now they have two problems. -- Jamie Zawinski
Please try the following URLs, that are simpler:
url(r'_edit/(?P<page_name>[\w-]+), views.edit)'
url(r'(?P<page_name>[\w-]+), views.page),

Configuring urls.py with this regular expression

I'm trying to build my first Django-powered blog, but I'm stuck in a point.
I'm trying to grab a permanent link from the URL visited in order to display a single post.
The permanent link I'm using is like that:
http://127.0.0.1:8000/blog/20-feb-2012/a-nice-post/
I'd like to grab both the date and the slug from this URL and pass them into a view's function.
I've made this regular expression:
(r'^blog/(?P<day>\d{2})-/(?P<month>\w{3})-/(?P<year>\d{4})/(P?<slug>[-\w]+)/$','blog.views.single_post'),
In the urls.py file, but it seems it is not working.
What's wrong with this regular expression?
You have included slashes between the day-month-year. Remove them.
(r'^blog/(?P<day>\d{2})-(?P<month>\w{3})-(?P<year>\d{4})/(?P<slug>[-\w]+)/$','blog.views.single_post'),
Without checking anything else, you have P? instead of ?P in the slug part.
For starters, you have extra slashes in your regexp for example here (?P<month>\w{3})-**/**(?P<year>\d{4}) and also you have a P? instead of ?P at the end.
In addition, I thought you might want to have a working regexp example. So I tested this one and it works for /blog/20-feb-2012/a-nice-post/:
r'^blog/(?P<day>\d{2})-(?P<month>\w{3})-(?P<year>\d{4})/(?P<slug>[-\w]+)/$'

Does django support hashbang in its URL?

Does django support urls having #! in it.Say I have ursl like
http://example.com/foo/!#/bar
Any regex for that?
Note: http://example.com/foo/ and http://example.com/foo/#!/bar are different URLs and having different corresponding Views.
url(r'^(?P<#!>.+)/bar/$', 'my_view', name='my-view'), throwing bad character in group name
No. Anything after the # is not even sent to your webserver. If you want to make interactivity using the anchored (#) url styles, you need to go look at ajax libraries like jquery.
This is the "evil standard" way of denoting AJAX URLs. For a better description of the topic you should referer to this document http://code.google.com/web/ajaxcrawling/ which describes both what they are and how then to make URL handlers on your site handle them.

Categories

Resources