Shoot for a Clean, Elegant URL Scheme: Path Parameter and QueryStrings

JunePyo Suh·2020년 5월 24일
0

When a user requests a page from a Django-powered site, Django first determines the root URLconf module to use. Django then loads that Python module and looks for urlpatterns. Once one of the URL patterns matches, Django imports and calls the given view. The view gets passed the following arguments:

  • An instance of HttpRequest
  • If the matched URL pattern contains no named groups, then the matches from the regular expression are provided as positional arguments
  • The keyword arguments are made up of any named parts matched by the path expression that are provided. Initialized keyword arguments passed to a view function will get overriden by any arguments passed through path() in urlpatterns.

URL path parameters

Take an example provided by Django documentation.

Use angle brackets to capture a value from the URL. In the above example, optional converter types are included to capture specific types of parameters. For instance, <int:name> captures an integer parameter. If a converter isn't included, any string, excludign a / character, is matched.

URL patterns are tested in order

/articles/2003/ would match the first pattern in the list, not the second one.

/articles/2003/03/building-a-django-site/ would match the final pattern

Path converters

Again, from the Django documentation,

Using regular expressions

There may be times when the paths and converters syntax isn't sufficient for defining your URL patterns. If this is your case, use regular expressions. To do so, use re_path(). Above urlpatterns can be rewritten as following:

It is important to note that each captured arugment is sent to the view as a string, so be aware that the type of the view arguments may change.

Specifying defaults for view arguments

By specifying a default parameter value for your view's arguments, you can let your view function cover two different endpoint patterns.
For example,

urlpatterns = [
  path('feed/', views.page),
  path('feed/page<int:num>/', views.page),
]

// View (in feed/views.py)
def page(request, num=1):
	// Outputs the appropriate page of feed entries, according to num
	...

If the first pattern matches, the page() function will use its default argument for num, 1. If the second pattern matches, page() will use whatever num value was captured.

The names of url parameters must match the names of the method arguments.

Passing extra options to view functions

URLconfs lets you pass extra arguments to your view functions in the form of a Python dictionary.

urlpatterns = [
	path('feed/<int:post_id/', views.year_archive, {'foo':'bar'}),
]

Reverse resolution of URLs

There may be times when you need to refer to URL paths without hard-coding the URLs. You do so by using the reverse() function and get_absolute_url() method.
Use named URL patterns to facilitate calling your URL patterns.

URL Query Strings

URL query string processing

URL parameters separated by ? and &, better known as a query string, can be accessed inside a view method using the request object.
Take for example the url /feeds/1/?hours=sunday&map=flash. Below is an illustration of how to extract the arguments from this url by using request.GET.

from django.shortcuts import render

def feed(request, feed_id=1, location=None):
	// Extract 'hours' or 'map' value appended to url 
	hours = request.GET.get('hours', '')
	map = request.GET.get('map', '')
	// 'hours' has value 'sunday' or '' if hours not in url
	// 'map' has value 'flash' or '' if map not in url
	return render(request, 'feeds/feed.html')

The basic syntax is: request.GET.get(<parameter>, '')

Request.GET

request.GET refers to the dictionary of the GET variables in the http request made to a server. Take a look at the following url:
www.google.com?search=querystring&page=2
Here, request.GET would be {'search':'querystring', 'page':2}
We can take on the advantage of request.GET being a dictionary, which is by using the .get() method to retrieve a value for a key in query string.

Request.GET.getlist()

Request.GET.getlist() is useful when there is a need to retrieve a list from a query string.
http://127.0.0.1:8000/auction?search=\['querystring','django','python'] will return:
['querystring', 'django', 'python']

However, if comma separated values are provided, www.google.com?search=querystring,django,python,
request.GET.getlist('page') will return ['querystring, django, python'], which might not be the most convenient form for further parsing.

In case like above, it is recommended to simply use the .get() method and split the string values into a list:

values 	= request.GET.get('search', None)
values_list = values.split(',') if values else None

0개의 댓글