Effective Django QuerySet Regular Expression

I have a model like this:

class CampaignPermittedURL(models.Model):
    hostname = models.CharField(max_length=255)
    path = models.CharField(max_length=255,blank=True)

Often, I will be given a URL that I can use to enter the host name and path. I would like the end user to be able to enter the host name (yahoo.com) and possibly the path (weddings).

I would like to find when the url does not match this host / path combination this way:

  • success: www.yahoo.com/weddings/newyork
  • success: yahoo.com/weddings
  • failure: cnn.com
  • crash: cnn.com/weddings

I think the best way to do this is:

url = urlsplit("http://www.yahoo.com/weddings/newyork")
### split hostname on . and path on /
matches = CampaignPermittedURL.objects.filter(hostname__regex=r'(com|yahoo.com|www.yahoo.com)'), \
    path__regex=r'(weddings|weddings/newyork)')

- ? PostgreSQL Django Full , , , . , ?

, URL-, , CampaignPermittedURL . / , , .

back-end (Sphinx?), Django .

+3
2

ORM, . , Django:

        # >>> url.hostname.split(".")
    # ["bakery", "yahoo", "com"]
    host_list = url.hostname.split(".")

    # Build regex like r"^$|^[.]?com$|^[.]?yahoo\.com$|^[.]?baking[.]yahoo[.]com$"
    # Remember that
    # >>> r'\'
    # '\\'
    host_list.reverse()

    # append_str2 might not be necessary
    append_str = r""
    append_str2 = r""
    host_regex = r"^$"
    for host in host_list:
        append_str = r"[.]" + host + append_str
        append_str2 = append_str[3:]
        host_regex = host_regex + r"|^[.]?" + append_str2 + r"$"
    # If nothing is in the filter at all, bypass the filter.
    if CampaignRequiredURL.objects.filter():
        if not CampaignRequiredURL.objects.filter(hostname__iregex=host_regex):
            #Do something based on a hit.
+3

Regex: ^(http\:\/\/)?(www\.)?yahoo\.com(\/.+)?$

http://www.yahoo.com/weddings/newyork pass
www.yahoo.com/weddings/foo            pass
www.yahoo.com/weddings                pass
www.yahoo.com                         pass

yahoo.com/weddings/foo                pass
yahoo.com/weddings                    pass
yahoo.com                             pass

cnn.com/weddings/foo                  fail
cnn.com/weddings                      fail
cnn.com                               fail
+3

Source: https://habr.com/ru/post/1719557/


All Articles