简体   繁体   中英

Pass a URL as parameter in Django Urls

I'm working on a Django(2) project in which I need to pass an URL as a parameter in a Django URL, Here's what i have tried:

urls.py:

urlpatterns = [
path('admin/', admin.site.urls),
url(r'^api/(?P<address>.*)/$', PerformImgSegmentation.as_view()),
]

views.py:

class PerformImgSegmentation(generics.ListAPIView):
    def get(self, request, *args, **kwargs):
        img_url = self.kwargs.get('address')
        print(img_url)
        print('get request')
    return 'Done'

But it doesn't work, I have passed an argument with the name as address via postman, but it failed. It returns this error:

Not Found: /api/ [05/Sep/2018 15:28:06] "GET /api/ HTTP/1.1" 404 2085

Django 2.0 and later use now path func constructors to specify URLs. I'm not sure if there's still backwards compatibility; you can try that with a simple example. However if you are starting to write an app you should use path :

path('api/<str:encoded_url>/', view_action)

To avoid confusion with a stantard path to view in your app, I do not recommend using the path converter instead of the str (the former lets you match / , while the other does not).

You can get more help for transitioning from url to path with this article .

Second step, get the encoded_url as an argument in the view. You need to decode it : to pass a url inside the get url, you use ASCII encoding that substitutes certain reserved characters for others (for example, the forward slash).

You can encode and decode urls easily with urllib (there are other modules as well). For Python 3.7 syntax is as follows (docs here)

>>> urllib.parse.quote("http://www.google.com")
'http%3A//www.google.com'
>>> urllib.parse.unquote('http%3A//www.google.com')
'http://www.google.com'

Remember: if you pass the url without quoting it won't match: you are not accepting matches for slashes with that path expression. (Edit: quote method default does not convert forward slashes, for that you need to pass: quote(<str>, safe='')

So for example your GET call should look: /api/http%3A%2F%2Fwww.google.com . However it's better if you pass the URL as a get parameter and in the paths you only care aboubt readability (for example /api/name_to_my_method?url=http%3A%2F%2Fwww.google.com ). Path engineering is important for readability and passing a quoted URL through is usually not ebst practice (though perfectly possible).

Are you trying to pass the url https://i.imgur.com/TGJHFe1.jpg as a parameter from the django template to the view ?

You could simple write in your app's url.py:

path(api/<path:the_url_you_want_to_pass>', PerformImgSegmentation.as_view())

Please have a look at this article .

Django 2.0 is providing the Path Converters to convert the path parameters into appropriate types, which also includes a converter for urls , take a look at the docs .

So, your URLs can be like this:

path('api/<path:encoded_url>/', PerformImgSegmentation.as_view()),

So, the path converter will Matches any non-empty string, including the path separator, '/'. This allows you to match against a complete URL path rather than just a segment of a URL path as with str.

Then in the view, we can simply get our URL values from kwargs like this:

img_url = self.kwargs.get('encoded_url')
print(img_url)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM