How do I add a prefix to all urls and generically parse that as a kwarg - django

Let's say I have a site where all urls are username specific.
For example /username1/points/list is a list of that user's points.
How do I grab the /username1/ portion of the url from all urls and add it as a kwarg for all views?
Alternatively, it would be great to grab the /username1/ portion and append that to the request as request.view_user.

You might consider attacking this with middlware. Specifically using process_request. This is called before the urlresolver is called and you can do pretty much anything to the request (request.path in this case) you want to. You might strip out the username and store it in the request object. Specifics depend (obviously) on the conditions under which you do/do not want to remove the first path component.
Updated for comment:
Whichever way you go about it, when you call reverse() you have to give it the additional context info -- it can't just automagically figure it out for itself. Django doesn't play any man-behind-the-curtains games -- everything is straight Python and there isn't any global state floating around just off stage. I think this is a Good Thing™.

Related

API RESTful Resource Naming

I always have the doubt that you can see below when i need to create theresource URLs for a REST API. I wonder if some one can help me.
Let's suppose that i have two models.
User
Post
User can submit his own posts and can comment his own and another posts.
Main resources URLs for User would be:
GET /users # Retrieve all users.
POST /users # Create a new user.
GET/DELETE/PUT /users/{user_id} # Get, remove and update an user.
Main resource URLs for Post would be:
GET /posts # Retrieve all posts.
POST /posts # Create a new post.
GET/DELETE/PUT /posts/{post_id} # Get, remove and update a post.
My problem come when for example i want:
Top 10 submitters (filter for a parameter(external link, discussion, all)). The URL should be:
GET /users/top?type=ext
GET /users/top?type=disc
GET /users/top # for all
Or maybe it should be:
GET /users?top=ext
GET /users?top=disc
GET /users?top=all
The same but with posts:
Top 10 commented post (filter for a parameter(external link, discussion, all)). The URL should be:
GET /posts/comments?type=ext
GET /posts/comments?type=disc
GET /posts/comments # for all
Or maybe it should be:
GET /posts?top=ext
GET /posts?top=disc
GET /posts?top=all
Any of above options are good for you or it should be another way?
Regards
I like to think of the REST URI as a model representation in itself.
So /users/top doesn't make a lot of sense but /posts/comments seems to be fine (as comments could also be a different model). But for your case, I recommend other set of query parameters as they're widely used for filtering & sorting requests. So in your case, I'd recommend something like:
GET /users?sort=ext&order=desc&limit=10
which would help me understand that I'm requesting 10 user resources which have been sorted for ext in the descending order. (you can even change it to type=ext if you want)
As usual; REST doesn't care what spellings you use.
One place you might look for inspiration is... stack overflow itself. Do these URI look familiar?
/questions?sort=newest
/questions?sort=featured
/questions?sort=votes
The API has pretty decent documentation, which will also offer hints at decent spellings to deal with paging and search ranges.
That said, IMDB takes a different approach - The Shawshank Redemption uses a straight forward "I am an element of a collection" spelling
http://www.imdb.com/title/tt0111161/
But the top rated titles of all time? they appear as a chart
http://www.imdb.com/chart/top
But i want to know if there is a standard according to #Hawkes answer or there is no standard at all.
No standard at all; just local spelling conventions. Which is, to some degree, part of the point of REST: the server can use whatever spellings for URI make sense, and the client just "follows its nose" based on its understanding of the processing rules for the media type and the data provided by the server.

CFWheels: Redirect to URL with Params Hidden

I am using redirectTo() function with params to redirect to another pages with a query string in the url. For security purpose this does not look appealing because the user can change the parameters in the url, thus altering what is inserted into the database.
My code is:
redirectTo(action="checklist", params="r=#r#&i=#insp#&d=#d#");
Is there anyway around this? I am not using a forms, I just wish to redirect and I want the destination action/Controller to know what I am passing but not display it in the url.
You can obfuscate the variables in the URL. CfWheels makes this really easy.
All you have to do is call set(obfuscateURLs=true) in the config/settings.cfm file to turn on URL obfuscation.
I am sure this works with linkTo() function. I hope it works with RedirectTo() funcation as well. I do not have a set up to check it now. But if doesn't work for RedirectTo(), you can obfuscateParam() and deObfuscateParam() functions to do job for you.
Caution: This will only make harder for user to guess the value. It doesn't encrypt value.
To know more about this, Please read the document configuration and defaults and obfuscating url
A much better approach to this particular situation is to write params to the [flash].1 The flash is exactly the same thing as it is in Ruby on Rails or the ViewBag in ASP.Net. It stores the data in a session or cookie variable and is deleted at the end of the next page's load. This prevents you from posting back long query strings like someone that has been coding for less than a year. ObfuscateParam only works with numbers and is incredibly insecure. Any power user can easily deobfuscate, even more so with someone that actually makes a living stealing data.

Removing query string from url in django while keeping GET information

I am working on a Django setup where I can receive a url containining a query string as part of a GET. I would like to be able to process the data provided in the query string and return a page that is adjusted for that data but does not contain the query string in the URL.
Ordinarily I would just use reverse(), but I am not sure how to apply it in this case. Here are the details of the situation:
Example URL: .../test/123/?list_options=1&list_options=2&list_options=3
urls.py
urlpatterns = patterns('',
url(r'test/(P<testrun_id>\d+)/'), views.testrun, name='testrun')
)
views.py
def testrun(request, testrun_id):
if 'list_options' in request.GET.keys():
lopt = request.GET.getlist('list_options')
:
:
[process lopt list]
:
:
:
:
[other processing]
:
:
context = { ...stuff... }
return render(request, 'test_tracker/testview.html', context)
When the example URL is processed, Django will return the page I want but with the URL still containing the query string on the end. The standard way of stripping off the unwanted query string would be to return the testrun function with return HttpResponseRedirect(reverse('testrun', args=(testrun_id,))). However, if I do that here then I'm going to get an infinite loop through the testrun function. Furthermore, I am unsure if the list_options data that was on the original request will still be available after the redirect given that it has been removed from the URL.
How should I work around this? I can see that it might make sense to move the parsing of the list_options variable out into a separate function to avoid the infinite recursion, but I'm afraid that it will lose me the list_options data from the request if I do it that way. Is there a neat way of simultaneously lopping the query string off the end of the URL and returning the page I want in one place so I can avoid having separate things out into multiple functions?
EDIT: A little bit of extra background, since there have been a couple of "Why would you want to do this?" queries.
The website I'm designing is to report on the results of various tests of the software I'm working on. This particular page is for reporting on the results of a single test, and often I will link to it from a bigger list of tests.
The list_options array is a way of specifying the other tests in the list I have just come from. This allows me to populate a drop-down menu with other relevant tests to allow me to easily switch between them.
As such, I could easily end up passing in 15-20 different values and creating huge URLs, which I'd like to avoid. The page is designed to have a default set of other tests to fill in the menu in question if I don't suggest any others in the URL, so it's not a big deal if I remove the list_options. If the user wishes to come back to the page directly he won't care about the other tests in the list, so it's not a problem if that information is not available.
First a word of caution. This is probably not a good idea to do for various reasons:
Bookmarking. Imagine that .../link?q=bar&order=foo will filter some search results and also sort the results in particular order. If you will automatically strip out the querystring, then you will effectively disallow users to bookmark specific search queries.
Tests. Any time you add any automation, things can and will probably go wrong in ways you never imagined. It is always better to stick with simple yet effective approaches since they are widely used thus are less error-prone. Ill give an example for this below.
Maintenance. This is not a standard behavior model therefore this will make maintenance harder for future developers since first they will have to understand first what is going on.
If you still want to achieve this, one of the simplest methods is to use sessions. The idea is that when there is a querystring, you save its contents into a session and then you retrieve it later on when there is no querystring. For example:
def testrun(request, testrun_id):
# save the get data
if request.META['QUERY_STRING']:
request.session['testrun_get'] = request.GET
# the following will not have querystring hence no infinite loop
return HttpResponseRedirect(reverse('testrun', args=(testrun_id,)))
# there is no querystring so retreive it from session
# however someone could visit the url without the querystring
# without visiting the querystring version first hence
# you have to test for it
get_data = request.session.get('testrun_get', None)
if get_data:
if 'list_options' in get_data.keys():
...
else:
# do some default option
...
context = { ...stuff... }
return render(request, 'test_tracker/testview.html', context)
That should work however it can break rather easily and there is no way to easily fix it. This should illustrate the second bullet from above. For example, imagine a user wants to compare two search queries side-by-side. So he will try to visit .../link?q=bar&order=foo and `.../link?q=cat&order=dog in different tabs of the same browser. So far so good because each page will open correct results however as soon as the user will try to refresh the first opened tab, he will get results from the second tab since that is what is currently stored in the session and because browser will have a single session token for both tabs.
Even if you will find some other method to achieve what you want without using sessions, I imagine that you will encounter similar issues because HTTP is stateless hence you will have to store state on the server.
There is actually a way to do this without breaking much of the functionality - store state on client instead of server-side. So you will have a url without a querystring and then let javascript query some API for whatever you will need to display on that page. That however will force you to make some sort of API and use some javascript which does not exactly fall into the scope of your question. So it is possible to do cleanly however that will involve more than just using Django.

How to pass language information from page to page?

If I have a multilingual site, what is the best way to pass information about language?
Right now the language is saved in cookies. That's convenient except that might be not good for search optimization, if search bots don't use cookies.
The other option would be specifying language in address, like exampel.com/?lang=de, but then you probably need to add ?lang=xx to every link on the page.
Is there a right way?
Better way is to maintain this info in session,
The other option would be specifying
language in address, like
exampel.com/?lang=de, but then you
probably need to add ?lang=xx to every
link on the page.
Is there a right way?
I would have created filter than parse each request and fetches the lang param and process accordingly.
Moreover I would recommend you to use following url pattern, and get the lang from filter
yourapp.com/en/welcome/
If you want all the content crawlable then you'd have to pass it in the URL. Either as a parameter http://mydomain.com/en/english-content or maybe have separate sites/subdomains http://english.mydomain.com/english-content
I would use Wikepedia's approach: Different URLs for different languages.
http://en.wikipedia.org for english
http://es.wikipedia.org for Spanish

Recursive URL Patterns CMS Style

Whenever I learn a new language/framework, I always make a content management system...
I'm learning Python & Django and I'm stuck with making a URL pattern that will pick the right page.
For example, for a single-level URL pattern, I have:
url(r'^(?P<segment>[-\w]+)/$', views.page_by_slug, name='pg_slug'),
Which works great for urls like:
http://localhost:8000/page/
Now, I'm not sure if I can get Django's URL system to bring back a list of slugs ala:
http://localhost:8000/parent/child/grandchild/
would return parent, child, grandchild.
So is this something that Django does already? Or do I modify my original URL pattern to allow slashes and extract the URL data there?
Thanks for the help in advance.
That's because your regular expression does not allow middle '/' characters. Recursive definition of url segments pattern may be possible, but anyway it would be passed as a chunk to your view function.
Try this
url(r'^(?P<segments>[-/\w]+)/$', views.page_by_slug, name='pg_slug'),
and split segments argument passed to page_by_slug() by '/', then you will get ['parent', 'child', 'grandchild']. I'm not sure how you've organized the page model, but if it is not much sophiscated, consider using or improving flatpages package that is already included in Django.
Note that if you have other kind of urls that does not indicate user-generated pages but system's own pages, you should put them before the pattern you listed because Django's url matching mechanism follows the given order.