开发者

How to make a python regex?

I am working on a loginMiddleware class for Django. This middleware class must send a user to the login page when it's not logedin. But there are a few exceptions.

Because i run the build-in django server i had to make a media url. But know is de problem that when the login page loads a javascript file, the javascript file is the loginpage, because the user isn't logedin. Because of that reason i made a statement:

from django.http import HttpResponseRedirect
from django.conf import settings
import re
class loginMiddelware:
    def process_request(self,request):
        if request.path != settings.LOGIN_PATH and request.user.is_anonymous():
            if request.path.find('media') <= 0:
 开发者_Python百科               return HttpResponseRedirect(settings.LOGIN_PATH)
            else:
                return None

I mean the line with: if request.path.find('media') <= 0:. It works, but i don't find this a good method. I think that i must use a regex for that. So i looked to the re.match function, and tried different thinks, but nothing worked. I want a regex what allows only al urls beginning with /media/ and ending with one of the next extentions: js, css, png, gif or jpg.

How is this posible?

Thanx!

Tom


Sure:

DIRECT_ACCESS = re.compile(r'^/media/.*\.(js|css|png|gif|jpg)$')

...

if DIRECT_ACCESS.match(url):
    ...

Hint: If you want to make sure your regexp works, write a couple of unit tests that execute it. That way, you won't get any nasty surprises.


You don't need a regex:

if request.path.startswith('/path/to/your/media'):
    #do something

should do the trick. You are complaining about the fact, that if the request path contains:

/protected/secure/media/bla

that your implentation will let the user through.

So using a absolute path with the string method startswith is sufficient for your problem.


Take a look at Matt Grayson's Require Login Middleware. It lets you define a bunch of URLs that do not require logging in using a custom LOGIN_REQUIRED_URLS_EXCEPTIONS setting.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜