1
0
Эх сурвалжийг харах

feat: 重构configure模型

SongZihuan 3 жил өмнө
parent
commit
7c4c7753c5

+ 8 - 8
aliyun/__init__.py

@@ -12,10 +12,10 @@ class Aliyun:
         self.auth = oss2.Auth(key, secret)
         self.bucket = oss2.Bucket(self.auth, endpoint, name)
         self.logger = logging.getLogger("main.aliyun")
-        self.logger.setLevel(conf["log-level"])
-        if conf["log-home"] is not None:
+        self.logger.setLevel(conf["LOG_LEVEL"])
+        if len(conf["LOG_HOME"]) > 0:
             handle = logging.handlers.TimedRotatingFileHandler(
-                os.path.join(conf["log-home"], f"aliyun-{os.getpid()}-{key}.log"))
+                os.path.join(conf["LOG_HOME"], f"aliyun-{os.getpid()}-{key}.log"))
             handle.setFormatter(logging.Formatter(conf["log-format"]))
             self.logger.addHandler(handle)
 
@@ -32,10 +32,10 @@ class Aliyun:
         return url
 
 
-if conf["aliyun"]:
-    aliyun = Aliyun(conf["aliyun-key"],
-                    conf["aliyun-secret"],
-                    conf["aliyun-bucket-endpoint"],
-                    conf["aliyun-bucket-name"])
+if conf["USE_ALIYUN"]:
+    aliyun = Aliyun(conf["ALIYUN_KET"],
+                    conf["ALIYUN_SECRET"],
+                    conf["ALIYUN_BUCKET_ENDPOINT"],
+                    conf["ALIYUN_BUCKET_NAME"])
 else:
     aliyun = None

+ 10 - 14
app/app.py

@@ -25,6 +25,7 @@ from .about_me import about_me
 class HBlogFlask(Flask):
     def __init__(self, import_name: str, *args, **kwargs):
         super(HBlogFlask, self).__init__(import_name, *args, **kwargs)
+        self.update_configure()
 
         self.register_blueprint(index, url_prefix="/")
         self.register_blueprint(archive, url_prefix="/archive")
@@ -39,29 +40,21 @@ class HBlogFlask(Flask):
         self.login_manager.anonymous_user = AnonymousUser  # 设置未登录的匿名对象
         self.login_manager.login_view = "auth.login_page"
 
-        self.config["SECRET_KEY"] = conf['secret-key']
-        self.config["MAIL_SERVER"] = conf['email_server']
-        self.config["MAIL_PORT"] = conf['email_port']
-        self.config["MAIL_USE_TLS"] = conf['email_tls']
-        self.config["MAIL_USE_SSL"] = conf['email_ssl']
-        self.config["MAIL_USERNAME"] = conf['email_name']
-        self.config["MAIL_PASSWORD"] = conf['email_passwd']
-
         self.mail = Mail(self)
         self.pagedown = PageDown()
         self.pagedown.init_app(self)
 
         self.logger.removeHandler(default_handler)
-        self.logger.setLevel(conf["log-level"])
+        self.logger.setLevel(conf["LOG_LEVEL"])
         self.logger.propagate = False
-        if conf["log-home"] is not None:
+        if len(conf["LOG_HOME"]) > 0:
             handle = logging.handlers.TimedRotatingFileHandler(
-                os.path.join(conf["log-home"], f"flask-{os.getpid()}.log"))
-            handle.setFormatter(logging.Formatter(conf["log-format"]))
+                os.path.join(conf["LOG_HOME"], f"flask-{os.getpid()}.log"))
+            handle.setFormatter(logging.Formatter(conf["LOG_FORMAT"]))
             self.logger.addHandler(handle)
-        if conf["log-stderr"]:
+        if conf["LOG_STDERR"]:
             handle = logging.StreamHandler(sys.stderr)
-            handle.setFormatter(logging.Formatter(conf["log-format"]))
+            handle.setFormatter(logging.Formatter(conf["LOG_FORMAT"]))
             self.logger.addHandler(handle)
 
         @self.login_manager.user_loader
@@ -75,6 +68,9 @@ class HBlogFlask(Flask):
                  f"\treturn render_template('error.html', error_code='{i}', error_info=e)", func)
             self.errorhandler(i)(func[f"error_{i}"])
 
+    def update_configure(self):
+        self.config.update(conf)
+
     @staticmethod
     def get_max_page(count: int, count_page: int):
         return (count // count_page) + (0 if count % count_page == 0 else 1)

+ 3 - 3
app/index.py

@@ -33,7 +33,7 @@ def inject_base():
 
 @index.app_context_processor
 def inject_base():
-    return {"blog_name": conf['blog-name'],
+    return {"blog_name": conf['BLOG_NAME'],
             "top_nav": ["", "", "", "", "", ""],
-            "blog_describe": conf['blog-describe'],
-            "conf": conf}
+            "blog_describe": conf['BLOG_DESCRIBE'],
+            "conf": conf}

+ 48 - 76
configure/__init__.py

@@ -2,85 +2,57 @@ import json
 import logging
 import os
 
-conf = dict()
+conf = {
+    "SECRET_KEY": "HBlog-R-Salt",
+    "BLOG_NAME": "HBlog",
+    "BLOG_DESCRIBE": "Huan Blog.",
+    "FOOT": "Power by HBlog",
+    "ABOUT_ME_NAME": "",
+    "ABOUT_ME_DESCRIBE": "",
+    "INTRODUCTION": "",
+    "INTRODUCTION_LINK": "",
+    "MYSQL_URL": "localhost",
+    "MYSQL_NAME": "local",
+    "MYSQL_PASSWD": "123456",
+    "MYSQL_PORT": 3306,
+    "MAIL_SERVER": "",
+    "MAIL_PORT": "",
+    "MAIL_TLS": False,
+    "MAIL_SSL": False,
+    "MAIL_PASSWD": "",
+    "MAIL_PREFIX": "",
+    "MAIL_SENDER": "",
+    "USE_ALIYUN": False,
+    "ALIYUN_KET": "",
+    "ALIYUN_SECRET": "",
+    "ALIYUN_BUCKET_ENDPOINT": "",
+    "ALIYUN_BUCKET_NAME": "",
+    "LOG_HOME": "",
+    "LOG_FORMAT": "[%(levelname)s]:%(name)s:%(asctime)s "
+                  "(%(filename)s:%(lineno)d %(funcName)s) "
+                  "%(process)d %(thread)d "
+                  "%(message)s",
+    "LOG_LEVEL": logging.INFO,
+    "LOG_STDERR": True,
+}
 
 
 def configure(conf_file: str, encoding="utf-8"):
     """ 运行配置程序, 该函数需要在其他模块被执行前调用 """
     with open(conf_file, mode="r", encoding=encoding) as f:
         json_str = f.read()
-        _conf: dict = json.loads(json_str)
-
-    _mysql = _conf["mysql"]
-    conf["mysql_url"] = str(_mysql["url"])
-    conf["mysql_name"] = str(_mysql["name"])
-    conf["mysql_passwd"] = str(_mysql["passwd"])
-    conf["mysql_port"] = int(_mysql.get("port", 3306))
-
-    _email = _conf["email"]
-    conf["email_server"] = str(_email["server"])
-    conf["email_port"] = int(_email["port"])
-    conf["email_tls"] = bool(_email.get("tls", False))
-    conf["email_ssl"] = bool(_email.get("ssl", False))
-    conf["email_name"] = str(_email["name"])
-    conf["email_passwd"] = str(_email["passwd"])
-    conf["email_prefix"] = str(_email.get("prefix", "[HBlog]"))
-    conf["email_sender"] = str(_email["sender"])
-
-    conf["secret-key"] = str(_conf.get("secret-key", "HBlog-R-Salt"))
-    conf["server-name"] = _conf.get("server-name")
-
-    introduce = _conf["info"]["introduce"]
-    introduce_list = []
-    for i in introduce:
-        describe: str = introduce[i]
-        describe = " ".join([f"<p>{i}</p>" for i in describe.split('\n')])
-        introduce_list.append((i, describe))
-
-    conf["describe-link"] = _conf["info"]["link"]
-    conf["describe-info"] = introduce_list
-
-    conf["blog-name"] = _conf["info"]["blog-name"]
-    conf["blog-describe"] = _conf["info"]["blog-describe"]
-
-    conf["about-me-name"] = _conf["info"]["about-me"]["name"]
-    conf["about-me-describe"] = _conf["info"]["about-me"]["describe"]
-
-    conf["about-me-project"] = _conf["info"]["project"]
-    conf["about-me-skill"] = _conf["info"]["skill"]
-    conf["about-me-read"] = _conf["info"]["read"]
-
-    conf["foot-info"] = f'{_conf["info"]["foot-info"]} Power by HBlog'
-
-    aliyun = _conf.get("aliyun")
-    if aliyun is None:
-        conf["aliyun"] = False
-    else:
-        conf["aliyun"] = True
-        conf["aliyun-key"] = aliyun["Key"]
-        conf["aliyun-secret"] = aliyun["Secret"]
-        conf["aliyun-bucket-endpoint"] = aliyun["Bucket-Endpoint"]
-        conf["aliyun-bucket-name"] = aliyun["Bucket-Name"]
-
-    log = _conf.get("log")
-    if log is None:
-        conf["log-home"] = None
-        conf["log-format"] = ("[%(levelname)s]:%(name)s:%(asctime)s "
-                              "(%(filename)s:%(lineno)d %(funcName)s) "
-                              "%(process)d %(thread)d "
-                              "%(message)s")
-        conf["log-level"] = logging.INFO
-        conf["log-stderr"] = False
-    else:
-        conf["log-home"] = log.get("home")
-        if conf["log-home"]:
-            os.makedirs(conf["log-home"], exist_ok=True)
-        conf["log-level"] = {"debug": logging.DEBUG,
-                             "info": logging.INFO,
-                             "warning": logging.WARNING,
-                             "error": logging.ERROR}.get(log.get("level", "info"))
-        conf["log-format"] = log.get("format", ("[%(levelname)s]:%(name)s:%(asctime)s "
-                                                "(%(filename)s:%(lineno)d %(funcName)s) "
-                                                "%(process)d %(thread)d "
-                                                "%(message)s"))
-        conf["log-stderr"] = log.get("stderr", False)
+        conf.update(json.loads(json_str))
+
+        if type(conf["LOG_LEVEL"]) is str:
+            conf["LOG_LEVEL"] = {"debug": logging.DEBUG,
+                                 "info": logging.INFO,
+                                 "warning": logging.WARNING,
+                                 "error": logging.ERROR}.get(conf["LOG_LEVEL"])
+
+        introduce = conf["INTRODUCE"]
+        introduce_list = []
+        for i in introduce:
+            describe: str = introduce[i]
+            describe = " ".join([f"<p>{i}</p>" for i in describe.split('\n')])
+            introduce_list.append((i, describe))
+        conf["INTRODUCE"] = introduce_list

+ 0 - 3
main.py

@@ -16,9 +16,6 @@ from waitress import serve
 
 app = HBlogFlask(__name__)
 
-if conf["server-name"] is not None:
-    app.config['SERVER_NAME'] = conf["server-name"]
-
 if __name__ == '__main__':
     logging.info("Server start on 127.0.0.1:8080")
     serve(app, host='0.0.0.0', port="8080")

+ 2 - 2
object/user.py

@@ -108,12 +108,12 @@ class User(UserMixin):
 
     @staticmethod
     def creat_token(email: str, passwd_hash: str):
-        s = Serializer(conf["secret-key"])
+        s = Serializer(conf["SECRET_KEY"])
         return s.dumps({"email": email, "passwd_hash": passwd_hash})
 
     @staticmethod
     def load_token(token: str):
-        s = Serializer(conf["secret-key"])
+        s = Serializer(conf["SECRET_KEY"])
         try:
             token = s.loads(token, max_age=3600)
             return token['email'], token['passwd_hash']

+ 2 - 2
send_email/__init__.py

@@ -5,8 +5,8 @@ from configure import conf
 
 def send_msg(title: str, mail: Mail, to, template, **kwargs):
     """ 邮件发送 """
-    sender = f"HBlog Admin <{conf['email_sender']}>"
-    message = Message(conf['email_prefix'] + title, sender=sender, recipients=[to])
+    sender = f"HBlog Admin <{conf['MAIL_SENDER']}>"
+    message = Message(conf['MAIL_PREFIX'] + title, sender=sender, recipients=[to])
     message.body = render_template("email-msg/" + template + ".txt", **kwargs)
     message.html = render_template("email-msg/" + template + ".html", **kwargs)
     mail.send(message)

+ 1 - 1
sql/__init__.py

@@ -3,4 +3,4 @@ from configure import conf
 
 
 DB = MysqlDB
-db = DB(host=conf["mysql_url"], name=conf["mysql_name"], passwd=conf["mysql_passwd"], port=conf["mysql_port"])
+db = DB(host=conf["MYSQL_URL"], name=conf["MYSQL_NAME"], passwd=conf["MYSQL_PASSWD"], port=conf["MYSQL_PORT"])

+ 4 - 4
sql/base.py

@@ -34,11 +34,11 @@ class Database(metaclass=abc.ABCMeta):
         else:
             self._port = int(port)
         self.logger = logging.getLogger("main.database")
-        self.logger.setLevel(conf["log-level"])
-        if conf["log-home"] is not None:
+        self.logger.setLevel(conf["LOG_LEVEL"])
+        if len(conf["LOG_HOME"]) > 0:
             handle = logging.handlers.TimedRotatingFileHandler(
-                os.path.join(conf["log-home"], f"mysql-{os.getpid()}-{name}@{host}.log"))
-            handle.setFormatter(logging.Formatter(conf["log-format"]))
+                os.path.join(conf["LOG_HOME"], f"mysql-{os.getpid()}-{name}@{host}.log"))
+            handle.setFormatter(logging.Formatter(conf["LOG_FORMAT"]))
             self.logger.addHandler(handle)
 
     @abc.abstractmethod

+ 4 - 4
templates/about_me/about_me.html

@@ -14,13 +14,13 @@
             <div class="card mr-lg-2 mb-3">
                 <div class="card-header"> 关于我 </div>
                 <div class="card-body">
-                    <h4 class="card-title"> {{ conf['about-me-name'] }} </h4>
+                    <h4 class="card-title"> {{ conf['ABOUT_ME_NAME'] }} </h4>
                     <h5 class="card-subtitle"> 博主 </h5>
-                    <p class="card-text"> {{ conf['about-me-describe'] }} </p>
+                    <p class="card-text"> {{ conf['ABOUT_ME_DESCRIBE'] }} </p>
 
 
-                    {% for link in conf['describe-link'] %}
-                        <a class="card-link" href="{{ conf['describe-link'][link] }}"> {{ link }} </a>
+                    {% for link in conf['DESCRIBE_LINK'] %}
+                        <a class="card-link" href="{{ conf['DESCRIBE_LINK'][link] }}"> {{ link }} </a>
                     {% endfor %}
                 </div>
             </div>

+ 1 - 1
templates/base.html

@@ -96,7 +96,7 @@
 {% block footer %}
     <footer id="foot">
         <hr>
-        {{ conf['foot-info'] }}
+        {{ conf['FOOT'] }}
     </footer>
     <script>
         let context = document.getElementById('context')

+ 3 - 3
templates/index/index.html

@@ -12,13 +12,13 @@
         <div class="row">
             <article class="col-12">
                 <div class="introduce mr-lg-2 ml-lg-2">
-                    {% for info in conf['describe-info'] %}
+                    {% for info in conf['INTRODUCE'] %}
                         <h2> {{ info[0] }} </h2>
                         {{ info[1] | safe }}
                     {% endfor %}
 
-                    {% for link in conf['describe-link'] %}
-                        <a class="btn btn-info mb-2" href="{{ conf['describe-link'][link] }}"> {{ link }} </a>
+                    {% for link in conf['INTRODUCE_LINK'] %}
+                        <a class="btn btn-info mb-2" href="{{ conf['INTRODUCE_LINK'][link] }}"> {{ link }} </a>
                     {% endfor %}
                 </div>
             </article>