Browse Source

fix import bug

fanch 1 year ago
parent
commit
59691ce486

+ 1 - 1
setup.py

@@ -24,7 +24,7 @@ def get_files(path):
 
 setup(
     name="pytemplate",
-    version="0.1.2",
+    version="0.1.3",
     description="A short description of the project.",
     author="François GAUTRAIS",
     author_email="Your email",

+ 33 - 0
src/pytemplate/resources/django/_init_template.py

@@ -0,0 +1,33 @@
+import requests
+from pathlib import Path
+import os
+
+projet = os.environ["PYTEMPLATE_PROJET"]
+module = os.environ["PYTEMPLATE_MODULE"]
+
+
+static_dir = Path(__file__).parent / "src" / module / "frontend" / "static"
+js_vendor = static_dir / "js" / "vendor"
+css_vendor = static_dir / "css" / "vendor"
+font_vendor = static_dir / "css" / "vendor" / "fonts"
+
+files = [
+    ("https://code.jquery.com/jquery-latest.min.js", js_vendor / "jquery.js"),
+    ("https://cdn.jsdelivr.net/npm/bootstrap@latest/dist/js/bootstrap.bundle.min.js", js_vendor / "bootstrap.js"),
+    ("https://cdn.jsdelivr.net/npm/bootstrap@latest/dist/css/bootstrap.min.css", css_vendor / "bootstrap.css"),
+    ("https://cdn.jsdelivr.net/npm/bootstrap-icons@1.5.0/font/bootstrap-icons.css", css_vendor / "bootstrap-icons.css"),
+    ("https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.1/font/fonts/bootstrap-icons.woff2", font_vendor / "bootstrap-icons.woff2"),
+    ("https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.1/font/fonts/bootstrap-icons.woff", font_vendor / "bootstrap-icons.woff"),
+]
+
+for url, file in files:
+    file.parent.mkdir(exist_ok=True, parents=True)
+    print(f"{url} -> {file}")
+    req = requests.get(url)
+    if req.status_code != 200:
+        print(f"Erreur {url} -> {req.status_code}")
+    file.write_bytes(req.content)
+
+
+
+

+ 2 - 0
src/pytemplate/resources/django/src/%(module)s/app/views/main.py

@@ -0,0 +1,2 @@
+from djangotools.views import Route
+

+ 20 - 0
src/pytemplate/resources/django/src/%(module)s/frontend/templates/index.html

@@ -0,0 +1,20 @@
+<!DOCTYPE html>
+<html lang="fr">
+<head>
+    <meta charset="utf-8">
+    <meta name="viewport" content="width=device-width, initial-scale=1">
+    <title>Including Bootstrap Icons in HTML</title>
+    <!-- Bootstrap CSS -->
+    <link rel="stylesheet" href="static/css/vendor/bootstrap.css">
+    <!-- Bootstrap Font Icon CSS -->
+    <link rel="stylesheet" href="static/css/vendor/bootstrap-icons.css">
+</head>
+<body>
+    <h1><i class="bi-globe"></i> Hello, world!</h1>
+
+    <!-- Bootstrap JS Bundle with Popper -->
+
+    <script src="static/js/vendor/jquery.js"></script>
+    <script src="static/js/vendor/bootstrap.js"></script>
+</body>
+</html>

+ 20 - 0
src/pytemplate/resources/django/src/%(module)s/frontend/templates/login.html

@@ -0,0 +1,20 @@
+<!DOCTYPE html>
+<html lang="fr">
+<head>
+    <meta charset="utf-8">
+    <meta name="viewport" content="width=device-width, initial-scale=1">
+    <title>Login</title>
+    <!-- Bootstrap CSS -->
+    <link rel="stylesheet" href="static/css/vendor/bootstrap.css">
+    <!-- Bootstrap Font Icon CSS -->
+    <link rel="stylesheet" href="static/css/vendor/bootstrap-icons.css">
+</head>
+<body>
+    <h1><i class="bi-globe"></i> Login</h1>
+
+    <!-- Bootstrap JS Bundle with Popper -->
+
+    <script src="static/js/vendor/jquery.js"></script>
+    <script src="static/js/vendor/bootstrap.js"></script>
+</body>
+</html>

+ 5 - 2
src/pytemplate/resources/django/src/%(module)s/settings/__init__.py

@@ -60,8 +60,11 @@ LOGIN_URL="login"
 LOGOUT_URL="disconnect"
 AUTH_URL="auth"
 CONTEXT_URL="context/<str:name>"
-LOGIN_TEMPLATE="login"
+LOGIN_TEMPLATE="login.html"
+LOGIN_CONTEXT="login"
 app_dir = BASE_DIR.parent.parent / "data"
-
+STATICFILES_DIRS = ["frontend/static"]
+TEMPLATES_DIR = ["frontend/templates"]
+ROOT_TEMPLATE="index.html"
 
 CONFIG = load_settings(globals())

+ 48 - 6
src/pytemplate/template.py

@@ -1,8 +1,12 @@
 import json
+import os
+import re
 import shutil
+import sys
 from collections import OrderedDict
 from pathlib import Path
 
+import importlib.util
 from pytemplate.resources import get_resources_path
 
 
@@ -34,20 +38,39 @@ class Template:
             for file in curr.iterdir():
                 if file.is_file() and file.name != ".template_keys":
                     files.append(file)
-                elif not file.name == ".idea":
+                elif file.name not in  (".idea", "__pycache__"):
                     files.append(file)
                     queue.append(file)
         return files
 
+    def _find_names(self):
+        src = self.root / "src"
+        setup = self.root / "setup.py"
+        if src.is_dir():
+            dirs = [x.name for x in src.iterdir() if x.is_dir() and "." not in x.name]
+            if len(dirs) == 1:
+                self.variables["module"] = (self.variables["module"][0], dirs[0])
+        if setup.is_file():
+            content = setup.read_text()
+            for match in re.compile(r"name\s*=[\"\'](\w+)[\"\']\s*[,)]").findall(content):
+                self.variables["name"] = (self.variables["name"][0], match)
+                break
+        return
+
+
+
 
     def _prompt(self, data):
         if not data: data = {}
         for name, (help, *args) in self.variables.items():
             if data.get(name) is not None: continue
             default_value = ""
+            default_value_str = ""
             if args:
-                default_value = f"[{args[0](data)}]"
-            ret = input(f"{help}{default_value}: ").split()
+                default_value = args[0](data) if callable(args[0]) else args[0]
+                default_value_str = f"[{default_value}]"
+
+            ret = input(f"{help}{default_value_str}: ").split()
             if ret: ret = ret[0]
             if default_value and not ret:
                 ret = default_value
@@ -62,7 +85,12 @@ class Template:
         return content
 
     def mk_template(self, name, data):
-        data = self._prompt(data)
+        self._find_names()
+        while True:
+            data = self._prompt(data)
+            if data["name"] != data["module"] and data["name_lower"] != data["module"]: break
+            print(f"Erreur le nom est ambigue avec le module, merci de recommencer")
+            data = {k: None for k in data}
         out_dir = get_resources_path(name)
         if out_dir.exists():
             shutil.rmtree(out_dir)
@@ -99,7 +127,6 @@ class Template:
             exit(-1)
 
         output.mkdir(exist_ok=True, parents=True)
-
         data = self._prompt(data)
 
         for file in self.list_files():
@@ -111,12 +138,27 @@ class Template:
                 continue
             try:
                 file_in = file.read_text() % data
-            except UnicodeDecodeError:
+            except Exception:
+                print(f"Attention: le fichier {file} a été simplement copié et non rendu")
                 shutil.copy(file, out_file)
                 continue
             file_in = file_in % data
             out_file.write_text(file_in)
+            self.execute_post_install(output, data)
+
+
+    def execute_post_install(self, output, data):
+        pyfile = output / "_init_template.py"
+        if not pyfile.is_file(): return
+        print("Execution du script d'installation")
+        os.environ["PYTEMPLATE_PROJET"] = data["name"]
+        os.environ["PYTEMPLATE_MODULE"] = data["module"]
 
+        spec = importlib.util.spec_from_file_location("_init_template", pyfile)
+        foo = importlib.util.module_from_spec(spec)
+        sys.modules["_init_template"] = foo
+        spec.loader.exec_module(foo)
 
+        pyfile.unlink()