From b39101ee98f2549bff93394ea8b012a9da9b1c24 Mon Sep 17 00:00:00 2001 From: wendell <727169395@qq.com> Date: Tue, 7 May 2019 15:26:03 +0800 Subject: [PATCH] =?UTF-8?q?http=E8=AF=B7=E6=B1=82=E5=8F=8A=E6=95=B0?= =?UTF-8?q?=E6=8D=AE=E5=BA=93=E6=93=8D=E4=BD=9C=E5=B7=A5=E5=85=B7=E7=B1=BB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- source/area/china/util/DbUtil.py | 35 +++++++++++++++++++ source/area/china/util/RequestUtil.py | 49 +++++++++++++++++++++++++++ source/area/china/util/__init__.py | 0 3 files changed, 84 insertions(+) create mode 100644 source/area/china/util/DbUtil.py create mode 100644 source/area/china/util/RequestUtil.py create mode 100644 source/area/china/util/__init__.py diff --git a/source/area/china/util/DbUtil.py b/source/area/china/util/DbUtil.py new file mode 100644 index 0000000..3fca96c --- /dev/null +++ b/source/area/china/util/DbUtil.py @@ -0,0 +1,35 @@ +# -*- coding: UTF-8 -*- +""" +@description 工具类,数据库 +@author wendell +""" +from pymongo import MongoClient + + +def get_client(): + """ + 获取连接客户端 + :return: 链接客户端 + """ + return MongoClient("mongodb://localhost:27017/", connect=False) + + +def get_db(db=None): + """ + 获取数据库 + :param db: 默认链接到python数据库 + :return: + """ + if not db: + db = 'python' + return get_client().get_database(name=db) + + +def close_client(client): + """ + 关闭客户端连接 + :param client: 连接客户端 + :return: + """ + if client: + client.close() diff --git a/source/area/china/util/RequestUtil.py b/source/area/china/util/RequestUtil.py new file mode 100644 index 0000000..fa7b144 --- /dev/null +++ b/source/area/china/util/RequestUtil.py @@ -0,0 +1,49 @@ +# -*- coding: UTF-8 -*- +""" +@description 工具类,requests库二次封装 +@author wendell +""" +import requests +from requests.exceptions import InvalidURL + + +def get(url, timeout=None, headers=None, encoding=None): + """ + 发送GET请求 + :param url: URL + :param timeout: 超时时间(秒) + :param headers: 头部信息 + :param encoding: 编码 + :return: + """ + # 参数验证,URL不能为空 + if not url: + raise InvalidURL("Invalid URL %r" % url) + response = requests.get(url, headers=headers, timeout=timeout) + if not response: + return None + if encoding: + response.encoding = encoding + if response.status_code == 200: + r_text = response.text + response.close() + return r_text + response.close() + return None + + +def prepare_url(url): + """ + 预处理URL连接,规范url + www.a.com //www.a.com ==>> http://www.a.com + :param url: URL + :return: 处理的URL + """ + if not url: + return None + res = url + if url.startswith('//'): + res = 'http:' + url + elif not url.startswith('http://') and not url.startswith('https://'): + res = 'http://' + url + return res diff --git a/source/area/china/util/__init__.py b/source/area/china/util/__init__.py new file mode 100644 index 0000000..e69de29