1 | #!/usr/bin/env python |
---|
2 | # -*- coding: utf-8 -*- |
---|
3 | |
---|
4 | """ |
---|
5 | | This file is part of the web2py Web Framework |
---|
6 | | Copyrighted by Massimo Di Pierro <mdipierro@cs.depaul.edu> |
---|
7 | | License: LGPLv3 (http://www.gnu.org/licenses/lgpl.html) |
---|
8 | |
---|
9 | Generates names for cache and session files |
---|
10 | -------------------------------------------- |
---|
11 | """ |
---|
12 | import os |
---|
13 | from gluon._compat import builtin |
---|
14 | |
---|
15 | def generate(filename, depth=2, base=512): |
---|
16 | if os.path.sep in filename: |
---|
17 | path, filename = os.path.split(filename) |
---|
18 | else: |
---|
19 | path = None |
---|
20 | dummyhash = sum(ord(c) * 256 ** (i % 4) for i, c in enumerate(filename)) % base ** depth |
---|
21 | folders = [] |
---|
22 | for level in range(depth - 1, -1, -1): |
---|
23 | code, dummyhash = divmod(dummyhash, base ** level) |
---|
24 | folders.append("%03x" % code) |
---|
25 | folders.append(filename) |
---|
26 | if path: |
---|
27 | folders.insert(0, path) |
---|
28 | return os.path.join(*folders) |
---|
29 | |
---|
30 | |
---|
31 | def exists(filename, path=None): |
---|
32 | if os.path.exists(filename): |
---|
33 | return True |
---|
34 | if path is None: |
---|
35 | path, filename = os.path.split(filename) |
---|
36 | fullfilename = os.path.join(path, generate(filename)) |
---|
37 | if os.path.exists(fullfilename): |
---|
38 | return True |
---|
39 | return False |
---|
40 | |
---|
41 | |
---|
42 | def remove(filename, path=None): |
---|
43 | if os.path.exists(filename): |
---|
44 | return os.unlink(filename) |
---|
45 | if path is None: |
---|
46 | path, filename = os.path.split(filename) |
---|
47 | fullfilename = os.path.join(path, generate(filename)) |
---|
48 | if os.path.exists(fullfilename): |
---|
49 | return os.unlink(fullfilename) |
---|
50 | raise IOError |
---|
51 | |
---|
52 | |
---|
53 | def open(filename, mode="r", path=None): |
---|
54 | if not path: |
---|
55 | path, filename = os.path.split(filename) |
---|
56 | fullfilename = None |
---|
57 | if not mode.startswith('w'): |
---|
58 | fullfilename = os.path.join(path, filename) |
---|
59 | if not os.path.exists(fullfilename): |
---|
60 | fullfilename = None |
---|
61 | if not fullfilename: |
---|
62 | fullfilename = os.path.join(path, generate(filename)) |
---|
63 | if mode.startswith('w') and not os.path.exists(os.path.dirname(fullfilename)): |
---|
64 | os.makedirs(os.path.dirname(fullfilename)) |
---|
65 | return builtin.open(fullfilename, mode) |
---|