lesscode-flask 0.0.27__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (51) hide show
  1. lesscode_flask-0.0.27/PKG-INFO +127 -0
  2. lesscode_flask-0.0.27/README.md +92 -0
  3. lesscode_flask-0.0.27/lesscode_flask/__init__.py +1 -0
  4. lesscode_flask-0.0.27/lesscode_flask/app.py +156 -0
  5. lesscode_flask-0.0.27/lesscode_flask/db/__init__.py +60 -0
  6. lesscode_flask-0.0.27/lesscode_flask/db/datasource.py +27 -0
  7. lesscode_flask-0.0.27/lesscode_flask/db/executor.py +128 -0
  8. lesscode_flask-0.0.27/lesscode_flask/log/access_log_handler.py +62 -0
  9. lesscode_flask-0.0.27/lesscode_flask/model/access_log.py +26 -0
  10. lesscode_flask-0.0.27/lesscode_flask/model/auth_client.py +42 -0
  11. lesscode_flask-0.0.27/lesscode_flask/model/auth_permission.py +25 -0
  12. lesscode_flask-0.0.27/lesscode_flask/model/base_model.py +38 -0
  13. lesscode_flask-0.0.27/lesscode_flask/model/parameterized_query.py +210 -0
  14. lesscode_flask-0.0.27/lesscode_flask/model/response_result.py +60 -0
  15. lesscode_flask-0.0.27/lesscode_flask/model/user.py +118 -0
  16. lesscode_flask-0.0.27/lesscode_flask/service/access_log_service.py +8 -0
  17. lesscode_flask-0.0.27/lesscode_flask/service/auth_client_service.py +7 -0
  18. lesscode_flask-0.0.27/lesscode_flask/service/auth_permission_service.py +7 -0
  19. lesscode_flask-0.0.27/lesscode_flask/service/authentication_service.py +67 -0
  20. lesscode_flask-0.0.27/lesscode_flask/service/base_service.py +138 -0
  21. lesscode_flask-0.0.27/lesscode_flask/setting/__init__.py +122 -0
  22. lesscode_flask-0.0.27/lesscode_flask/setup/__init__.py +185 -0
  23. lesscode_flask-0.0.27/lesscode_flask/utils/__init__.py +1 -0
  24. lesscode_flask-0.0.27/lesscode_flask/utils/decorator/__init__.py +0 -0
  25. lesscode_flask-0.0.27/lesscode_flask/utils/decorator/cache.py +126 -0
  26. lesscode_flask-0.0.27/lesscode_flask/utils/decorator/swagger.py +19 -0
  27. lesscode_flask-0.0.27/lesscode_flask/utils/file/file_exporter.py +98 -0
  28. lesscode_flask-0.0.27/lesscode_flask/utils/helpers.py +139 -0
  29. lesscode_flask-0.0.27/lesscode_flask/utils/json/NotSortJSONProvider.py +9 -0
  30. lesscode_flask-0.0.27/lesscode_flask/utils/oss/__init__.py +0 -0
  31. lesscode_flask-0.0.27/lesscode_flask/utils/oss/ks3_oss.py +203 -0
  32. lesscode_flask-0.0.27/lesscode_flask/utils/redis/redis_helper.py +117 -0
  33. lesscode_flask-0.0.27/lesscode_flask/utils/request/request.py +96 -0
  34. lesscode_flask-0.0.27/lesscode_flask/utils/swagger/swagger_template.py +82 -0
  35. lesscode_flask-0.0.27/lesscode_flask/utils/swagger/swagger_util.py +172 -0
  36. lesscode_flask-0.0.27/lesscode_flask/wsgi.py +37 -0
  37. lesscode_flask-0.0.27/lesscode_flask.egg-info/PKG-INFO +127 -0
  38. lesscode_flask-0.0.27/lesscode_flask.egg-info/SOURCES.txt +49 -0
  39. lesscode_flask-0.0.27/lesscode_flask.egg-info/dependency_links.txt +1 -0
  40. lesscode_flask-0.0.27/lesscode_flask.egg-info/requires.txt +22 -0
  41. lesscode_flask-0.0.27/lesscode_flask.egg-info/top_level.txt +2 -0
  42. lesscode_flask-0.0.27/redash/query_runner/__init__.py +523 -0
  43. lesscode_flask-0.0.27/redash/query_runner/clickhouse.py +230 -0
  44. lesscode_flask-0.0.27/redash/query_runner/kingbase.py +228 -0
  45. lesscode_flask-0.0.27/redash/query_runner/mysql.py +309 -0
  46. lesscode_flask-0.0.27/redash/query_runner/pg.py +284 -0
  47. lesscode_flask-0.0.27/redash/settings/__init__.py +90 -0
  48. lesscode_flask-0.0.27/redash/settings/helpers.py +66 -0
  49. lesscode_flask-0.0.27/redash/utils/requests_session.py +18 -0
  50. lesscode_flask-0.0.27/setup.cfg +4 -0
  51. lesscode_flask-0.0.27/setup.py +58 -0
@@ -0,0 +1,127 @@
1
+ Metadata-Version: 2.1
2
+ Name: lesscode-flask
3
+ Version: 0.0.27
4
+ Summary: lesscode-flask 是基于flask的web开发脚手架项目,该项目初衷为简化开发过程,让研发人员更加关注业务。
5
+ Home-page: https://lesscode-flask
6
+ Author: Chao.yy
7
+ Author-email: yuyc@ishangqi.com
8
+ Platform: python
9
+ Classifier: Programming Language :: Python :: 3
10
+ Classifier: Operating System :: OS Independent
11
+ Requires-Python: >=3.9
12
+ Description-Content-Type: text/markdown
13
+ Requires-Dist: blinker==1.6.2
14
+ Requires-Dist: Flask==3.0.3
15
+ Requires-Dist: itsdangerous==2.2.0
16
+ Requires-Dist: Jinja2==3.1.4
17
+ Requires-Dist: MarkupSafe==2.1.3
18
+ Requires-Dist: Werkzeug==3.0.3
19
+ Requires-Dist: zipp==3.17.0
20
+ Requires-Dist: gunicorn==23.0.0
21
+ Requires-Dist: python-dateutil==2.9.0.post0
22
+ Requires-Dist: sqlparse==0.5.1
23
+ Requires-Dist: Flask-SQLAlchemy==3.1.1
24
+ Requires-Dist: sqlalchemy_utils==0.41.2
25
+ Requires-Dist: requests==2.32.3
26
+ Requires-Dist: advocate==1.0.0
27
+ Requires-Dist: rq==1.16.2
28
+ Requires-Dist: sshtunnel==0.4.0
29
+ Requires-Dist: funcy==2.0
30
+ Requires-Dist: pystache==0.6.5
31
+ Requires-Dist: flask-swagger-ui==4.11.1
32
+ Requires-Dist: lesscode-utils==0.0.61
33
+ Requires-Dist: Flask-Login==0.6.3
34
+ Requires-Dist: gevent==24.2.1
35
+
36
+ # lesscode-flask
37
+
38
+
39
+
40
+ ## Getting started
41
+
42
+ To make it easy for you to get started with GitLab, here's a list of recommended next steps.
43
+
44
+ Already a pro? Just edit this README.md and make it your own. Want to make it easy? [Use the template at the bottom](#editing-this-readme)!
45
+
46
+ ## Add your files
47
+
48
+ - [ ] [Create](https://docs.gitlab.com/ee/user/project/repository/web_editor.html#create-a-file) or [upload](https://docs.gitlab.com/ee/user/project/repository/web_editor.html#upload-a-file) files
49
+ - [ ] [Add files using the command line](https://docs.gitlab.com/ee/gitlab-basics/add-file.html#add-a-file-using-the-command-line) or push an existing Git repository with the following command:
50
+
51
+ ```
52
+ cd existing_repo
53
+ git remote add origin http://gitlab.chanyeos.com/backend/lesscode-flask.git
54
+ git branch -M main
55
+ git push -uf origin main
56
+ ```
57
+
58
+ ## Integrate with your tools
59
+
60
+ - [ ] [Set up project integrations](http://gitlab.chanyeos.com/backend/lesscode-flask/-/settings/integrations)
61
+
62
+ ## Collaborate with your team
63
+
64
+ - [ ] [Invite team members and collaborators](https://docs.gitlab.com/ee/user/project/members/)
65
+ - [ ] [Create a new merge request](https://docs.gitlab.com/ee/user/project/merge_requests/creating_merge_requests.html)
66
+ - [ ] [Automatically close issues from merge requests](https://docs.gitlab.com/ee/user/project/issues/managing_issues.html#closing-issues-automatically)
67
+ - [ ] [Enable merge request approvals](https://docs.gitlab.com/ee/user/project/merge_requests/approvals/)
68
+ - [ ] [Automatically merge when pipeline succeeds](https://docs.gitlab.com/ee/user/project/merge_requests/merge_when_pipeline_succeeds.html)
69
+
70
+ ## Test and Deploy
71
+
72
+ Use the built-in continuous integration in GitLab.
73
+
74
+ - [ ] [Get started with GitLab CI/CD](https://docs.gitlab.com/ee/ci/quick_start/index.html)
75
+ - [ ] [Analyze your code for known vulnerabilities with Static Application Security Testing(SAST)](https://docs.gitlab.com/ee/user/application_security/sast/)
76
+ - [ ] [Deploy to Kubernetes, Amazon EC2, or Amazon ECS using Auto Deploy](https://docs.gitlab.com/ee/topics/autodevops/requirements.html)
77
+ - [ ] [Use pull-based deployments for improved Kubernetes management](https://docs.gitlab.com/ee/user/clusters/agent/)
78
+ - [ ] [Set up protected environments](https://docs.gitlab.com/ee/ci/environments/protected_environments.html)
79
+
80
+ ***
81
+
82
+ # Editing this README
83
+
84
+ When you're ready to make this README your own, just edit this file and use the handy template below (or feel free to structure it however you want - this is just a starting point!). Thank you to [makeareadme.com](https://www.makeareadme.com/) for this template.
85
+
86
+ ## Suggestions for a good README
87
+ Every project is different, so consider which of these sections apply to yours. The sections used in the template are suggestions for most open source projects. Also keep in mind that while a README can be too long and detailed, too long is better than too short. If you think your README is too long, consider utilizing another form of documentation rather than cutting out information.
88
+
89
+ ## Name
90
+ Choose a self-explaining name for your project.
91
+
92
+ ## Description
93
+ Let people know what your project can do specifically. Provide context and add a link to any reference visitors might be unfamiliar with. A list of Features or a Background subsection can also be added here. If there are alternatives to your project, this is a good place to list differentiating factors.
94
+
95
+ ## Badges
96
+ On some READMEs, you may see small images that convey metadata, such as whether or not all the tests are passing for the project. You can use Shields to add some to your README. Many services also have instructions for adding a badge.
97
+
98
+ ## Visuals
99
+ Depending on what you are making, it can be a good idea to include screenshots or even a video (you'll frequently see GIFs rather than actual videos). Tools like ttygif can help, but check out Asciinema for a more sophisticated method.
100
+
101
+ ## Installation
102
+ Within a particular ecosystem, there may be a common way of installing things, such as using Yarn, NuGet, or Homebrew. However, consider the possibility that whoever is reading your README is a novice and would like more guidance. Listing specific steps helps remove ambiguity and gets people to using your project as quickly as possible. If it only runs in a specific context like a particular programming language version or operating system or has dependencies that have to be installed manually, also add a Requirements subsection.
103
+
104
+ ## Usage
105
+ Use examples liberally, and show the expected output if you can. It's helpful to have inline the smallest example of usage that you can demonstrate, while providing links to more sophisticated examples if they are too long to reasonably include in the README.
106
+
107
+ ## Support
108
+ Tell people where they can go to for help. It can be any combination of an issue tracker, a chat room, an email address, etc.
109
+
110
+ ## Roadmap
111
+ If you have ideas for releases in the future, it is a good idea to list them in the README.
112
+
113
+ ## Contributing
114
+ State if you are open to contributions and what your requirements are for accepting them.
115
+
116
+ For people who want to make changes to your project, it's helpful to have some documentation on how to get started. Perhaps there is a script that they should run or some environment variables that they need to set. Make these steps explicit. These instructions could also be useful to your future self.
117
+
118
+ You can also document commands to lint the code or run tests. These steps help to ensure high code quality and reduce the likelihood that the changes inadvertently break something. Having instructions for running tests is especially helpful if it requires external setup, such as starting a Selenium server for testing in a browser.
119
+
120
+ ## Authors and acknowledgment
121
+ Show your appreciation to those who have contributed to the project.
122
+
123
+ ## License
124
+ For open source projects, say how it is licensed.
125
+
126
+ ## Project status
127
+ If you have run out of energy or time for your project, put a note at the top of the README saying that development has slowed down or stopped completely. Someone may choose to fork your project or volunteer to step in as a maintainer or owner, allowing your project to keep going. You can also make an explicit request for maintainers.
@@ -0,0 +1,92 @@
1
+ # lesscode-flask
2
+
3
+
4
+
5
+ ## Getting started
6
+
7
+ To make it easy for you to get started with GitLab, here's a list of recommended next steps.
8
+
9
+ Already a pro? Just edit this README.md and make it your own. Want to make it easy? [Use the template at the bottom](#editing-this-readme)!
10
+
11
+ ## Add your files
12
+
13
+ - [ ] [Create](https://docs.gitlab.com/ee/user/project/repository/web_editor.html#create-a-file) or [upload](https://docs.gitlab.com/ee/user/project/repository/web_editor.html#upload-a-file) files
14
+ - [ ] [Add files using the command line](https://docs.gitlab.com/ee/gitlab-basics/add-file.html#add-a-file-using-the-command-line) or push an existing Git repository with the following command:
15
+
16
+ ```
17
+ cd existing_repo
18
+ git remote add origin http://gitlab.chanyeos.com/backend/lesscode-flask.git
19
+ git branch -M main
20
+ git push -uf origin main
21
+ ```
22
+
23
+ ## Integrate with your tools
24
+
25
+ - [ ] [Set up project integrations](http://gitlab.chanyeos.com/backend/lesscode-flask/-/settings/integrations)
26
+
27
+ ## Collaborate with your team
28
+
29
+ - [ ] [Invite team members and collaborators](https://docs.gitlab.com/ee/user/project/members/)
30
+ - [ ] [Create a new merge request](https://docs.gitlab.com/ee/user/project/merge_requests/creating_merge_requests.html)
31
+ - [ ] [Automatically close issues from merge requests](https://docs.gitlab.com/ee/user/project/issues/managing_issues.html#closing-issues-automatically)
32
+ - [ ] [Enable merge request approvals](https://docs.gitlab.com/ee/user/project/merge_requests/approvals/)
33
+ - [ ] [Automatically merge when pipeline succeeds](https://docs.gitlab.com/ee/user/project/merge_requests/merge_when_pipeline_succeeds.html)
34
+
35
+ ## Test and Deploy
36
+
37
+ Use the built-in continuous integration in GitLab.
38
+
39
+ - [ ] [Get started with GitLab CI/CD](https://docs.gitlab.com/ee/ci/quick_start/index.html)
40
+ - [ ] [Analyze your code for known vulnerabilities with Static Application Security Testing(SAST)](https://docs.gitlab.com/ee/user/application_security/sast/)
41
+ - [ ] [Deploy to Kubernetes, Amazon EC2, or Amazon ECS using Auto Deploy](https://docs.gitlab.com/ee/topics/autodevops/requirements.html)
42
+ - [ ] [Use pull-based deployments for improved Kubernetes management](https://docs.gitlab.com/ee/user/clusters/agent/)
43
+ - [ ] [Set up protected environments](https://docs.gitlab.com/ee/ci/environments/protected_environments.html)
44
+
45
+ ***
46
+
47
+ # Editing this README
48
+
49
+ When you're ready to make this README your own, just edit this file and use the handy template below (or feel free to structure it however you want - this is just a starting point!). Thank you to [makeareadme.com](https://www.makeareadme.com/) for this template.
50
+
51
+ ## Suggestions for a good README
52
+ Every project is different, so consider which of these sections apply to yours. The sections used in the template are suggestions for most open source projects. Also keep in mind that while a README can be too long and detailed, too long is better than too short. If you think your README is too long, consider utilizing another form of documentation rather than cutting out information.
53
+
54
+ ## Name
55
+ Choose a self-explaining name for your project.
56
+
57
+ ## Description
58
+ Let people know what your project can do specifically. Provide context and add a link to any reference visitors might be unfamiliar with. A list of Features or a Background subsection can also be added here. If there are alternatives to your project, this is a good place to list differentiating factors.
59
+
60
+ ## Badges
61
+ On some READMEs, you may see small images that convey metadata, such as whether or not all the tests are passing for the project. You can use Shields to add some to your README. Many services also have instructions for adding a badge.
62
+
63
+ ## Visuals
64
+ Depending on what you are making, it can be a good idea to include screenshots or even a video (you'll frequently see GIFs rather than actual videos). Tools like ttygif can help, but check out Asciinema for a more sophisticated method.
65
+
66
+ ## Installation
67
+ Within a particular ecosystem, there may be a common way of installing things, such as using Yarn, NuGet, or Homebrew. However, consider the possibility that whoever is reading your README is a novice and would like more guidance. Listing specific steps helps remove ambiguity and gets people to using your project as quickly as possible. If it only runs in a specific context like a particular programming language version or operating system or has dependencies that have to be installed manually, also add a Requirements subsection.
68
+
69
+ ## Usage
70
+ Use examples liberally, and show the expected output if you can. It's helpful to have inline the smallest example of usage that you can demonstrate, while providing links to more sophisticated examples if they are too long to reasonably include in the README.
71
+
72
+ ## Support
73
+ Tell people where they can go to for help. It can be any combination of an issue tracker, a chat room, an email address, etc.
74
+
75
+ ## Roadmap
76
+ If you have ideas for releases in the future, it is a good idea to list them in the README.
77
+
78
+ ## Contributing
79
+ State if you are open to contributions and what your requirements are for accepting them.
80
+
81
+ For people who want to make changes to your project, it's helpful to have some documentation on how to get started. Perhaps there is a script that they should run or some environment variables that they need to set. Make these steps explicit. These instructions could also be useful to your future self.
82
+
83
+ You can also document commands to lint the code or run tests. These steps help to ensure high code quality and reduce the likelihood that the changes inadvertently break something. Having instructions for running tests is especially helpful if it requires external setup, such as starting a Selenium server for testing in a browser.
84
+
85
+ ## Authors and acknowledgment
86
+ Show your appreciation to those who have contributed to the project.
87
+
88
+ ## License
89
+ For open source projects, say how it is licensed.
90
+
91
+ ## Project status
92
+ If you have run out of energy or time for your project, put a note at the top of the README saying that development has slowed down or stopped completely. Someone may choose to fork your project or volunteer to step in as a maintainer or owner, allowing your project to keep going. You can also make an explicit request for maintainers.
@@ -0,0 +1 @@
1
+ __version__ = '0.0.27'
@@ -0,0 +1,156 @@
1
+ import json
2
+ import logging
3
+ import os
4
+ import time
5
+ import traceback
6
+
7
+ from flask import Flask, typing as ft
8
+ import typing as t
9
+ from flask.globals import request_ctx, request
10
+ from flask_login import current_user
11
+ from werkzeug.middleware.proxy_fix import ProxyFix
12
+ from lesscode_flask.utils.helpers import inject_args, generate_uuid, app_config
13
+ from lesscode_flask.model.response_result import ResponseResult
14
+ from lesscode_flask.setup import setup_blueprint, setup_logging, setup_query_runner, setup_swagger, setup_sql_alchemy, \
15
+ setup_redis, setup_login_manager
16
+ from lesscode_flask.utils.json.NotSortJSONProvider import NotSortJSONProvider
17
+ from lesscode_flask.utils.redis.redis_helper import RedisHelper
18
+
19
+
20
+ class Lesscoder(Flask):
21
+ """A custom Flask app for lesscode-flask"""
22
+
23
+ def __init__(self, *args, **kwargs):
24
+ # kwargs.update(
25
+ # {
26
+ # "template_folder": settings.FLASK_TEMPLATE_PATH,
27
+ # "static_folder": settings.STATIC_ASSETS_PATH,
28
+ # "static_url_path": "/static",
29
+ # }
30
+ # )
31
+ super(Lesscoder, self).__init__(__name__, *args, **kwargs)
32
+ # Make sure we get the right referral address even behind proxies like nginx.
33
+ # 将self.wsgi_app设置为一个经过ProxyFix包装的应用程序。
34
+ # ProxyFix配置为信任代理服务器发来的X - Forwarded - For和X - Host头部信息,各信任一层(即数值1)。
35
+ # 这里的ProxyFix通常用于修复在反向代理环境下WSGI应用收到的客户端地址和主机头信息。
36
+ self.wsgi_app = ProxyFix(self.wsgi_app, x_for=1, x_host=1)
37
+ # # Configure Redash using our settings
38
+ setting_name = "setting.config_{}.Config".format(os.getenv("profile")) if os.getenv(
39
+ "profile") else "setting.config.Config"
40
+ self.config.from_object(setting_name)
41
+ self.register_error_handler(Exception, self.handle_exception)
42
+ # 请求开始时间存储的字典
43
+ # self.register_error_handler(code_or_exception, f)
44
+
45
+ def dispatch_request(self) -> ft.ResponseReturnValue:
46
+ """ 实现参数自动注入功能,对父级代码进行重写
47
+ """
48
+
49
+ # 此处开始 均为原代码直接拷贝
50
+ req = request_ctx.request
51
+ if req.routing_exception is not None:
52
+ self.raise_routing_exception(req)
53
+ rule: Rule = req.url_rule # type: ignore[assignment]
54
+ # if we provide automatic options for this URL and the
55
+ # request came with the OPTIONS method, reply automatically
56
+ if (
57
+ getattr(rule, "provide_automatic_options", False)
58
+ and req.method == "OPTIONS"
59
+ ):
60
+ return self.make_default_options_response()
61
+ # otherwise dispatch to the handler for that endpoint
62
+ view_args: dict[str, t.Any] = req.view_args # type:
63
+ func = self.view_functions[rule.endpoint]
64
+ # 到此结束 以下增加新实现
65
+ # 此处增加参数注入代码
66
+ params_dict = inject_args(req, func, view_args)
67
+ params_dict.update(view_args)
68
+ print("params_dict", params_dict)
69
+ # 调用处理函数执行请求处理
70
+ result = self.ensure_sync(func)(**params_dict)
71
+ # 获取不包装路径
72
+ NOT_RESPONSE_RESULT = self.config.get("NOT_RESPONSE_RESULT", [])
73
+ # 如果访问的路径以不包装路径开头,则不包装返回结果
74
+ for url in NOT_RESPONSE_RESULT:
75
+ if req.full_path.startswith(url):
76
+ return result
77
+ try:
78
+ # 判断返回结构是否是json,不是json则不包装
79
+ json.dumps(result)
80
+ return ResponseResult(data=result)
81
+ except:
82
+ return result
83
+
84
+ def setup(self):
85
+ setup_logging(self)
86
+ setup_blueprint(self)
87
+ setup_query_runner()
88
+ setup_swagger(self)
89
+ setup_sql_alchemy(self)
90
+ setup_redis(self)
91
+ setup_login_manager(self)
92
+
93
+ @staticmethod
94
+ def handle_exception(e):
95
+ traceback.print_exc() # 打印堆栈信息
96
+ # 统一异常处理
97
+ if hasattr(e, "get_response"):
98
+ response = e.get_response()
99
+ return ResponseResult.make_response(message=e.description, data=f"{e.code} {e.name}",
100
+ http_code=response.status_code, status_code="500")
101
+ else:
102
+ return ResponseResult.make_response(message=str(e), data=str(e), http_code=500, status_code="500")
103
+
104
+
105
+ # 请求开始时间的集合
106
+ request_start_time = {}
107
+
108
+
109
+ def create_app():
110
+ app = Lesscoder()
111
+ app.json = NotSortJSONProvider(app) # 设置自定义的 JSON provider
112
+ with app.app_context():
113
+ app.setup()
114
+
115
+ @app.before_request
116
+ def before_request():
117
+ # 生成请求标识
118
+ request_id = request.headers.get('Request-Id')
119
+ if request_id is None:
120
+ request_id = generate_uuid()
121
+ request.request_id = request_id
122
+ # 记录请求开始时间
123
+ request_start_time[request_id] = time.time()
124
+ # 获取当前请求的url
125
+ url = request.path
126
+ # 获取URL 对应的id 与访问权限
127
+ id, access = RedisHelper(app_config.get("REDIS_OAUTH_KEY", "redis")).sync_hmget(f"upms:url_info:{url}",
128
+ ["id", "access"])
129
+ if not id:
130
+ # 如果没有进行注册的url 默认需要登录权限
131
+ access = app_config.get("AUTH_DEFAULT_ACCESS", "0")
132
+ # '访问权限2:需要权限 1:需要登录 0:游客',
133
+ if str(access) == "1": # 需要登录
134
+ if current_user.is_anonymous_user:
135
+ # abort(403, "需要登录")
136
+ ResponseResult.fail("请登录后访问", status_code="403")
137
+ elif str(access) == "2": # 需要权限
138
+ if current_user.is_anonymous_user:
139
+ ResponseResult.fail("请登录后访问", status_code="403")
140
+ if not current_user.has_permission(id):
141
+ ResponseResult.fail("请获取授权后访问", status_code="403")
142
+
143
+ @app.after_request
144
+ def after_request(response):
145
+ # 每个请求后执行
146
+ request_id = request.request_id
147
+ response.headers['Request-Id'] = request.request_id
148
+ # 计算请求耗时
149
+ start_time = request_start_time.pop(request_id, None)
150
+ if start_time:
151
+ duration = time.time() - start_time
152
+ # 100 为自定义 'ACCESS' 的日志级别标识
153
+ logging.log(100, duration, {"request_id": request_id, "duration": duration})
154
+ return response
155
+
156
+ return app
@@ -0,0 +1,60 @@
1
+ import logging
2
+
3
+ from lesscode_flask.db.executor import QueryExecutor, QueryExecutionError
4
+ from lesscode_flask.model.parameterized_query import ParameterizedQuery
5
+
6
+
7
+ def execute_query(
8
+ query_text, parameters,
9
+ query_runner, should_apply_auto_limit=True
10
+ ):
11
+ """
12
+ 执行查询操作
13
+ :param query_text: 待执行语句
14
+ :param parameters: 查询参数数
15
+ :param query_runner: 查询执行器
16
+ :param should_apply_auto_limit:
17
+ :return:
18
+ """
19
+ try:
20
+ query = ParameterizedQuery(query_text)
21
+ if parameters is None:
22
+ parameters = {}
23
+ query.apply(parameters)
24
+ query_text = query_runner.apply_auto_limit(query.text, should_apply_auto_limit)
25
+ logging.info("query_text:{}".format(query_text))
26
+ return QueryExecutor(
27
+ query_text,
28
+ query_runner
29
+ ).run()
30
+ except QueryExecutionError as e:
31
+ # models.db.session.rollback()
32
+ return e
33
+
34
+
35
+ from flask_sqlalchemy import SQLAlchemy
36
+
37
+
38
+ class LessCodeSQLAlchemy(SQLAlchemy):
39
+ pass
40
+ # def apply_driver_hacks(self, app, info, options):
41
+ # options.update(json_serializer=json_dumps)
42
+ # if settings.SQLALCHEMY_ENABLE_POOL_PRE_PING:
43
+ # options.update(pool_pre_ping=True)
44
+ # return super(RedashSQLAlchemy, self).apply_driver_hacks(app, info, options)
45
+ #
46
+ # def apply_pool_defaults(self, app, options):
47
+ # super(RedashSQLAlchemy, self).apply_pool_defaults(app, options)
48
+ # if settings.SQLALCHEMY_ENABLE_POOL_PRE_PING:
49
+ # options["pool_pre_ping"] = True
50
+ # if settings.SQLALCHEMY_DISABLE_POOL:
51
+ # options["poolclass"] = NullPool
52
+ # # Remove options NullPool does not support:
53
+ # options.pop("max_overflow", None)
54
+ # return options
55
+
56
+
57
+ # db = LessCodeSQLAlchemy(
58
+ # session_options={"expire_on_commit": False},
59
+ # engine_options={"json_serializer": json_dumps, "json_deserializer": json_loads}, )
60
+ db = LessCodeSQLAlchemy()
@@ -0,0 +1,27 @@
1
+ from redash.query_runner import get_query_runner, with_ssh_tunnel
2
+
3
+
4
+ class DataSource():
5
+ def __init__(self):
6
+ self.options = None
7
+ self.data_source_id = None
8
+
9
+ @staticmethod
10
+ def get_by_id(object_id):
11
+ datasource = DataSource()
12
+ datasource.data_source_id = object_id
13
+ from lesscode_flask.utils.helpers import app_config
14
+ datasource_list = app_config.get("DATA_SOURCE")
15
+ datasource_list = [item for item in datasource_list if item.get("id") == object_id]
16
+ if len(datasource_list) > 0:
17
+ datasource.options = datasource_list[0]
18
+ return datasource
19
+
20
+ @property
21
+ def query_runner(self):
22
+ query_runner = get_query_runner(self.options.get("type"), self.options)
23
+ uses_ssh_tunnel = self.options.get("ssh_tunnel", False)
24
+ if uses_ssh_tunnel:
25
+ query_runner = with_ssh_tunnel(query_runner, self.options.get("ssh_tunnel"))
26
+
27
+ return query_runner
@@ -0,0 +1,128 @@
1
+ import time
2
+
3
+
4
+ class QueryExecutionError(Exception):
5
+ pass
6
+
7
+
8
+ class QueryExecutor:
9
+ # , user_id, is_api_key, metadata, is_scheduled_query
10
+ def __init__(self, query_text, query_runner):
11
+ # self.job = get_current_job()
12
+ self.query_text = query_text
13
+ # self.data_source_id = data_source_id
14
+ # self.metadata = metadata
15
+ self.metadata = {}
16
+ # self.data_source = self._load_data_source()
17
+ self.query_runner = query_runner
18
+ # self.query_id = metadata.get("query_id")
19
+ # self.user = _resolve_user(user_id, is_api_key, metadata.get("query_id"))
20
+ self.user = None
21
+ # self.query_model = (
22
+ # models.Query.query.get(self.query_id)
23
+ # if self.query_id and self.query_id != "adhoc"
24
+ # else None
25
+ # ) # fmt: skip
26
+
27
+ # Close DB connection to prevent holding a connection for a long time while the query is executing.
28
+ # models.db.session.close()
29
+ # self.query_hash = gen_query_hash(self.query)
30
+ # self.is_scheduled_query = is_scheduled_query
31
+ # if self.is_scheduled_query:
32
+ # # Load existing tracker or create a new one if the job was created before code update:
33
+ # models.scheduled_queries_executions.update(self.query_model.id)
34
+
35
+ def run(self):
36
+ started_at = time.time()
37
+ #
38
+ # logger.debug("Executing query:\n%s", self.query)
39
+ self._log_progress("executing_query")
40
+
41
+ annotated_query = self._annotate_query(self.query_runner)
42
+
43
+ try:
44
+ data, error = self.query_runner.run_query(annotated_query, self.user)
45
+ except Exception as e:
46
+ # if isinstance(e, JobTimeoutException):
47
+ # error = TIMEOUT_MESSAGE
48
+ # else:
49
+ # error = str(e)
50
+ print(f"发生异常: {e}")
51
+ data = None
52
+ # logger.warning("Unexpected error while running query:", exc_info=1)
53
+ run_time = time.time() - started_at
54
+ return data
55
+
56
+ #
57
+ # logger.info(
58
+ # "job=execute_query query_hash=%s ds_id=%d data_length=%s error=[%s]",
59
+ # self.query_hash,
60
+ # self.data_source_id,
61
+ # data and len(data),
62
+ # error,
63
+ # )
64
+ #
65
+ # _unlock(self.query_hash, self.data_source.id)
66
+
67
+ # if error is not None and data is None:
68
+ # result = QueryExecutionError(error)
69
+ # # if self.is_scheduled_query:
70
+ # # self.query_model = models.db.session.merge(self.query_model, load=False)
71
+ # # track_failure(self.query_model, error)
72
+ # raise result
73
+ # else:
74
+ # if self.query_model and self.query_model.schedule_failures > 0:
75
+ # self.query_model = models.db.session.merge(self.query_model, load=False)
76
+ # self.query_model.schedule_failures = 0
77
+ # self.query_model.skip_updated_at = True
78
+ # models.db.session.add(self.query_model)
79
+ #
80
+ # query_result = models.QueryResult.store_result(
81
+ # self.data_source.org_id,
82
+ # self.data_source,
83
+ # self.query_hash,
84
+ # self.query,
85
+ # data,
86
+ # run_time,
87
+ # utcnow(),
88
+ # )
89
+ #
90
+ # updated_query_ids = models.Query.update_latest_result(query_result)
91
+ #
92
+ # models.db.session.commit() # make sure that alert sees the latest query result
93
+ # self._log_progress("checking_alerts")
94
+ # for query_id in updated_query_ids:
95
+ # check_alerts_for_query.delay(query_id, self.metadata)
96
+ # self._log_progress("finished")
97
+ #
98
+ # result = query_result.id
99
+ # models.db.session.commit()
100
+ # return result
101
+
102
+ def _annotate_query(self, query_runner):
103
+ pass
104
+ # self.metadata["Job ID"] = self.job.id
105
+ # self.metadata["Query Hash"] = self.query_hash
106
+ # self.metadata["Scheduled"] = self.is_scheduled_query
107
+
108
+ return query_runner.annotate_query(self.query_text, self.metadata)
109
+
110
+ def _log_progress(self, state):
111
+ pass
112
+ # logger.info(
113
+ # "job=execute_query state=%s query_hash=%s type=%s ds_id=%d "
114
+ # "job_id=%s queue=%s query_id=%s username=%s", # fmt: skip
115
+ # state,
116
+ # self.query_hash,
117
+ # self.data_source.type,
118
+ # self.data_source.id,
119
+ # self.job.id,
120
+ # self.metadata.get("Queue", "unknown"),
121
+ # self.metadata.get("query_id", "unknown"),
122
+ # self.metadata.get("Username", "unknown"),
123
+ # )
124
+
125
+ def _load_data_source(self):
126
+ pass
127
+ # logger.info("job=execute_query state=load_ds ds_id=%d", self.data_source_id)
128
+ # return models.DataSource.query.get(self.data_source_id)
@@ -0,0 +1,62 @@
1
+ from logging import Handler
2
+
3
+ from flask import request, copy_current_request_context
4
+ from flask_login import current_user
5
+ import threading
6
+ from lesscode_flask.model.access_log import AccessLog
7
+
8
+ from lesscode_flask.service.access_log_service import AccessLogService
9
+ from lesscode_flask.utils.helpers import app_config
10
+ from lesscode_flask.utils.redis.redis_helper import RedisHelper
11
+
12
+
13
+ class AccessLogHandler(Handler):
14
+ def __init__(self, *args, **kwargs):
15
+ super().__init__(*args, **kwargs)
16
+
17
+ def emit(self, record):
18
+ # 客户端IP
19
+ referrer = request.referrer
20
+ client_ip = request.remote_addr
21
+ x_forwarded_for = request.headers.get('X-Forwarded-For')
22
+ if x_forwarded_for:
23
+ client_ip = x_forwarded_for.split(',')[0]
24
+ params = {}
25
+ args = request.args
26
+ if args:
27
+ params["args"] = args
28
+ form = request.form
29
+ if form:
30
+ params["form"] = form
31
+ if request.mimetype == 'application/json' and request.json is not None:
32
+ params["json"] = request.json
33
+
34
+ request_id = request.headers.get('Request-Id')
35
+ if request_id is None:
36
+ request_id = request.request_id
37
+ user_agent_string = request.headers.get('user-agent')
38
+ url = request.path
39
+ url_info_key = f"upms:url_info:{url}"
40
+
41
+ resource_id = "-"
42
+ resource_label = "-"
43
+ url_info = RedisHelper(app_config.get("REDIS_OAUTH_KEY", "redis")).sync_hgetall(url_info_key)
44
+ if url_info:
45
+ resource_id = url_info.get("id", "-")
46
+ resource_label = url_info.get("label", "-")
47
+
48
+ access_log = AccessLog(request_id=request_id, display_name=current_user.display_name,
49
+ phone_no=current_user.phone_no,
50
+ resource_id=resource_id,
51
+ resource_label=resource_label, url=url, referrer=referrer, client_ip=client_ip,
52
+ user_agent=user_agent_string,
53
+ params=params, duration=record.message)
54
+
55
+ @copy_current_request_context
56
+ def thread_function(access_log):
57
+ # 在这个函数内部,应用上下文将会被正确传递
58
+ AccessLogService.add_item(access_log)
59
+
60
+ # 创建并启动线程
61
+ thread = threading.Thread(target=thread_function, args=[access_log])
62
+ thread.start()