允许网址作为参数

时间:2014-04-25 03:43:15

标签: python django django-urls

我想在我的数据库中保存URL,为此我实现了以下调用:

http://myapp.com/save/url_to_be_saved

参数url_to_be_saved可以是任何网址,如:

http://myapp.com/save/http://stackoverflow.com/questions/ask
http://myapp.com/save/http://getbootstrap.com/css/#forms

如何让Django接受这些模式?我目前的myapp.urls如下:

urlpatterns = patterns(
    '',
    url(r'^$', views.index, name='index'),
    url(r'^a/signup/$', views.signup, name='signup'),
    url(r'^a/login/$', views.login, name='login'),
    url(r'^a/logout/$', views.logout, name='logout'),
    url(r'^a/search/(?P<term>.{1,50})/$', views.search, name='search'),
    url(r'^save/(?P<url>([^a/]){1,50})/$', views.save_url, name='save_url'),
)

1 个答案:

答案 0 :(得分:3)

我允许在url中传递任何内容,然后我会在视图中validate the url

url(r'^save/(?P<url>.*)/$', views.save_url, name='save_url'),

然后,视图需要验证url:

from django.core.validators import URLValidator
from django.core.exceptions import ValidationError

def save_url(request, url):
    url_validator = URLValidator(verify_exists=False)
    try:
        url_validator(url)
    except ValidationError:
        print 'Not a valid URL'

在验证之前,您可能还需要unquote网址。