Python标准库一览

repo: github.com/alphardex/p…

想掌握Python标准库,读它的官方文档很重要。本文并非此文档的复制版,而是对每一个库的一句话概括以及它的主要函数,由此用什么库心里就会有数了。

文本处理

  • string: 提供了字符集:ascii_lowercase, ascii_uppercase, digits, hexdigits, punctuation
  • re: 正则表达式支持(pattern, string):match, search, findall, sub, split, finditer

数据结构

  • datetime: 处理日期,建议用arrow代替
  • calendar: 日历: Calendar
  • collections: 其他数据结构: deque, Counter, defaultdict, namedtuple
  • heapq: 堆排序实现: nlargest, nsmallest, merge
  • bisect: 二分查找实现: bisect, insort
  • array: 数列实现: array
  • copy: 浅拷贝和深拷贝: copy, deepcopy
  • pprint: 漂亮地输出文本: pprint
  • enum: 枚举类的实现: Enum

数学

  • math: 数学函数库,函数太多故不一一列举
  • fractions: 分数运算: Fraction as F
  • random: 随机数: choice, randint, randrange, sample, shuffle, gauss
  • statistics: 统计学函数: mean, median, mode, variance

函数式编程模块

  • itertools: 迭代器工具: permutations, combinations, product, chain, repeat, cycle, accumulate
  • functools: 函数工具: @wraps, reduce, partial, @lrucache, @singledispatch
  • operator: 基本运算符

文件目录访问

  • pathlib: 对路径对象进行操作,完美替代os.path: Path
  • fileinput: 读取一个或多个文件并处理行: input
  • filecmp: 比较两个文件是否相同: cmp
  • tempfile:用来创建临时文件,一关闭就自动删除:TemporaryFile
  • linecache: 读取文件的行,缓存优化: getline, getlines
  • shutil: 文件操作: copy, copytree, rmtree, move, make_archive

数据持久化

  • pickle: 文件pickle序列化: dump, dumps, load, loads
  • sqlite3: sqlite数据库接口

文件格式

  • csv: 处理csv文件: reader, writeheader, writerow
  • configparser: 处理配置文件: ConfigParser, get, sections

密码学

  • hashlib: 哈希加密算法: sha256, hexdigest
  • secrets:密钥生成:token_bytes, token_hex, token_urlsafe

操作系统

  • os: 操作系统,具体看文档
  • io: 在内存中读写str和bytes: StringIO, BytesIO, write, get_value
  • time: 计时器: time, sleep, strftime
  • argparse, getopt: 命令行处理,建议用clickdocopt代替
  • logging: 打日志: debug, info, warning, error, critical,建议用loguru代替
  • getpass: 获取用户输入的密码: getpass
  • platform: 提供跨平台支持: uname, system

并发执行

  • threading: 多线程模型: Thread, start, join
  • multiprocessing: 多进程模型: Pool, map, Process
  • concurrent.futures: 异步执行模型: ThreadPoolExecutor, ProcessPoolExecutor
  • subprocess: 子进程管理: run
  • sched: 调度工具,建议用schedule代替
  • queue: 同步队列: Queue

进程间通信和网络

  • asyncio: 异步IO, eventloop, 协程: get_event_loop, run_until_complete, wait, async和await关键字

网络数据处理

  • email: 处理email,建议用yagmail代替
  • json: 处理json: dumps, loads
  • base64: 处理base64编码: b64encode, b64decode

结构化标记语言工具

  • html: 转义html: escape, unescape
  • html.parser: 解析html,建议用parsel代替

网络协议支持

  • webbrowser: 打开浏览器: open
  • wsgiref: 实现WSGI接口
  • uuid: 通用唯一识别码: uuid1, uuid3, uuid4, uuid5
  • ftplib, poplib, imaplib, nntplib, smptlib, telnetlib: 实现各种网络协议

其余库用requests代替

程序框架

  • turtle: 画图工具
  • cmd: 实现交互式shell
  • shlex: 利用shell的语法分割字符串: split

GUI

开发工具

  • typing: 类型注解,可配合mypy对项目进行静态类型检查
  • pydoc: 查阅模块文档: python -m pydoc [name]
  • doctest: 文档测试: python -m doctest [pyfile]
  • unittest: 单元测试: python -m unittest [pyfile]

DEBUG和性能优化

  • pdb: Python Debugger: python -m pdb [pyfile]
  • cProfile: 分析程序性能: python -m cProfile [pyfile]
  • timeit: 检测代码运行时间: python -m timeit [pyfile]

软件打包发布

  • setuptools: 编写setup.py专用: setup, find_packages
  • venv: 创建虚拟环境,建议用pipenv代替

Python运行时服务

  • sys: 系统环境交互: argv, path, exit, stderr, stdin, stdout
  • builtins: 所有的内置函数和类,默认引进(还有一个boltons扩充了许多有用的函数和类)
  • __main__: 顶层运行环境,使得python文件既可以独立运行,也可以当做模块导入到其他文件。
  • warnings: 警告功能(代码过时等): warn
  • contextlib: 上下文管理器实现: @contextmanager
  • inspect:用于获取对象的各种信息(自省)

自定义Python解释器

  • code: 实现自定义的Python解释器(比如Scrapy的shell): interact

转载于:https://juejin.im/post/5cc45a146fb9a0322c429557

这里提供一个简单的示例,实现基于 Spring MVC 和 Ajax 的表格查询功能,使用的前端框架是 layui 数据表格,数据库使用的是 MySQL。 1. 在 pom.xml 文件中添加以下依赖: ```xml <!-- Spring MVC --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>${spring.version}</version> </dependency> <!-- Jackson JSON --> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>${jackson.version}</version> </dependency> <!-- MySQL JDBC --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>${mysql.version}</version> </dependency> ``` 2. 在 Spring 配置文件中添加以下配置: ```xml <!-- 数据源配置 --> <bean id="dataSource" class="org.apache.commons.dbcp2.BasicDataSource" destroy-method="close"> <property name="driverClassName" value="com.mysql.jdbc.Driver" /> <property name="url" value="jdbc:mysql://localhost:3306/test" /> <property name="username" value="root" /> <property name="password" value="password" /> </bean> <!-- MyBatis 配置 --> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource" /> <property name="typeAliasesPackage" value="com.example.model" /> <property name="mapperLocations" value="classpath*:com/example/mapper/*.xml" /> <property name="configLocation" value="classpath:mybatis-config.xml" /> </bean> <!-- MyBatis Mapper 扫描 --> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="com.example.mapper" /> </bean> <!-- 开启 Spring MVC 注解支持 --> <annotation-driven/> <!-- 静态资源处理 --> <mvc:resources mapping="/static/**" location="/static/" /> <!-- 视图解析器 --> <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/views/" /> <property name="suffix" value=".jsp" /> </bean> ``` 3. 在 Spring MVC 配置文件中添加以下配置: ```xml <!-- 开启注解驱动 --> <mvc:annotation-driven /> <!-- 配置处理器映射器 --> <bean class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping" /> <!-- 配置控制器 --> <bean name="/ajaxTable" class="com.example.controller.AjaxTableController" /> <!-- 配置 AJAX 返回值处理器 --> <bean class="org.springframework.web.servlet.view.json.MappingJackson2JsonView" /> ``` 4. 创建一个实体类 User,对应 MySQL 数据库中的 user 表: ```java public class User { private Long id; private String username; private String email; private String phone; // getter 和 setter 方法省略 } ``` 5. 创建一个 DAO 接口 UserMapper,使用 MyBatis 进行数据库操作: ```java public interface UserMapper { List<User> selectByCondition(Map<String, Object> condition); } ``` 6. 创建一个控制器 AjaxTableController,实现搜索功能: ```java @Controller public class AjaxTableController { @Autowired private UserMapper userMapper; @RequestMapping("/ajaxTable") public ModelAndView ajaxTable() { return new ModelAndView("ajaxTable"); } @RequestMapping("/ajaxTable/search") @ResponseBody public Map<String, Object> search(HttpServletRequest request) { Map<String, Object> result = new HashMap<>(); String username = request.getParameter("username"); String email = request.getParameter("email"); String phone = request.getParameter("phone"); Map<String, Object> condition = new HashMap<>(); condition.put("username", username); condition.put("email", email); condition.put("phone", phone); List<User> userList = userMapper.selectByCondition(condition); result.put("code", 0); result.put("msg", ""); result.put("count", userList.size()); result.put("data", userList); return result; } } ``` 7. 创建一个 JSP 页面 ajaxTable.jsp,使用 layui 数据表格展示数据: ```html <!doctype html> <html> <head> <meta charset="UTF-8"> <title>Ajax Table</title> <link rel="stylesheet" href="/static/layui/css/layui.css"> </head> <body> <div class="layui-container"> <div class="layui-row layui-col-space15"> <div class="layui-card"> <div class="layui-card-body"> <form class="layui-form layui-form-pane" lay-filter="table-search"> <div class="layui-form-item layui-inline"> <label class="layui-form-label">Username</label> <div class="layui-input-inline"> <input type="text" name="username" class="layui-input" autocomplete="off"> </div> </div> <div class="layui-form-item layui-inline"> <label class="layui-form-label">Email</label> <div class="layui-input-inline"> <input type="text" name="email" class="layui-input" autocomplete="off"> </div> </div> <div class="layui-form-item layui-inline"> <label class="layui-form-label">Phone</label> <div class="layui-input-inline"> <input type="text" name="phone" class="layui-input" autocomplete="off"> </div> </div> <div class="layui-form-item"> <div class="layui-input-inline"> <button class="layui-btn" type="button" lay-submit lay-filter="table-search-btn">Search</button> <button class="layui-btn layui-btn-primary" type="reset">Reset</button> </div> </div> </form> </div> </div> <div class="layui-card"> <div class="layui-card-body"> <table id="userTable" lay-filter="userTable"></table> </div> </div> </div> </div> <script src="/static/layui/layui.js"></script> <script> layui.use(['table', 'form'], function () { var table = layui.table; var form = layui.form; table.render({ elem: '#userTable', url: '/ajaxTable/search', method: 'post', page: true, cols: [[ {field: 'id', title: 'ID', width: 80}, {field: 'username', title: 'Username', width: 120}, {field: 'email', title: 'Email', width: 200}, {field: 'phone', title: 'Phone', width: 120} ]] }); form.on('submit(table-search-btn)', function (data) { table.reload('userTable', { where: data.field }); return false; }); }); </script> </body> </html> ``` 通过访问 `/ajaxTable` 页面即可看到一个带搜索功能的数据表格。用户输入搜索条件后,点击搜索按钮即可实现异步请求,后台根据条件查询数据库,将查询结果返回给前端,前端使用 layui 数据表格展示数据。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值