简体   繁体   English

在Django Urls中将网址作为参数传递

[英]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: 我正在Django(2)项目中工作,我需要在Django URL中将URL作为参数传递,这是我尝试的方法:

urls.py: urls.py:

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

views.py: 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. 但这是行不通的,我通过邮递员传递了一个名称为address的参数,但是失败了。 It returns this error: 它返回此错误:

Not Found: /api/ [05/Sep/2018 15:28:06] "GET /api/ HTTP/1.1" 404 2085 找不到:/ 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. Django 2.0和更高版本现在使用path func构造函数来指定URL。 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

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). 为了避免与标准路径在应用程序中查看混淆,我不建议使用path转换器而不是str (前者可以匹配/ ,而后者不能匹配)。

You can get more help for transitioning from url to path with this article . 你可以得到更多的帮助,从过渡urlpath与此文章

Second step, get the encoded_url as an argument in the view. 第二步,在视图中获取encoded_url作为参数。 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). 您需要对其进行解码 :要在get url中传递一个url,请使用ASCII编码,该编码将某些保留字符替换为其他保留字符(例如,正斜杠)。

You can encode and decode urls easily with urllib (there are other modules as well). 您可以使用urllib轻松地对URL进行编码和解码(还有其他模块)。 For Python 3.7 syntax is as follows (docs here) 对于Python 3.7,语法如下(此处文档)

>>> 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='') (编辑:quote方法默认不转换正斜杠,为此您需要传递: quote(<str>, safe='')

So for example your GET call should look: /api/http%3A%2F%2Fwww.google.com . 因此,例如,您的GET调用应如下: /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 ). 但是,最好将URL作为get参数传递,并且只在路径中只关心aboubt的可读性(例如/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). 路径工程对于提高可读性很重要,并且通常不推荐使用通过引号引起来的URL(尽管完全有可能)。

Are you trying to pass the url https://i.imgur.com/TGJHFe1.jpg as a parameter from the django template to the view ? 您是否要尝试将url https://i.imgur.com/TGJHFe1.jpg作为参数从django模板传递给视图?

You could simple write in your app's url.py: 您可以简单地在应用程序的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 . Django 2.0提供了将路径参数转换为适当类型的Path Converters ,其中还包括urls转换器,请参阅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, '/'. 因此, path转换器将匹配任何非空字符串,包括路径分隔符“ /”。 This allows you to match against a complete URL path rather than just a segment of a URL path as with str. 这样一来,您就可以匹配完整的URL路径,而不是像str那样仅匹配URL路径的一部分。

Then in the view, we can simply get our URL values from kwargs like this: 然后在视图中,我们可以简单地从kwargs获取URL值,如下所示:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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