Handling multiple sub-urls in Django's url.py file - django

In my djang urls pattern file, I'd like to hold a bunch of sub-url's but I don't want to make it ugly.
I have a file which handles all of my Ajax requests (it outputs different JSON files depending on the request it gets.
example (in my url.py):
in the form: (url, maps to)
(ajax/do_a, ajax.do_a)
ajax/do_b, ajax.do_b)
ajax/do_c, ajax.do_c)
ajax/do_d, ajax.do_d)
these are all sub-urls, eg.
mywebsite.com/ajax/do_a
mywebsite.com/ajax/do_b
etc.
Basically do_a,do_b,do_c,and do_d are all different request handlers sitting in the same same in the "ajax.py" file. I really don't want to be filling up my urls.py file with all of these urls for ajax requests. I was thinking of move this so that I only have
ajax/
in my url.py file and then somehow parse the ajax/ request url in my request handler (in the ajax.py file) so I can see what string came after the "ajax/". I'm not sure how to do this or if this would be a good idea to do this....Could anyone offer some advice? thanks :)

You could set up a dispatcher view for handling these. For example, in your urls.py:
(r'^ajax/do_(?P<do_token>(\d+))/$', 'do_dispatcher', {}, "di_dispatcher"),
Then, give yourself a view to handle it:
def do_a(request):
pass
def do_b(request):
pass
def do_c(request):
pass
DO_LOOKUP = {
'a' = do_a,
'b' = do_b,
'c' = do_c,
}
def do_dispatch(request, do_token):
do_func = DO_LOOKUP.get(do_token, None)
if do_func is None:
return HttpResponseNotFound("No do could be found for token '%s'!" % do_token)
else:
return do_func(request)

Related

In Django, How do you write the url pattern for a json file?

My website generates json files in saves them with the user specified name: test.json
I couldn't immediately access it, so I assumed that I would have to write a URL pattern and view to see this file.
I want something akin to this :
url(r'^(?P<Controller>).json$', views.loadjson, name='loadjson')
If you need to serve static JSON files then doing so through Django is not the best way - if that's the case use something like Nginx.
If you wan't Django to generate those files and/or for e.g. an authentication mechanism in front of it then ok for Django.
To your question:
# urls.py
url(r'^(?P<json_file>[\w]+).json$', views.loadjson, name='loadjson')
It seems like you forgotten about [\w]+ which I guess is the right pattern for your needs.
the view function will be called with a WSGIRequest instance and the json_file argument (from your url pattern), from there you should be able to do whatever you like with the file. It's a good idea to return in as an application/json content type as those are supposed to be JSON.
# views.py
from django.http import HttpResponse
def loadjson(request, json_file):
# open, generate, fetch the json file
# for e.g.:
json_content = read_file(json_file)
return HttpResponse(
json_content,
content_type='application/json',
status=200
)

Django-Weasyprint image issue

As it says in the docs page, I defined a img tag in my html file as follows:
<img src='{% static 'image.png' %}'/>
This url exists in the server and I even made a different view with a http response and the image is displayed just fine. Here is the code for both views:
The pdf-weasyprint view:
def card_view(request):
template = loader.get_template('card.html')
context = {'sample': None
}
html = template.render(RequestContext(request, context))
response = HttpResponse(mimetype='application/pdf')
HTML(string=html).write_pdf(response)
return response
The html view:
def card_view2(request):
context = {'sample': None,
}
return render_to_response('card.html', context,
context_instance=RequestContext(request))
I thought the default url fetcher was supposed to find and render the image (it's a png - so no format issue should be involved)
Any ideas? Any help would be appreciated!!
What exactly is the issue? Do you get anything in the logs? (You may need to configure logging if your server does not log stderr.) What does the generated HTML look like?
I’d really need answers to the above to confirm, but my guess is that the image’s URL is relative, but with HTML(string=...) WeasyPrint has no idea of what is the base URL. Try something like this. (I’m not sure of the Django details.)
HTML(string=html, base_url=request.build_absolute_uri()).write_pdf(response)
This will make a real HTTP request on your app, which may deadlock on a single-threaded server. (I think the development server defaults to a single thread.)
To avoid that and the cost of going through the network, you may want to look into writing a custom "URL fetcher". It could be anywhere from specialized to just this one image, to a full Django equivalent of Flask-WeasyPrint.
Here it is a URL fetcher which reads (image) files locally, without performing an HTTP request:
from weasyprint import HTML, CSS, default_url_fetcher
import mimetypes
def weasyprint_local_fetcher(url):
if url.startswith('local://'):
filepath = url[8:]
with open(filepath, 'rb') as f:
file_data = f.read()
return {
'string': file_data,
'mime_type': mimetypes.guess_type(filepath)[0],
}
return default_url_fetcher(url)
In order to use it, use the local:// scheme in your URLs, for example:
<img src="local://myapp/static/images/image.svg" />
Then, pass the fetcher to the HTML __init__ method:
html = HTML(
string=html_string,
url_fetcher=weasyprint_local_fetcher,
)

json? in Django URL regex

This question might reveal a gaping hole in my knowledge of json queries, but I'm trying to get json data to display on a view with the following URL.
http://localhost:8000/structures/hydrants/json?id=%3D2/
Here's my URL regex:
url(r'^hydrants/json\\?id=(?P<hydrant_id>\d+)/$', views.hydrant_json, name='hydrant_json'),
and the view:
def hydrant_json(request, hydrant_id):
hydrant = get_object_or_404(Hydrant, pk=hydrant_id)
data = [hydrant.json()]
return HttpResponse(json.dumps(data), content_type='application/json')
Obviously, the question mark is throwing it off, because if I make the regex
url(r'^hydrants/json/id=(?P<hydrant_id>\d+)/$', views.hydrant_json, name='hydrant_json'),
then the following URL will work:
http://localhost:8000/structures/hydrants/json/id%3D2/
Thanks in advance!
If you want to send the data as GET parameters, you can simply do:
url(r'^hydrants/json/$', views.hydrant_json, name='hydrant_json'),
url(r'^hydrants/json/(?P<hydrant_id>\d+)/$', views.hydrant_json, name='hydrant_json_with_key'),
and views:
def hydrant_json(request, hydrant_id=None):
if not hydrant_id:
hydrant_id = request.GET.get('id')
if not hydrant_id: #if hydrant_id is not received for some reason, throw 404.
raise Http404
hydrant = get_object_or_404(Hydrant, pk=hydrant_id)
data = [hydrant.json()]
return HttpResponse(json.dumps(data), content_type='application/json')
Here, you are defining flexible ways of sending hydrant_id into the view.
By default, for a GET request, request.GET would have all the get parameters - example: ?id=123
Also, if you want to send hydrant_id as a part of the URL, You can just do
http://localhost:8000/structures/hydrants/json/302/
Please note, 3D2 would never get matched as a URL in the regex because your URL is looking for \d+ which is digits only.

Django: creating/modifying the request object

I'm trying to build an URL-alias app which allows the user create aliases for existing url in his website.
I'm trying to do this via middleware, where the request.META['PATH_INFO'] is checked against database records of aliases:
try:
src: request.META['PATH_INFO']
alias = Alias.objects.get(src=src)
view = get_view_for_this_path(request)
return view(request)
except Alias.DoesNotExist:
pass
return None
However, for this to work correctly it is of life-importance that (at least) the PATH_INFO is changed to the destination path.
Now there are some snippets which allow the developer to create testing request objects (http://djangosnippets.org/snippets/963/, http://djangosnippets.org/snippets/2231/), but these state that they are intended for testing purposes.
Of course, it could be that these snippets are fit for usage in a live enviroment, but my knowledge about Django request processing is too undeveloped to assess this.
Instead of the approach you're taking, have you considered the Redirects app?
It won't invisibly alias the path /foo/ to return the view bar(), but it will redirect /foo/ to /bar/
(posted as answer because comments do not seem to support linebreaks or other markup)
Thank for the advice, I have the same feeling regarding modifying request attributes. There must be a reason that the Django manual states that they should be considered read only.
I came up with this middleware:
def process_request(self, request):
try:
obj = A.objects.get(src=request.path_info.rstrip('/')) #The alias record.
view, args, kwargs = resolve_to_func(obj.dst + '/') #Modified http://djangosnippets.org/snippets/2262/
request.path = request.path.replace(request.path_info, obj.dst)
request.path_info = obj.dst
request.META['PATH_INFO'] = obj.dst
request.META['ROUTED_FROM'] = obj.src
request.is_routed = True
return view(request, *args, **kwargs)
except A.DoesNotExist: #No alias for this path
request.is_routed = False
except TypeError: #View does not exist.
pass
return None
But, considering the objections against modifying the requests' attributes, wouldn't it be a better solution to just skip that part, and only add the is_routed and ROUTED_TO (instead of routed from) parts?
Code that relies on the original path could then use that key from META.
Doing this using URLConfs is not possible, because this aliasing is aimed at enabling the end-user to configure his own URLs, with the assumption that the end-user has no access to the codebase or does not know how to write his own URLConf.
Though it would be possible to write a function that converts a user-readable-editable file (XML for example) to valid Django urls, it feels that using database records allows a more dynamic generation of aliases (other objects defining their own aliases).
Sorry to necro-post, but I just found this thread while searching for answers. My solution seems simpler. Maybe a) I'm depending on newer django features or b) I'm missing a pitfall.
I encountered this because there is a bot named "Mediapartners-Google" which is asking for pages with url parameters still encoded as from a naive scrape (or double-encoded depending on how you look at it.) i.e. I have 404s in my log from it that look like:
1.2.3.4 - - [12/Nov/2012:21:23:11 -0800] "GET /article/my-slug-name%3Fpage%3D2 HTTP/1.1" 1209 404 "-" "Mediapartners-Google
Normally I'd just ignore a broken bot, but this one I want to appease because it ought to better target our ads (It's google adsense's bot) resulting in better revenue - if it can see our content. Rumor is it doesn't follow redirects so I wanted to find a solution similar to the original Q. I do not want regular clients accessing pages by these broken urls, so I detect the user-agent. Other applications probably won't do that.
I agree a redirect would normally be the right answer.
My (complete?) solution:
from django.http import QueryDict
from django.core.urlresolvers import NoReverseMatch, resolve
class MediapartnersPatch(object):
def process_request(self, request):
# short-circuit asap
if request.META['HTTP_USER_AGENT'] != 'Mediapartners-Google':
return None
idx = request.path.find('?')
if idx == -1:
return None
oldpath = request.path
newpath = oldpath[0:idx]
try:
url = resolve(newpath)
except NoReverseMatch:
return None
request.path = newpath
request.GET = QueryDict(oldpath[idx+1:])
response = url.func(request, *url.args, **url.kwargs)
response['Link'] = '<%s>; rel="canonical"' % (oldpath,)
return response

Capturing URL parameters in request.GET

I am currently defining regular expressions in order to capture parameters in a URL, as described in the tutorial. How do I access parameters from the URL as part the HttpRequest object?
My HttpRequest.GET currently returns an empty QueryDict object.
I'd like to learn how to do this without a library, so I can get to know Django better.
When a URL is like domain/search/?q=haha, you would use request.GET.get('q', '').
q is the parameter you want, and '' is the default value if q isn't found.
However, if you are instead just configuring your URLconf**, then your captures from the regex are passed to the function as arguments (or named arguments).
Such as:
(r'^user/(?P<username>\w{0,50})/$', views.profile_page,),
Then in your views.py you would have
def profile_page(request, username):
# Rest of the method
To clarify camflan's explanation, let's suppose you have
the rule url(regex=r'^user/(?P<username>\w{1,50})/$', view='views.profile_page')
an incoming request for http://domain/user/thaiyoshi/?message=Hi
The URL dispatcher rule will catch parts of the URL path (here "user/thaiyoshi/") and pass them to the view function along with the request object.
The query string (here message=Hi) is parsed and parameters are stored as a QueryDict in request.GET. No further matching or processing for HTTP GET parameters is done.
This view function would use both parts extracted from the URL path and a query parameter:
def profile_page(request, username=None):
user = User.objects.get(username=username)
message = request.GET.get('message')
As a side note, you'll find the request method (in this case "GET", and for submitted forms usually "POST") in request.method. In some cases, it's useful to check that it matches what you're expecting.
Update: When deciding whether to use the URL path or the query parameters for passing information, the following may help:
use the URL path for uniquely identifying resources, e.g. /blog/post/15/ (not /blog/posts/?id=15)
use query parameters for changing the way the resource is displayed, e.g. /blog/post/15/?show_comments=1 or /blog/posts/2008/?sort_by=date&direction=desc
to make human-friendly URLs, avoid using ID numbers and use e.g. dates, categories, and/or slugs: /blog/post/2008/09/30/django-urls/
Using GET
request.GET["id"]
Using POST
request.POST["id"]
Someone would wonder how to set path in file urls.py, such as
domain/search/?q=CA
so that we could invoke query.
The fact is that it is not necessary to set such a route in file urls.py. You need to set just the route in urls.py:
urlpatterns = [
path('domain/search/', views.CityListView.as_view()),
]
And when you input http://servername:port/domain/search/?q=CA. The query part '?q=CA' will be automatically reserved in the hash table which you can reference though
request.GET.get('q', None).
Here is an example (file views.py)
class CityListView(generics.ListAPIView):
serializer_class = CityNameSerializer
def get_queryset(self):
if self.request.method == 'GET':
queryset = City.objects.all()
state_name = self.request.GET.get('q', None)
if state_name is not None:
queryset = queryset.filter(state__name=state_name)
return queryset
In addition, when you write query string in the URL:
http://servername:port/domain/search/?q=CA
Do not wrap query string in quotes. For example,
http://servername:port/domain/search/?q="CA"
def some_view(request, *args, **kwargs):
if kwargs.get('q', None):
# Do something here ..
For situations where you only have the request object you can use request.parser_context['kwargs']['your_param']
You have two common ways to do that in case your URL looks like that:
https://domain/method/?a=x&b=y
Version 1:
If a specific key is mandatory you can use:
key_a = request.GET['a']
This will return a value of a if the key exists and an exception if not.
Version 2:
If your keys are optional:
request.GET.get('a')
You can try that without any argument and this will not crash.
So you can wrap it with try: except: and return HttpResponseBadRequest() in example.
This is a simple way to make your code less complex, without using special exceptions handling.
I would like to share a tip that may save you some time.
If you plan to use something like this in your urls.py file:
url(r'^(?P<username>\w+)/$', views.profile_page,),
Which basically means www.example.com/<username>. Be sure to place it at the end of your URL entries, because otherwise, it is prone to cause conflicts with the URL entries that follow below, i.e. accessing one of them will give you the nice error: User matching query does not exist.
I've just experienced it myself; hope it helps!
These queries are currently done in two ways. If you want to access the query parameters (GET) you can query the following:
http://myserver:port/resource/?status=1
request.query_params.get('status', None) => 1
If you want to access the parameters passed by POST, you need to access this way:
request.data.get('role', None)
Accessing the dictionary (QueryDict) with 'get()', you can set a default value. In the cases above, if 'status' or 'role' are not informed, the values ​​are None.
If you don't know the name of params and want to work with them all, you can use request.GET.keys() or dict(request.GET) functions
This is not exactly what you asked for, but this snippet is helpful for managing query_strings in templates.
If you only have access to the view object, then you can get the parameters defined in the URL path this way:
view.kwargs.get('url_param')
If you only have access to the request object, use the following:
request.resolver_match.kwargs.get('url_param')
Tested on Django 3.
views.py
from rest_framework.response import Response
def update_product(request, pk):
return Response({"pk":pk})
pk means primary_key.
urls.py
from products.views import update_product
from django.urls import path
urlpatterns = [
...,
path('update/products/<int:pk>', update_product)
]
You might as well check request.META dictionary to access many useful things like
PATH_INFO, QUERY_STRING
# for example
request.META['QUERY_STRING']
# or to avoid any exceptions provide a fallback
request.META.get('QUERY_STRING', False)
you said that it returns empty query dict
I think you need to tune your url to accept required or optional args or kwargs
Django got you all the power you need with regrex like:
url(r'^project_config/(?P<product>\w+)/$', views.foo),
more about this at django-optional-url-parameters
This is another alternate solution that can be implemented:
In the URL configuration:
urlpatterns = [path('runreport/<str:queryparams>', views.get)]
In the views:
list2 = queryparams.split("&")
url parameters may be captured by request.query_params
It seems more recommended to use request.query_params. For example,
When a URL is like domain/search/?q=haha, you would use request.query_params.get('q', None)
https://www.django-rest-framework.org/api-guide/requests/
"request.query_params is a more correctly named synonym for request.GET.
For clarity inside your code, we recommend using request.query_params instead of the Django's standard request.GET. Doing so will help keep your codebase more correct and obvious - any HTTP method type may include query parameters, not just GET requests."