简体   繁体   中英

Django url with IP address

I want to make this URL pattern works : http://myapp.com/api/ipaddress/username where IP address is an IPv4 and username is the account of a django user.

What is the good regex format to do this at url.py ?

urlpatterns = [
    url(r'^$', view_api, name='api'),
    url(r'^(?P<ip>[0-9.])/(?P<username>\w+)/$', view_ip_check_user, name='ip_check_user'),
]

For anyone who wants to know :

I tried this and it works :

urlpatterns = [
    url(r'^$', view_api, name='api'),
    url(r'^(?P<ip>(?:(?:0|1[\d]{0,2}|2(?:[0-4]\d?|5[0-5]?|[6-9])?|[3-9]\d?)\.){3}(?:0|1[\d]{0,2}|2(?:[0-4]\d?|5[0-5]?|[6-9])?|[3-9]\d?))/(?P<pseudo>\w+)/$', view_ip_check_user, name='ip_check_user'),
]

This regex only accept valid IPv4 address. So for example wrong address like 172.16.1.256 is not deserved by Django.

So it's perfect.

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