I use django as a backend. I have big project and there are many views(ViewSets from django-rest-framework, views and functions). And I use React as a front and and how can I get function or class which will be called from the url. For example I have the url:
api/v2/users/322/send_letters/1232/
from this url I want to know which class or function will be called.
I think you're looking for resolve() that can be used for resolving URL paths to the corresponding view functions.
Be careful when using resolve(path) the function raises a Resolver404 if the URL does not resolve (Doesn't exist in your all URLs patterns)
>>> from django.core.urlresolvers import resolve
>>> path = 'api/v2/users/322/send_letters/1232/'
>>> match = resolve(path)
>>> match.url_name
>>> 'url_name'
>>> match.view_name
>>> match.func # func, that you are looking for
match.view_name will return the name of the view that matches the URL, including the namespace if there is one.
Related
I am doing a django project, and is very confused about reverse, reverse_lazy and redirect.
Can redirect function redirect with parameters? Or should I change method to reverse whenever I want to post parameters?
Can redirect function redirect with parameters?
Yes. Imagine that you have a url pattern with:
path('foo/<str:bar>/<id:pk>/', name='some_path')
you can redirect to that path with:
return redirect('some_path', bar='value-for-bar', pk=1425)
is very confused about reverse, reverse_lazy and redirect.
reverse and reverse_lazy determine the path for a given view name. That path is a string, not a HTTP response, you can not return such string as a result for a view.
The redirect(…) function [Django-doc] will call reverse(…) function [Django-doc] internally and wrap the result in a HttpResponseRedirect [Django-doc] or HttpResponsePermanentRedirect [Django-doc].
It thus combines two layers with each other: the urls layer to calculate the path, and the view layer to construct a HTTP response, that is why it is defined in the django.shortcuts module [Django-doc].
I am learing Django on Django at a glance | Django documentation | Django
When introducing URLconf It reads:
To design URLs for an app, you create a Python module called a URLconf. A table of contents for your app, it contains a simple mapping between URL patterns and Python callback functions.
Nevertheless, a callback function is not called.
mysite/news/urls.py
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^articles/([0-9]{4})/$', views.year_archive),
]
print('callback funtion:',views.year_archive)
output:
callback function: <function views.year_archive at 0x1039611e0>
So it a funtion object which is not called.
I suppose it should be views.year_archive() to enable it to call.
If not called,how does it work? I assume there a decorator to process it in parent class.
I check the source codes of urldjango.conf.urls | Django documentation | Django
The key statement is:
elif callable(view):
return RegexURLPattern(regex, view, kwargs, name)
I dig on to explore LocaleRegexProvider, RegexURLPattern django.urls.resolvers | Django documentation | Django.
No appopriate codes were found to call the callback function views.year_archive
What's the mechanism of its working?
Django automatically calls the callback view function whenever a request is made to the given url pattern.
To understand how it works, look at this example:
>>> def a():
print("Called function a")
>>> def b():
print("Called function b")
>>> def c(callback):
# call the callback function like this
callback()
>>> c(a)
Called function a
>>> c(b)
Called function b
Basically, this is how Django's url function works.
i'm new to django and i'd like to know how the url maps work in detail.
from django.conf.urls import url
from polls import views
urlpatterns =[
url(r'^$',views.index,name='index')
]
the url function takes 3 parameters, could you explain how they work and what functionalies they have.
I've searched for this, but no detailed information are available for an absolute beginner
The Django URL dispatcher contains urlpatterns which is a Python list of url() instances.
The url(regex, view, kwargs=None, name=None) function can take 4 arguments:
regex: Regular expression, pattern matching the url.
view: View name, path, function or the result of as_view() for class-based views. It can also be an include().
kwargs: Allows you to pass additional arguments to the view function or method.
name: Naming URL patterns.
I just learnt that with Rails is possible to simulate HTTP requests in the console with few lines of code.
Check out: http://37signals.com/svn/posts/3176-three-quick-rails-console-tips (section "Dive into your app").
Is there a similar way to do that with Django? Would be handy.
You can use RequestFactory, which allows
inserting a user into the request
inserting an uploaded file into the request
sending specific parameters to the view
and does not require the additional dependency of using requests.
Note that you have to specify both the URL and the view class, so it takes an extra line of code than using requests.
from django.test import RequestFactory
request_factory = RequestFactory()
my_url = '/my_full/url/here' # Replace with your URL -- or use reverse
my_request = request_factory.get(my_url)
response = MyClasBasedView.as_view()(my_request) # Replace with your view
response.render()
print(response)
To set the user of the request, do something like my_request.user = User.objects.get(id=123) before getting the response.
To send parameters to a class-based view, do something like response = MyClasBasedView.as_view()(my_request, parameter_1, parameter_2)
Extended Example
Here's an example of using RequestFactory with these things in combination
HTTP POST (to url url, functional view view, and a data dictionary post_data)
uploading a single file (path file_path, name file_name, and form field value file_key)
assigning a user to the request (user)
passing on kwargs dictionary from the url (url_kwargs)
SimpleUploadedFile helps format the file in a way that is valid for forms.
from django.core.files.uploadedfile import SimpleUploadedFile
from django.test import RequestFactory
request = RequestFactory().post(url, post_data)
with open(file_path, 'rb') as file_ptr:
request.FILES[file_key] = SimpleUploadedFile(file_name, file_ptr.read())
file_ptr.seek(0) # resets the file pointer after the read
if user:
request.user = user
response = view(request, **url_kwargs)
Using RequestFactory from a Python shell
RequestFactory names your server "testserver" by default, which can cause a problem if you're not using it inside test code. You'll see an error like:
DisallowedHost: Invalid HTTP_HOST header: 'testserver'. You may need to add 'testserver' to ALLOWED_HOSTS.
This workaround from #boatcoder's comment shows how to override the default server name to "localhost":
request_factory = RequestFactory(**{"SERVER_NAME": "localhost", "wsgi.url_scheme":"https"}).
How I simulate requests from the python command line is:
Use the excellent requests library
Use the django reverse function
A simple way of simulating requests is:
>>> from django.urls import reverse
>>> import requests
>>> r = requests.get(reverse('app.views.your_view'))
>>> r.text
(prints output)
>>> r.status_code
200
Update: be sure to launch the django shell (via manage.py shell), not a classic python shell.
Update 2: For Django <1.10, change the first line to
from django.core.urlresolvers import reverse
(See tldr; down)
Its an old question,
but just adding an answer, in case someone maybe interested.
Though this might not be the best(or lets say Django) way of doing things.
but you can try doing this way.
Inside your django shell
>>> import requests
>>> r = requests.get('your_full_url_here')
Explanation:
I omitted the reverse(),
explanation being, since reverse() more or less,
finds the url associated to a views.py function,
you may omit the reverse() if you wish to, and put the whole url instead.
For example, if you have a friends app in your django project,
and you want to see the list_all() (in views.py) function in the friends app,
then you may do this.
TLDR;
>>> import requests
>>> url = 'http://localhost:8000/friends/list_all'
>>> r = requests.get(url)
In the Django testing documentation they promise that you can "Test that the correct view is executed for a given URL."
However I didn't find any possibility how to test which view was executed. I would expect that in the Response class but there's nothing about the executed view.
Thanks in advance.
You can extract the view function name thusly
from django.test.client import Client
c = Client()
response = c.get('/')
from django.core.urlresolvers import resolve
resolve(response.request["PATH_INFO"])[0].func_name
Dave's answer involves a HTTP request each time you're testing a url, which can be slow. If you just want to know what view a url resolves to, you can do that without using Client:
>>> from django.core.urlresolvers import get_resolver
>>> from myapp.views import func_to_test
>>> resolver = get_resolver(None)
>>> match = resolver.resolve('/some/path/')
>>> if match.func is func_to_test:
>>> print "correct function for resolution!"
Ryan Wilcox's post on route testing goes into more detail and provides techniques for making it even easier to test them.