Explorar el Código

feat: 基础架构

SongZihuan hace 2 años
commit
6366765e33
Se han modificado 6 ficheros con 242 adiciones y 0 borrados
  1. 143 0
      .gitignore
  2. 2 0
      README.md
  3. 46 0
      app/__init__.py
  4. 34 0
      configure/__init__.py
  5. 17 0
      main.py
  6. BIN
      requirements.txt

+ 143 - 0
.gitignore

@@ -0,0 +1,143 @@
+.idea
+
+# Byte-compiled / optimized / DLL files
+__pycache__/
+*.py[cod]
+*$py.class
+
+# C extensions
+*.so
+
+# Distribution / packaging
+.Python
+build/
+develop-eggs/
+dist/
+downloads/
+eggs/
+.eggs/
+lib/
+lib64/
+parts/
+sdist/
+var/
+wheels/
+share/python-wheels/
+*.egg-info/
+.installed.cfg
+*.egg
+MANIFEST
+
+# PyInstaller
+#  Usually these files are written by a python script from a template
+#  before PyInstaller builds the exe, so as to inject date/other infos into it.
+*.manifest
+*.spec
+
+# Installer logs
+pip-log.txt
+pip-delete-this-directory.txt
+
+# Unit test / coverage reports
+htmlcov/
+.tox/
+.nox/
+.coverage
+.coverage.*
+.cache
+nosetests.xml
+coverage.xml
+*.cover
+*.py,cover
+.hypothesis/
+.pytest_cache/
+cover/
+
+# Translations
+*.mo
+*.pot
+
+# Django stuff:
+*.log
+log
+local_settings.py
+db.sqlite3
+db.sqlite3-journal
+
+# Flask stuff:
+instance/
+.webassets-cache
+
+# Scrapy stuff:
+.scrapy
+
+# Sphinx documentation
+docs/_build/
+
+# PyBuilder
+.pybuilder/
+target/
+
+# Jupyter Notebook
+.ipynb_checkpoints
+
+# IPython
+proarchive_default/
+ipython_config.py
+
+# pyenv
+#   For a library or package, you might want to ignore these files since the code is
+#   intended to run in multiple environments; otherwise, check them in:
+# .python-version
+
+# pipenv
+#   According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
+#   However, in case of collaboration, if having platform-specific dependencies or dependencies
+#   having no cross-platform support, pipenv may install dependencies that don't work, or not
+#   install all needed dependencies.
+#Pipfile.lock
+
+# PEP 582; used by e.g. github.com/David-OConnor/pyflow
+__pypackages__/
+
+# Celery stuff
+celerybeat-schedule
+celerybeat.pid
+
+# SageMath parsed files
+*.sage.py
+
+# Environments
+.env
+.venv
+env/
+venv/
+ENV/
+env.bak/
+venv.bak/
+
+# Spyder project settings
+.spyderproject
+.spyproject
+
+# Rope project settings
+.ropeproject
+
+# mkdocs documentation
+/site
+
+# mypy
+.mypy_cache/
+.dmypy.json
+dmypy.json
+
+# Pyre type checker
+.pyre/
+
+# pytype static type analyzer
+.pytype/
+
+# Cython debug symbols
+cython_debug/
+
+etc

+ 2 - 0
README.md

@@ -0,0 +1,2 @@
+# HTalk
+基于Python-Flask的沟通交流平台。

+ 46 - 0
app/__init__.py

@@ -0,0 +1,46 @@
+from flask import Flask
+from flask.logging import default_handler
+import logging
+import logging.handlers
+import os
+import sys
+
+from configure import conf
+
+
+if conf["DEBUG_PROFILE"]:
+    from werkzeug.middleware.profiler import ProfilerMiddleware
+
+
+class HTalkFlask(Flask):
+    def __init__(self, name):
+        super(HTalkFlask, self).__init__(name)
+        self.update_configure()
+        self.profile_setting()
+        self.logging_setting()
+
+
+    def profile_setting(self):
+        if conf["DEBUG_PROFILE"]:
+            self.wsgi_app = ProfilerMiddleware(self.wsgi_app, sort_by=("cumtime",))
+
+
+    def logging_setting(self):
+        self.logger.removeHandler(default_handler)
+        self.logger.setLevel(conf["LOG_LEVEL"])
+        self.logger.propagate = False  # 不传递给更高级别的处理器处理日志
+
+        if len(conf["LOG_HOME"]) > 0:
+            handle = logging.handlers.TimedRotatingFileHandler(
+                os.path.join(conf["LOG_HOME"], f"flask.log"), backupCount=10)
+            handle.setFormatter(logging.Formatter(conf["LOG_FORMAT"]))
+            self.logger.addHandler(handle)
+
+        if conf["LOG_STDERR"]:
+            handle = logging.StreamHandler(sys.stderr)
+            handle.setFormatter(logging.Formatter(conf["LOG_FORMAT"]))
+            self.logger.addHandler(handle)
+
+    def update_configure(self):
+        """ 更新配置 """
+        self.config.update(conf)

+ 34 - 0
configure/__init__.py

@@ -0,0 +1,34 @@
+import json
+import logging
+import os
+from typing import Dict
+
+
+conf: Dict[str, any] = {
+    "DEBUG_PROFILE": False,
+    "LOG_STDERR": True,
+    "LOG_LEVEL": "info",
+    "LOG_HOME": "",
+    "LOG_FORMAT": "[%(levelname)s]:%(name)s:%(asctime)s "
+                  "(%(filename)s:%(lineno)d %(funcName)s) "
+                  "%(process)d %(thread)d "
+                  "%(message)s",
+
+    "SECRET_KEY": "11111111",
+    "SQL_URL": "mysql://root:12345678@localhost:3306/htalk",
+}
+
+
+def configure(conf_file: str, encoding="utf-8"):
+    """ 运行配置程序, 该函数需要在其他模块被执行前调用 """
+    with open(conf_file, mode="r", encoding=encoding) as f:
+        json_str = f.read()
+        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"])
+    if len(conf["LOG_HOME"]) > 0:
+        os.makedirs(conf["LOG_HOME"], exist_ok=True)

+ 17 - 0
main.py

@@ -0,0 +1,17 @@
+from configure import configure
+
+import os
+import logging
+
+env_dict = os.environ
+hblog_conf = env_dict.get("hblog_conf")
+if hblog_conf is None:
+    logging.info("Configure file ./etc/conf.json")
+    configure("./etc/conf.json")
+else:
+    logging.info(f"Configure file {hblog_conf}")
+    configure(hblog_conf)
+
+
+from app import HTalkFlask
+app = HTalkFlask(__name__)

BIN
requirements.txt