Mahmudm commited on
Commit
82a2c4e
·
verified ·
1 Parent(s): db84eaa

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +36 -16
app.py CHANGED
@@ -2,22 +2,42 @@
2
  import os
3
  import tempfile
4
 
5
- # Writable cache directory
6
- CACHE_ROOT = os.path.join(tempfile.gettempdir(), "my_app_cache")
7
- os.makedirs(CACHE_ROOT, exist_ok=True)
8
-
9
- # Matplotlib cache directory (to avoid /.config write)
10
- os.environ["MPLCONFIGDIR"] = os.path.join(CACHE_ROOT, "matplotlib")
11
- os.makedirs(os.environ["MPLCONFIGDIR"], exist_ok=True)
12
-
13
- # Cartopy cache directory (avoid /.local)
14
- os.environ["CARTOPY_USER_BACKGROUNDS"] = os.path.join(CACHE_ROOT, "cartopy")
15
- os.environ["CARTOPY_CACHE_DIR"] = os.path.join(CACHE_ROOT, "cartopy")
16
- os.makedirs(os.environ["CARTOPY_CACHE_DIR"], exist_ok=True)
17
-
18
- # Optional: contextily tile cache
19
- os.environ["XDG_CACHE_HOME"] = os.path.join(CACHE_ROOT, "contextily")
20
- os.makedirs(os.environ["XDG_CACHE_HOME"], exist_ok=True)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
21
 
22
 
23
 
 
2
  import os
3
  import tempfile
4
 
5
+ def get_writable_dir(name, subfolder=None):
6
+ """
7
+ Tries multiple locations and returns the first writable path.
8
+ If all fail, returns None.
9
+ """
10
+ candidates = [
11
+ os.path.join("/code", name),
12
+ os.path.join(tempfile.gettempdir(), name)
13
+ ]
14
+ for path in candidates:
15
+ if subfolder:
16
+ path = os.path.join(path, subfolder)
17
+ try:
18
+ os.makedirs(path, exist_ok=True)
19
+ return path
20
+ except PermissionError:
21
+ continue
22
+ return None
23
+
24
+ # Try to assign a safe cache root
25
+ CACHE_ROOT = get_writable_dir("my_app_cache") or tempfile.gettempdir()
26
+
27
+ # Apply safe directories for matplotlib and others
28
+ matplotlib_dir = get_writable_dir("my_app_cache", "matplotlib")
29
+ if matplotlib_dir:
30
+ os.environ["MPLCONFIGDIR"] = matplotlib_dir
31
+
32
+ cartopy_dir = get_writable_dir("my_app_cache", "cartopy")
33
+ if cartopy_dir:
34
+ os.environ["CARTOPY_CACHE_DIR"] = cartopy_dir
35
+ os.environ["CARTOPY_USER_BACKGROUNDS"] = cartopy_dir
36
+
37
+ xdg_cache = get_writable_dir("my_app_cache", "contextily")
38
+ if xdg_cache:
39
+ os.environ["XDG_CACHE_HOME"] = xdg_cache
40
+
41
 
42
 
43