首页 文章 精选 留言 我的

精选列表

搜索[博客搭建],共10000篇文章
优秀的个人博客,低调大师

[python作业AI毕业设计博客]Functional Programming For Dummies - 2019 函数式编程傻瓜书

函数式编程范例指南 下载地址:https://itbooks.pipipan.com/fs/18113597-335607573 函数式编程主要用于数学计算,包括人工智能和游戏中使用的算法。这种编程范例使得用于数学计算的算法更容易理解,并为非开发人员提供了一种编码算法的简洁方法。目前市场上的书籍具有陡峭的学习曲线,因为它们大多是由开发人员为开发人员编写的。 本书探讨了纯粹(由Haskell语言表示)和不纯(用Python语言表示)方法之间的差异,为像您一样的读者进行函数式编程。纯方法最适合那些不想创建生产代码但需要完全测试算法并证明它们对同行有用的研究人员。不纯的方法最适合生产环境,因为可以在单个应用程序中混合编码范例以更快地生成结果。函数式编程傻瓜书使用这种双管齐下的方法为您提供一种编码方法的一体化方法,否则很难掌握。 •在编码时学习纯粹和不纯洁•深入了解大多数功能程序员用来推导,分析和证明算法价值的过程•受益于Python和Haskell中提供的示例•收集专家作者的专业知识,该作者迄今已编写了一些市场领先的编程书籍 如果您已准备好按摩数据以了解事物如何以新的方式运作,那么您来对地方了!

优秀的个人博客,低调大师

[雪峰磁针石博客]大数据Hadoop工具python教程9-Luigi工作流

管理Hadoop作业的官方工作流程调度程序是Apache Oozie。与许多其他Hadoop产品一样,Oozie是用Java编写的,是基于服务器的Web应用程序,它运行执行Hadoop MapReduce和Pig的工作流作业。 Oozie工作流是在XML文档中指定的控制依赖性指导非循环图(DAG)中排列的动作集合。虽然Oozie在Hadoop社区中有很多支持,但通过XML属性配置工作流和作业的学习曲线非常陡峭。 Luigi是Spotify创建的Python替代方案,可以构建和配置复杂的批处理作业管道。它处理依赖项解析,工作流管理,可视化等等。它还拥有庞大的社区,并支持许多Hadoop技术。在github上超过1万星。 本章介绍Luigi的安装和工作流程的详细说明。 安装 pip install luigi 工作流 在Luigi中,工作流由一系列操作组成,称为任务。 Luigi任务是非特定的,也就是说,它们可以是任何可以用Python编写的东西。任务的输入和输出数据的位置称为目标(target)。目标通常对应于磁盘上,HDFS上或数据库中的文件位置。除了任务和目标之外,Luigi还利用参数来自定义任务的执行方式。 任务 任务是构成Luigi工作流的操作序列。每个任务都声明其依赖于其他任务创建的目标。这样Luigi能够创建依赖链。 目标 目标是任务的输入和输出。最常见的目标是磁盘上的文件,HDFS中的文件或数据库中的记录。 Luigi包装了底层文件系统操作,以确保与目标的交互是原子的。这允许从故障点重放工作流,而不必重放任何已经成功完成的任务。 参数 参数允许通过允许值从命令行,以编程方式或从其他任务传递任务来自定义任务。例如,任务输出的名称可以通过参数传递给任务的日期来确定。 参考资料 python测试开发项目实战-目录 python工具书籍下载-持续更新 python 3.7极速入门教程 - 目录 原文地址 本文涉及的python测试开发库 谢谢点赞! [本文相关海量书籍下载](https://github.com/china-testing/python-api-tesing/blob/master/books.md 工作流本示例 #!/usr/bin/env python # 项目实战讨论QQ群630011153 144081101 # https://github.com/china-testing/python-api-tesing import luigi class InputFile(luigi.Task): """ A task wrapping a Target """ input_file = luigi.Parameter() def output(self): """ Return the target for this task """ return luigi.LocalTarget(self.input_file) class WordCount(luigi.Task): """ A task that counts the number of words in a file """ input_file = luigi.Parameter() output_file = luigi.Parameter(default='/tmp/wordcount') def requires(self): """ The task's dependencies: """ return InputFile(self.input_file) def output(self): """ The task's output """ return luigi.LocalTarget(self.output_file) def run(self): """ The task's logic """ count = {} ifp = self.input().open('r') for line in ifp: for word in line.strip().split(): count[word] = count.get(word, 0) + 1 ofp = self.output().open('w') for k, v in count.items(): ofp.write('{}\t{}\n'.format(k, v)) ofp.close() if __name__ == '__main__': luigi.run() 执行 $ python wordcount.py WordCount --local-scheduler --input-file /home/hduser_/input2.txt --output-file /tmp/wordcount2.txt DEBUG: Checking if WordCount(input_file=/home/hduser_/input2.txt, output_file=/tmp/wordcount2.txt) is complete DEBUG: Checking if InputFile(input_file=/home/hduser_/input2.txt) is complete INFO: Informed scheduler that task WordCount__home_hduser__in__tmp_wordcount2__a94efba0f2 has status PENDING INFO: Informed scheduler that task InputFile__home_hduser__in_0eced493f7 has status DONE INFO: Done scheduling tasks INFO: Running Worker with 1 processes DEBUG: Asking scheduler for work... DEBUG: Pending tasks: 1 INFO: [pid 21592] Worker Worker(salt=067173106, workers=1, host=andrew-PC, username=hduser_, pid=21592) running WordCount(input_file=/home/hduser_/input2.txt, output_file=/tmp/wordcount2.txt) INFO: [pid 21592] Worker Worker(salt=067173106, workers=1, host=andrew-PC, username=hduser_, pid=21592) done WordCount(input_file=/home/hduser_/input2.txt, output_file=/tmp/wordcount2.txt) DEBUG: 1 running tasks, waiting for next task to finish INFO: Informed scheduler that task WordCount__home_hduser__in__tmp_wordcount2__a94efba0f2 has status DONE DEBUG: Asking scheduler for work... DEBUG: Done DEBUG: There are no more tasks to run at this time INFO: Worker Worker(salt=067173106, workers=1, host=andrew-PC, username=hduser_, pid=21592) was stopped. Shutting down Keep-Alive thread INFO: ===== Luigi Execution Summary ===== Scheduled 2 tasks of which: * 1 complete ones were encountered: - 1 InputFile(input_file=/home/hduser_/input2.txt) * 1 ran successfully: - 1 WordCount(input_file=/home/hduser_/input2.txt, output_file=/tmp/wordcount2.txt) This progress looks :) because there were no failed tasks or missing dependencies ===== Luigi Execution Summary ===== hduser_@andrew-PC:/home/andrew/code/HadoopWithPython/python/Luigi$ cat /tmp/wordcount2.txt jack 2 be 2 nimble 1 quick 1

优秀的个人博客,低调大师

[雪峰磁针石博客]python标准模块介绍- binascii 二进制和ASCII转换

python测试开发项目实战-目录 python工具书籍下载-持续更新 python 3.7极速入门教程 - 目录 简介 binascii模块包含很多用来方法来转换二进制和各种ASCII编码的二进制表示法。通常不直接使用这些功能,而是使用封装模块,如uu, base64或binhex。binascii模块包含用C语言编写更快的低级功能,通常为高级模块所使用。 功能:二进制和ASCII转换。 类型:标准模块 相关模块: base64 标准模块。 binhex 标准模块。 uu 标准模块。 quopri 标准模块。 Uu编码 uu编码格式现在已经比较少使用(http://zh.wikipedia.org/wiki/Uuencode),相关函数binascii.a2b_uu(string)和binascii.b2a_uu(data)这里不做介绍。 更多资料参见:http://docs.python.org/2/library/uu.html Binhex编码 Binhex用于Macintosh平台。这里暂不做介绍。相关函数有:binascii.rledecode_hqx(data) ,binascii.rlecode_hqx(data),binascii.b2a_hqx(data) ,binascii.crc_hqx(data, crc)。 更多资料参见: http://docs.python.org/2/library/uu.html Base64编码 binascii.a2b_base64(string):转换的base64数据块为二进制,并返回二进制数据。一次可以传递多行。和base64. b64decode对应。 binascii.b2a_base64(data):转换二进制数据为一行base64编码的ASCII字符。返回字符串包含换行符。根据base64的标准data的长度最大为57。和base64. b64encode对应。 更多资料参见:http://docs.python.org/2/library/base64.html QP码 Quoted-printable,或QP encoding,没有规范的中文译名,可译为“可打印字符引用编码”、“使用可打印字符的编码”。Quoted-printable是使用可打印的 ASCII字符 (如字母、数字与"=")表示各种编码格式下的字符,以便能在7-bit数据通路上传输8-bit数据, 或者更一般地说在非8-bit clean媒体上正确处理数据。这被定义为MIME content transfer encoding,用于e-mail。 QP使用"="开头的转义字符. 一般限制行宽为76,因为有些软件限制了行宽. binascii.a2b_qp(string[, header]):转换引述打印数据块为二进制,并返回二进制数据。多行可以在同一时间被传递。如果可选参数头存在和真实,下划线将被解码为空格。 实际上,QP码是是把’\x00’转换成’=00’,也就是替换’\x’为’=’。 >>> s ='\x00=' >>> s = '=\x00hello' >>> import binascii >>> encoded = binascii.b2a_qp(s) >>> encoded '=3D=00hello' >>> decoded = binascii.a2b_qp(encoded) >>> print decoded =hello >>> print repr(decoded) '=\x00hello' CRC校验和 binascii.crc32(data[, crc]):计算的data 的32位校验和CRC- 32时,crc为初始CRC 。crc32与ZIP文件的校验和一致。 >>> print binascii.crc32("hello world") 222957957 >>> crc = binascii.crc32("hello") >>> crc = binascii.crc32(" world", crc) & 0xffffffff >>> print 'crc32 = 0x%08x' % crc crc32 = 0x0d4a1185 >>> crc 222957957 为了保证跨平台,可以在crc结果上& 0xffffffff。原因如下: Changed in version 2.6: The return value is in the range [-2**31, 2**31-1] regardless of platform. In the past the value would be signed on some platforms and unsigned on others. Use & 0xffffffff on the value if you want it to match Python 3 behavior. Changed in version 3.0: The return value is unsigned and in the range [0, 2**32-1] regardless of platform. 二进制转换 binascii.b2a_hex(data)和binascii.hexlify(data):返回二进制数据的十六进制表示。每个字节被转换成相应的 2位十六进制表示形式。因此,得到的字符串是是原数据长度的两倍。 binascii.a2b_hex(hexstr) 和binascii.unhexlify(hexstr):从十六进制字符串hexstr返回二进制数据。是b2a_hex的逆向操作。 hexstr必须包含偶数个十六进制数字(可以是大写或小写),否则报TypeError。 >>> s = 'hello' >>> b = b2a_hex(s) >>> print b 68656c6c6f >>> a2b_hex(b) 'hello' >>> b = hexlify(s) >>> print b 68656c6c6f >>> unhexlify(b) 'hello' 参考资料 python测试等IT技术支持qq群: 144081101(后期会录制视频存在该群群文件) 591302926 567351477 本文最新版本地址 本文涉及的python测试开发库 谢谢点赞! 本文相关海量书籍下载 python官方文档:https://docs.python.org/3/library/binascii.html http://effbot.org/librarybook/binascii.htm 其他实例 http://effbot.org/librarybook/binascii.htm 有如下实例: import binascii text = "hello, mrs teal" data = binascii.b2a_base64(text) text = binascii.a2b_base64(data) print text, "<=>", repr(data) data = binascii.b2a_uu(text) text = binascii.a2b_uu(data) print text, "<=>", repr(data) data = binascii.b2a_hqx(text) text = binascii.a2b_hqx(data)[0] print text, "<=>", repr(data) # 2.0 and newer data = binascii.b2a_hex(text) text = binascii.a2b_hex(data) print text, "<=>", repr(data) 执行结果: # python test.py hello, mrs teal <=> 'aGVsbG8sIG1ycyB0ZWFs\n' hello, mrs teal <=> '/:&5L;&\\L(&UR<R!T96%L\n' hello, mrs teal <=> 'D\'9XE\'mX)\'ebFb"dC@&X' hello, mrs teal <=> '68656c6c6f2c206d7273207465616c' 另外单元测试的代码也可供参考:http://svn.python.org/projects/python/branches/tarek_sysconfig/Lib/test/test_binascii.py

优秀的个人博客,低调大师

[雪峰磁针石博客]flask构建自动化测试平台7-添加google地图

本章将介绍以下主题: mock数据库 创建犯罪地图 本文最新版本 代码地址 mock数据库 mockdbhelper.py class MockDBHelper: def connect(self, database="crimemap"): pass def add_crime(self, category, date, latitude, longitude, description): data = [category, date, latitude, longitude, description] for i in data: print (i, type(i)) def get_all_crimes(self): return [{'latitude': -33.301304, 'longitude': 26.523355, 'date': "2000-01-01", 'category': "mugging", 'description': "mock description"}] def add_input(self, data): pass def clear_all(self): pass db_setup.py import pymysql import dbconfig connection = pymysql.connect(host='localhost', user=dbconfig.db_user, passwd=dbconfig.db_password) try: with connection.cursor() as cursor: sql = "CREATE DATABASE IF NOT EXISTS crimemap" cursor.execute(sql) sql = """CREATE TABLE IF NOT EXISTS crimemap.crimes ( id int NOT NULL AUTO_INCREMENT, latitude FLOAT(10,6), longitude FLOAT(10,6), date DATETIME, category VARCHAR(50), description VARCHAR(255), updated_at TIMESTAMP, PRIMARY KEY (id) )""" cursor.execute(sql) connection.commit() finally: connection.close() crimemap.py from flask import Flask from flask import render_template from flask import request import json import dbconfig if dbconfig.test: from mockdbhelper import MockDBHelper as DBHelper else: from dbhelper import DBHelper app = Flask(__name__) DB = DBHelper() @app.route("/") def home(): crimes = DB.get_all_crimes() crimes = json.dumps(crimes) return render_template("home.html", crimes=crimes) @app.route("/submitcrime", methods=['POST']) def submitcrime(): category = request.form.get("category") date = request.form.get("date") latitude = float(request.form.get("latitude")) longitude = float(request.form.get("longitude")) description = request.form.get("description") DB.add_crime(category, date, latitude, longitude, description) return home() if __name__ == '__main__': app.run(host='0.0.0.0',port=8000, debug=True) dbconfig.py test = True dbhelper.py import pymysql import dbconfig class DBHelper: def connect(self, database="crimemap"): return pymysql.connect(host='localhost', user=dbconfig.db_user, passwd=dbconfig.db_password, db=database) def get_all_inputs(self): connection = self.connect() try: query = "SELECT description FROM crimes;" with connection.cursor() as cursor: cursor.execute(query) return cursor.fetchall() finally: connection.close() def add_input(self, data): connection = self.connect() try: query = "INSERT INTO crimes (description) VALUES (%s);" with connection.cursor() as cursor: cursor.execute(query, data) connection.commit() finally: connection.close() def clear_all(self): connection = self.connect() try: query = "DELETE FROM crimes;" with connection.cursor() as cursor: cursor.execute(query) connection.commit() finally: connection.close() home.html <!DOCTYPE html> <html lang="en"> <head> <link type="text/css" rel="stylesheet" href="{{url_for('static', filename='css/style.css') }}" /> <script type="text/javascript" src="https://maps.googleapis.com/maps/api/js"> </script> <script type="text/javascript"> var map; var marker; var existing_crimes; function initialize() { var mapOptions = { center: new google.maps.LatLng(-33.30578381949298, 26.523442268371582), zoom: 15 }; map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions); google.maps.event.addListener(map, 'click', function(event){ placeMarker(event.latLng); }); placeCrimes({{crimes | safe}}); } function placeCrimes(crimes) { for (i=0; i<crimes.length; i++) { crime = new google.maps.Marker( { position: new google.maps.LatLng(crimes[i].latitude, crimes[i].longitude), map: map, title: crimes[i].date + "\n" + crimes[i].category + "\n" + crimes[i].description } ); } } function placeMarker(location) { if (marker) { marker.setPosition(location); } else { marker = new google.maps.Marker({ position: location, map: map }); } document.getElementById('latitude').value = location.lat(); document.getElementById('longitude').value = location.lng(); } </script> </head> <body onload="initialize()"> <h1>CrimeMap</h1> <p>A map of recent criminal activity in the Grahamstown area.</p> <div id="map-canvas"></div> <div id="newcrimeform"> <h2>Submit new crime</h2> <form action="/submitcrime" method="POST"> <label for="category">Category</label> <select name="category" id="category"> <option value="mugging">Mugging</option> <option value="breakin">Break-in</option> </select> </select> <label for="date">Date</label> <input name="date" id="date" type="date"> <label for="latitude">Latitude</label> <input name="latitude" id="latitude" type="text"> <label for="longitude">Longitude</label> <input name="longitude" id="longitude" type="text"> <label for="description">Description</label> <textarea name="description" id="description" placeholder="A brief but detailed description of the crime"></textarea> <input type="submit" value="Submit"> </form> </div> </body> </html> style.css body { font-family: sans-serif; background: #eee; } #map-canvas { width: 70%; height: 500px; float: left; } #newcrimeform { float: right; width: 25%; } input, select, textarea { display: block; color: grey; border: 1px solid lightsteelblue; line-height: 15px; margin: 2px 6px 16px 0px; width: 100%; } input[type="submit"] { padding: 5px 10px 5px 10px; color: black; background: lightsteelblue; border: none; box-shadow: 1px 1px 1px #4C6E91; } input[type="submit"]:hover { background: steelblue; } 参考资料 本文相关书籍下载 讨论 钉钉免费群21745728 qq群144081101 567351477 本文涉及的python测试开发库 谢谢点赞! 本文代码地址

优秀的个人博客,低调大师

[雪峰磁针石博客]python代码风格指南(PEP8中文版)

本文给出主Python版本标准库的编码约定。CPython的C代码风格参见PEP7。 本文和PEP 257 文档字符串标准改编自Guido最初的《Python Style Guide》, 并增加了Barry的GNU Mailman Coding Style Guide的部分内容。 本文会随着语言改变等而改变。 许多项目都有自己的编码风格指南,冲突时自己的指南为准。 一致性考虑 Guido的关键点之一是:代码更多是用来读而不是写。本指南旨在改善Python代码的可读性,即PEP 20所说的“可读性计数"(Readability counts)。 风格指南强调一致性。项目、模块或函数保持一致都很重要。 最重要的是知道何时不一致, 有时风格指南并不适用。当有疑惑时运用你的最佳判断,参考其他例子并多问! 特别注意:不要因为遵守本PEP而破坏向后兼容性! 部分可以违背指南情况: 遵循指南会降低可读性。 与周围其他代码不一致。 代码在引入指南完成,暂时没有理由修改。 旧版本兼容。 代码布局 缩进 每级缩进用4个空格。 括号中使用垂直隐式缩进或使用悬挂缩进。后者应该注意第一行要没有参数,后续行要有缩进。 Yes # 对准左括号 foo = long_function_name(var_one, var_two, var_three, var_four) # 不对准左括号,但加多一层缩进,以和后面内容区别。 def long_function_name( var_one, var_two, var_three, var_four): print(var_one) # 悬挂缩进必须加多一层缩进. foo = long_function_name( var_one, var_two, var_three, var_four) No # 不使用垂直对齐时,第一行不能有参数。 foo = long_function_name(var_one, var_two, var_three, var_four) # 参数的缩进和后续内容缩进不能区别。 def long_function_name( var_one, var_two, var_three, var_four): print(var_one) 4个空格的规则是对续行可选的。 # 悬挂缩进不一定是4个空格 foo = long_function_name( var_one, var_two, var_three, var_four) if语句跨行时,两个字符关键字(比如if)加上一个空格,再加上左括号构成了很好的缩进。后续行暂时没有规定,至少有如下三种格式,建议使用第3种。 # 没有额外缩进,不是很好看,个人不推荐. if (this_is_one_thing and that_is_another_thing): do_something() # 添加注释 if (this_is_one_thing and that_is_another_thing): # Since both conditions are true, we can frobnicate. do_something() # 额外添加缩进,推荐。 # Add some extra indentation on the conditional continuation line. if (this_is_one_thing and that_is_another_thing): do_something() 右边括号也可以另起一行。有两种格式,建议第2种。 # 右括号不回退,个人不推荐 my_list = [ 1, 2, 3, 4, 5, 6, ] result = some_function_that_takes_arguments( 'a', 'b', 'c', 'd', 'e', 'f', ) # 右括号回退 my_list = [ 1, 2, 3, 4, 5, 6, ] result = some_function_that_takes_arguments( 'a', 'b', 'c', 'd', 'e', 'f', ) 空格或Tab? 空格是首选的缩进方法。 Tab仅仅在已经使用tab缩进的代码中为了保持一致性而使用。 Python 3中不允许混合使用Tab和空格缩进。 Python 2的包含空格与Tab和空格缩进的应该全部转为空格缩进。 Python2命令行解释器使用-t选项时有非法混合Tab和空格的情况会告警。当使用-tt警告提升为错误。强烈推荐这些选项!另外个人推荐pep8和autopep8模块。 最大行宽 限制所有行的最大行宽为79字符。 文本长块,比如文档字符串或注释,行长度应限制为72个字符。 多数工具默认的续行功能会破坏代码结构,使它更难理解,不推荐使用。但是超过80个字符加以提醒是必要的。一些工具可能根本不具备动态换行功能。 一些团队强烈希望更长的行宽。如果能达成一致,可以从从80提高到100个字符(最多99个字符)增加了标称线的长度,不过依旧建议文档字符串和注释保持在72的长度。 Python标准库比较保守,限制行宽79个字符(文档字符串/注释72)。 续行的首选方法是使用小括号、中括号和大括号反斜线仍可能在适当的时候。其次是反斜杠。比如with语句中: with open('/path/to/some/file/you/want/to/read') as file_1, \ open('/path/to/some/file/being/written', 'w') as file_2: file_2.write(file_1.read()) 类似的还有assert。 注意续行要尽量不影响可读性。比如通常在二元运算符之后续行: class Rectangle(Blob): def __init__(self, width, height, color='black', emphasis=None, highlight=0): if (width == 0 and height == 0 and color == 'red' and emphasis == 'strong' or highlight > 100): raise ValueError("sorry, you lose") if width == 0 and height == 0 and (color == 'red' or emphasis is None): raise ValueError("I don't think so -- values are %s, %s" % (width, height)) Blob.__init__(self, width, height, color, emphasis, highlight) 空行 两行空行分割顶层函数和类的定义。 类的方法定义用单个空行分割。 额外的空行可以必要的时候用于分割不同的函数组,但是要尽量节约使用。 额外的空行可以必要的时候在函数中用于分割不同的逻辑块,但是要尽量节约使用。 Python接 contol-L作为空白符;许多工具视它为分页符,这些要因编辑器而异。 源文件编码 在核心Python发布的代码应该总是使用UTF-8(ASCII在Python 2)。 ASCII文件(Python 2)或UTF-8(Python 3)不应有编码声明。 标准库中非默认的编码应仅用于测试或当注释或文档字符串,比如包含非ASCII字符的作者姓名,尽量使用\x , \u , \U , or \N。 Python 3.0及以后版本,PEP 3131可供参考,部分内容如下:在Python标准库必须使用ASCII标识符,并尽量只使用英文字母。此外字符串和注释也必须用ASCII。唯一的例外是:(a)测试非ASCII的功能,和(b)作者的名字不是拉丁字母。 导入 导入在单独行 Yes: import os import sys from subprocess import Popen, PIPE No: import sys, os 导入始终在文件的顶部,在模块注释和文档字符串之后,在模块全局变量和常量之前。 导入顺序如下:标准库进口,相关的第三方库,本地库。各组的导入之间要有空行。 相关的all放在导入之后。 推荐绝对路径导入,因为它们通常更可读,而且往往是表现更好的(或至少提供更好的错误消息。 import mypkg.sibling from mypkg import sibling from mypkg.sibling import example 在绝对路径比较长的情况下,也可以使用相对路径: from . import sibling from .sibling import example Python 3中已经禁止隐式的相对导入。 导入类的方法: from myclass import MyClass from foo.bar.yourclass import YourClass 如果和本地名字有冲突: import myclass import foo.bar.yourclass 禁止使用通配符导入。 通配符导入(from import *)应该避免,因为它不清楚命名空间有哪些名称存,混淆读者和许多自动化的工具。唯一的例外是重新发布对外的API时可以考虑使用。 字符串引用 Python中单引号字符串和双引号字符串都是相同的。注意尽量避免在字符串中的反斜杠以提高可读性。 根据PEP 257, 三个引号都使用双引号。 表达式和语句中的空格 强制要求 括号里边避免空格 # 括号里边避免空格 # Yes spam(ham[1], {eggs: 2}) # No spam( ham[ 1 ], { eggs: 2 } ) 逗号,冒号,分号之前避免空格 # 逗号,冒号,分号之前避免空格 # Yes if x == 4: print x, y; x, y = y, x # No if x == 4 : print x , y ; x , y = y , x 索引操作中的冒号当作操作符处理前后要有同样的空格(一个空格或者没有空格,个人建议是没有。 # Yes ham[1:9], ham[1:9:3], ham[:9:3], ham[1::3], ham[1:9:] ham[lower:upper], ham[lower:upper:], ham[lower::step] ham[lower+offset : upper+offset] ham[: upper_fn(x) : step_fn(x)], ham[:: step_fn(x)] ham[lower + offset : upper + offset] # No ham[lower + offset:upper + offset] ham[1: 9], ham[1 :9], ham[1:9 :3] ham[lower : : upper] ham[ : upper] 函数调用的左括号之前不能有空格 # Yes spam(1) dct['key'] = lst[index] # No spam (1) dct ['key'] = lst [index] 赋值等操作符前后不能因为对齐而添加多个空格 # Yes x = 1 y = 2 long_variable = 3 # No x = 1 y = 2 long_variable = 3 其他建议 二元运算符两边放置一个空格: 涉及 =、符合操作符 ( += , -=等)、比较( == , < , > , != , <> , <= , >= , in , not in , is , is not )、布尔( and , or , not )。 优先级高的运算符或操作符的前后不建议有空格。 # Yes i = i + 1 submitted += 1 x = x*2 - 1 hypot2 = x*x + y*y c = (a+b) * (a-b) # No i=i+1 submitted +=1 x = x * 2 - 1 hypot2 = x * x + y * y c = (a + b) * (a - b) 关键字参数和默认值参数的前后不要加空格 # Yes def complex(real, imag=0.0): return magic(r=real, i=imag) # No def complex(real, imag = 0.0): return magic(r = real, i = imag) 函数注释中,=前后要有空格,冒号和"->"的前面无空格,后面有空格。 # Yes def munge(input: AnyStr): def munge(sep: AnyStr = None): def munge() -> AnyStr: def munge(input: AnyStr, sep: AnyStr = None, limit=1000): # No def munge(input: AnyStr=None): def munge(input:AnyStr): def munge(input: AnyStr)->PosInt: 通常不推荐复合语句(Compound statements: 多条语句写在同一行)。 # Yes if foo == 'blah': do_blah_thing() do_one() do_two() do_three() # No if foo == 'blah': do_blah_thing() do_one(); do_two(); do_three() 尽管有时可以在if/for/while 的同一行跟一小段代码,但绝不要跟多个子句,并尽量避免换行。 # No if foo == 'blah': do_blah_thing() for x in lst: total += x while t < 10: t = delay() 更不是: # No if foo == 'blah': do_blah_thing() else: do_non_blah_thing() try: something() finally: cleanup() do_one(); do_two(); do_three(long, argument, list, like, this) if foo == 'blah': one(); two(); three() 注释 与代码自相矛盾的注释比没注释更差。修改代码时要优先更新注释! 注释是完整的句子。如果注释是断句,首字母应该大写,除非它是小写字母开头的标识符(永远不要修改标识符的大小写)。 如果注释很短,可以省略末尾的句号。注释块通常由一个或多个段落组成。段落由完整的句子构成且每个句子应该以点号(后面要有两个空格)结束,并注意断词和空格。 非英语国家的程序员请用英语书写你的注释,除非你120%确信代码永远不会被不懂你的语言的人阅读。 注释块 注释块通常应用在代码前,并和这些代码有同样的缩进。每行以 '# '(除非它是注释内的缩进文本,注意#后面有空格)。 注释块内的段落用仅包含单个 '#' 的行分割。 行内注释 慎用行内注释(Inline Comments) 节俭使用行内注释。 行内注释是和语句在同一行,至少用两个空格和语句分开。行内注释不是必需的,重复罗嗦会使人分心。不要这样做: x = x + 1 # Increment x 但有时很有必要: x = x + 1 # Compensate for border 文档字符串 文档字符串的标准参见:PEP 257。 为所有公共模块、函数、类和方法书写文档字符串。非公开方法不一定有文档字符串,建议有注释(出现在 def 行之后)来描述这个方法做什么。 更多参考:PEP 257 文档字符串约定。注意结尾的 """ 应该单独成行,例如: """Return a foobang Optional plotz says to frobnicate the bizbaz first. """ 单行的文档字符串,结尾的 """ 在同一行。 版本标签 版本注记 (Version Bookkeeping) 如果你必须在源文件中包含git、Subversion、CVS或RCS crud信息,放置在模块的文档字符串之后,任何其他代码之前,上下各用一个空行: __version__ = "$Revision$"# $Source$ 命名约定 Python库的命名约定有点混乱,不可能完全一致。但依然有些普遍推荐的命名规范的。新的模块和包 (包括第三方的框架) 应该遵循这些标准。对不同风格的已有的库,建议保持内部的一致性。 最重要的原则 用户可见的API命名应遵循使用约定而不是实现。 描述:命名风格 有多种命名风格: b(单个小写字母) B(单个大写字母) lowercase(小写串) lower_case_with_underscores(带下划线的小写) UPPERCASE(大写串) UPPER_CASE_WITH_UNDERSCORES(带下划线的大写串) CapitalizedWords(首字母大写的单词串或驼峰缩写) 注意: 使用大写缩写时,缩写使用大写字母更好。故 HTTPServerError 比 HttpServerError 更好。 mixedCase(混合大小写,第一个单词是小写) Capitalized_Words_With_Underscores(带下划线,首字母大写,丑陋) 还有一种风格使用短前缀分组名字。这在Python中不常用, 但出于完整性提一下。例如,os.stat()返回的元组有st_mode, st_size, st_mtime等等这样的名字(与POSIX系统调用结构体一致)。 X11库的所有公开函数以X开头, Python中通常认为是不必要的,因为属性和方法名有对象作前缀,而函数名有模块名为前缀。 下面讲述首尾有下划线的情况: _single_leading_underscore:(单前置下划线): 弱内部使用标志。 例如"from M import " 不会导入以下划线开头的对象。 single_trailing_underscore_(单后置下划线): 用于避免与 Python关键词的冲突。 例如: Tkinter.Toplevel(master, class_='ClassName') __double_leading_underscore(双前置下划线): 当用于命名类属性,会触发名字重整。 (在类FooBar中,__boo变成 _FooBar__boo)。 __double_leading_and_trailing_underscore__(双前后下划线):用户名字空间的魔法对象或属性。例如:__init__ , __import__ or __file__,不要自己发明这样的名字。 命名约定规范 避免采用的名字 决不要用字符'l'(小写字母el),'O'(大写字母oh),或 'I'(大写字母eye) 作为单个字符的变量名。一些字体中,这些字符不能与数字1和0区别。用'L' 代替'l'时。 包和模块名 模块名要简短,全部用小写字母,可使用下划线以提高可读性。包名和模块名类似,但不推荐使用下划线。 模块名对应到文件名,有些文件系统不区分大小写且截短长名字,在 Unix上不是问题,但当把代码迁移到 Mac、Windows 或 DOS 上时,就可能是个问题。当然随着系统的演进,这个问题已经不是经常出现。 另外有些模块底层用C或C++ 书写,并有对应的高层Python模块,C/C++模块名有一个前置下划线 (如:_socket)。 类名 遵循CapWord。 接口需要文档化并且可以调用时,可能使用函数的命名规则。 注意大部分内置的名字是单个单词(或两个),CapWord只适用于异常名称和内置的常量。 异常名 如果确实是错误,需要在类名添加后缀 "Error"。 全局变量名 变量尽量只用于模块内部,约定类似函数。 对设计为通过 "from M import " 来使用的模块,应采用 __all__ 机制来防止导入全局变量;或者为全局变量加一个前置下划线。 函数名 函数名应该为小写,必要时可用下划线分隔单词以增加可读性。 mixedCase(混合大小写)仅被允许用于兼容性考虑(如: threading.py)。 函数和方法的参数 实例方法第一个参数是 'self'。 类方法第一个参数是 'cls'。 如果函数的参数名与保留关键字冲突,通常在参数名后加一个下划线。 方法名和实例变量 同函数命名规则。 非公开方法和实例变量增加一个前置下划线。 为避免与子类命名冲突,采用两个前置下划线来触发重整。类Foo属性名为__a, 不能以 Foo.__a访问。(执著的用户还是可以通过Foo._Foo__a。) 通常双前置下划线仅被用来避免与基类的属性发生命名冲突。 常量 常量通常在模块级定义,由大写字母用下划线分隔组成。比如括MAX_OVERFLOW和TOTAL。 继承设计 考虑类的方法和实例变量(统称为属性)是否公开。如果有疑问,选择不公开;把其改为公开比把公开属性改为非公开要容易。 公开属性可供所有人使用,并通常向后兼容。非公开属性不给第三方使用、可变甚至被移除。 这里不使用术语"private", Python中没有属性是真正私有的。 另一类属性是子类API(在其他语言中通常称为 "protected")。 一些类被设计为基类,可以扩展和修改。 谨记这些Python指南: 公开属性应该没有前导下划线。 如果公开属性名和保留关键字冲突,可以添加后置下划线 简单的公开数据属性,最好只公开属性名,没有复杂的访问/修改方法,python的Property提供了很好的封装方法。 d.如果不希望子类使用的属性,考虑用两个前置下划线(没有后置下划线)命名。 公共和内部接口 任何向后兼容的保证只适用于公共接口。 文档化的接口通常是公共的,除非明说明是临时的或为内部接口、其他所有接口默认是内部的。 为了更好地支持内省,模块要在__all__属性列出公共API。 内部接口要有前置下划线。 如果命名空间(包、模块或类)是内部的,里面的接口也是内部的。 导入名称应视为实现细节。其他模块不能间接访名字,除非在模块的API文档中明确记载,如os.path中或包的__init__暴露了子模块。 编程建议 考虑多种Python实现(PyPy, Jython, IronPython,Pyrex, Psyco, 等等)。 例如,CPython对a+=b或a=a+b等语句有高效的实现,但在Jython中运行很慢,尽量改用_.join()。_ None比较用'is'或'is not',不要用等号。 注意"if x is not None" 与"if x" 的区别。 用"is not"代替"not ... is"。前者的可读性更好。 # Yes if foo is not None # No if not foo is None 使用基于类的异常。 比较排序操作最好是实现所有六个操作,而不是代码中实现比较逻辑。functools.total_ordering()装饰符可以生成缺失的比较方法。 __eq__,__ne__,__lt__,__lt__,__gt__,____) PEP207 比较标准表明反射规则由Python完成。因此解释器可能会交换参数的位置,比如替换y > x为x < y,所以有必要实现这5种方法。 使用函数定义def代替lambda赋值给标识符: # Yes def f(x): return 2*x # No f = lambda x: 2*x 前者更适合回调和字符串表示。 异常类继承自Exception,而不是BaseException。 源于异常,而不是BaseException例外。从BaseException直接继承的例外情况追赶他们几乎总是错误的事情做保留。 要设计基于层次的异常,捕捉到需要的异常,而不是异常引发的位置。能回答:“出了什么问题?”,而不是仅仅指出“问题发生”(更多参考:PEP3151 重构OS和IO异常层次) 适当使用异常链。在Python3中"raise X from Y"明确表示更换且保留了原来的traceback。 替换内部异常(在Python2: "raise X"或"raise X from None")时,确保相关细节转移到新的异常(如转换KeyError为AttributeError保存属性名,或在新的异常中嵌入原始异常)。 Python2中用" raise ValueError('message')"代替"raise ValueError, 'message'" 后者不兼容Python3语法。前者续行方便。 捕获异常时尽量指明具体异常,而不是空"except:"子句。比如: # Yes try: import platform_specific_module except ImportError: platform_specific_module = None 空"except:"子句(相当于except Exception)会捕捉SystemExit和KeyboardInterrupt异常,难以用Control-C中断程序,并可掩盖其他问题。如果 你捕捉信号错误之外所有的异常,使用"except Exception"。 空"except:"子句适用的情况两种情况: a, 打印出或记录了traceback,至少让用户将知道已发生错误。 b, 代码需要做一些清理工作,并用 raise转发了异常。这样try...finally可以捕捉到它。 Python 2.6以后建议用as显示绑定异常名: # Yes try: process_data() except Exception as exc: raise DataProcessingFailedError(str(exc)) 这样才能兼容Python3语法并避免歧义。 捕捉操作系统错误时,建议使用Python 3.3引入显式异常层次,支持内省errno值。 此外所有try/except子句的代码要尽可的少,以免屏蔽其他的错误。 # Yes try: value = collection[key] except KeyError: return key_not_found(key) else: return handle_value(value) # No try: # 太泛了! return handle_value(collection[key]) except KeyError: # 会捕捉到handle_value()中的KeyError return key_not_found(key) 本地资源建议使用with语句,以确保即时清理。当然try / finally语句也是可以接受的。 上下文管理器在做获取和释放资源之外的事情时,应通过独立的函数或方法。例如: # Yes with conn.begin_transaction(): do_stuff_in_transaction(conn) # No with conn: do_stuff_in_transaction(conn) 后者指明enter和exit方法。 函数或者方法在没有返回时要明确返回None。 # Yes def foo(x): if x >= 0: return math.sqrt(x) else: return Nonedef bar(x): if x < 0: return None return math.sqrt(x)# Nodef foo(x): if x >= 0: return math.sqrt(x)def bar(x): if x < 0: return return math.sqrt(x) 使用字符串方法而不是string模块。 python 2.0以后字符串方法总是更快,且Unicode字符串相同的API。 使用使用 _.startswith()和_.endswith()代替字符串切片来检查前缀和后缀。and startswith()和endswith更简洁,利于减少错误。例如: # Yes if foo.startswith('bar'): # No if foo[:3] == 'bar': 使用isinstance()代替对象类型的比较: # Yes if isinstance(obj, int): # No if type(obj) is type(1): 检查是否是字符串时,注意Python 2中str和unicode有公共的基类: if isinstance(obj, basestring): 在 Python 2.2 中,types 模块为此定义了 StringTypes 类型,例如: # Yes if isinstance(obj, basestring): Python3中Unicode和basestring的不再存在(只有str)和字节对象不再是字符串(是整数序列) 对序列(字符串、列表 、元组), 空序列为false: # Yes if not seq: pass if seq: pass # No if len(seq): pass if not len(seq): pass 字符串后面不要有大量拖尾空格。 不要用 == 进行布尔比较 # Yes if greeting:: pass # No if greeting == True pass if greeting is True: # Worse pass Python标准库不使用的功能注释,这块有待用户去发现和体验有用的注释风格。下面有些第三方的建议(略)。 参考资料 紧张整理更新中,讨论 钉钉免费群21745728 qq群144081101 567351477 本文涉及的python测试开发库 谢谢点赞! 本文相关书籍下载 2018最佳12个开源或免费web服务器和客户端性能测试工具 本文最新版本地址 PEP 8 - Style Guide for Python Code

优秀的个人博客,低调大师

[雪峰磁针石博客]使用python3和flask构建RESTful API(接口测试服务)

引言 构建RESTful API貌似是开发的工作,和测试有和关系? 其实测试开发需要构建RESTful API的场景很多。比如测试Android应用,一般的接口测试只考虑了服务器端,至于客户端在网络异常或者服务端异常时如何反应,多数天朝的测试人员是没有考虑到的。客户端在对这些异常处理不够充分的时候,会出现崩溃等各种莫名其妙的问题。 为此一些走在前沿的测试人员会自己写一些RESTful API, 把服务端的域名劫持到自己的API,故意返回各种异常,看客户端的稳定性。 另外测试开发的测试工具需要和其他系统对接等场景也经常需要API。 参考资料 本文源码地址 本文相关书籍下载 讨论 钉钉免费群21745728 qq群144081101 567351477 本文涉及的python测试开发库 谢谢点赞! How to Build RESTful APIs with Python and Flask 术语 REST: REpresentational State Transfer 目标 GET - /api/Category - Retrieve all categories POST - /api/Category - Add a new category PUT - /api/Category - Update a category DELETE - /api/Category - Delete a category GET - /api/Comment - Retrieve all the stored comments POST - /api/Comment - Add new comment 要求 python3.* PostgreSQL 工程目录 #!python project/ ├── app.py ├── config.py ├── migrate.py ├── Model.py ├── requirements.txt ├── resources │ └── Hello.py │ └── Comment.py │ └── Category.py └── run.py requirements.txt的内容如下: #!python flask flask_restful flask_script flask_migrate marshmallow flask_sqlalchemy flask_marshmallow marshmallow-sqlalchemy psycopg2 flask - Python的微框架 flask_restful - 这是Flask的扩展,可快速构建REST API。 flask_script - 提供了在Flask中编写外部脚本的支持。 flask_migrate - 使用Alembic的Flask应用进行SQLAlchemy数据库迁移。 marshmallow - ORM/ODM/框架无关的库,用于复杂数据类型(如对象)和Python数据类型转换。 flask_sqlalchemy - Flask扩展,增加了对SQLAlchemy的支持。 flask_marshmallow - 这是Flask和marshmallow的中间层。 marshmallow-sqlalchemy - 这是sqlalchemy和marshmallow的中间层。 psycopg - Python的PostgreSQL API。 安装依赖 #!python # pip3 install -r requirements.txt 安装配置PostgreSQL 这里以 Ubuntu 16.04为例: #!python # sudo apt-get update && sudo apt-get upgrade # apt-get install postgresql postgresql-contrib # su - postgres $ createdb api $ createuser andrew --pwprompt #创建用户 $ psql -d api -c "ALTER USER andrew WITH PASSWORD 'api';" 参考资料: How to Install PostgreSQL on Ubuntu 16.04 How To Install and Use PostgreSQL on Ubuntu 14.04 配置 #!python # -*- coding: utf-8 -*- # Author: xurongzhong#126.com wechat:pythontesting qq:37391319 # CreateDate: 2018-1-10 from flask import Blueprint from flask_restful import Api from resources.Hello import Hello from resources.Category import CategoryResource from resources.Comment import CommentResource api_bp = Blueprint('api', __name__) api = Api(api_bp) # Routes api.add_resource(Hello, '/Hello') api.add_resource(CategoryResource, '/Category') api.add_resource(CommentResource, '/Comment') 快速入门 app.py #!python from flask import Blueprint from flask_restful import Api from resources.Hello import Hello api_bp = Blueprint('api', __name__) api = Api(api_bp) # Route api.add_resource(Hello, '/Hello') resource/Hello.py #!python #!/usr/bin/python # -*- coding: utf-8 -*- # Author: xurongzhong#126.com wechat:pythontesting qq:37391319 # CreateDate: 2018-1-10 from flask_restful import Resource class Hello(Resource): def get(self): return {"message": "Hello, World!"} def post(self): return {"message": "Hello, World!"} run.py #!python from flask import Flask def create_app(config_filename): app = Flask(__name__) app.config.from_object(config_filename) from app import api_bp app.register_blueprint(api_bp, url_prefix='/api') return app if __name__ == "__main__": app = create_app("config") app.run(debug=True) 启动服务 #!python $ python3 run.py * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit) * Restarting with stat * Debugger is active! * Debugger PIN: 136-695-873 用浏览器访问: http://127.0.0.1:5000/api/Hello #!python { "hello": "world" } 接入数据库 #!python from flask import Flask from marshmallow import Schema, fields, pre_load, validate from flask_marshmallow import Marshmallow from flask_sqlalchemy import SQLAlchemy ma = Marshmallow() db = SQLAlchemy() class Comment(db.Model): __tablename__ = 'comments' id = db.Column(db.Integer, primary_key=True) comment = db.Column(db.String(250), nullable=False) creation_date = db.Column(db.TIMESTAMP, server_default=db.func.current_timestamp(), nullable=False) category_id = db.Column(db.Integer, db.ForeignKey('categories.id', ondelete='CASCADE'), nullable=False) category = db.relationship('Category', backref=db.backref('comments', lazy='dynamic' )) def __init__(self, comment, category_id): self.comment = comment self.category_id = category_id class Category(db.Model): __tablename__ = 'categories' id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(150), unique=True, nullable=False) def __init__(self, name): self.name = name class CategorySchema(ma.Schema): id = fields.Integer() name = fields.String(required=True) class CommentSchema(ma.Schema): id = fields.Integer(dump_only=True) category_id = fields.Integer(required=True) comment = fields.String(required=True, validate=validate.Length(1)) creation_date = fields.DateTime() migrate.py #!python from flask_script import Manager from flask_migrate import Migrate, MigrateCommand from Model import db from run import create_app app = create_app('config') migrate = Migrate(app, db) manager = Manager(app) manager.add_command('db', MigrateCommand) if __name__ == '__main__': manager.run() 数据迁移 #!python $ python3 migrate.py db init $ python3 migrate.py db migrate $ python migrate.py db upgrade 修改Category.py 和Comment.py, 完整代码 测试 可以使用curl,比如: #!python curl http://127.0.0.1:5000/api/Category --data '{"name":"test5","id":5}' -H "Content-Type: application/json" 也可以在chrome中使用postman: how_to_build_restful_apis_using_flask_creating_categories.png how_to_build_restful_apis_using_flask_listing_categories.png how_to_build_restful_apis_using_flask_creating_comment.png how_to_build_restful_apis_in_flask_listing_comments.png

资源下载

更多资源
Mario

Mario

马里奥是站在游戏界顶峰的超人气多面角色。马里奥靠吃蘑菇成长,特征是大鼻子、头戴帽子、身穿背带裤,还留着胡子。与他的双胞胎兄弟路易基一起,长年担任任天堂的招牌角色。

Spring

Spring

Spring框架(Spring Framework)是由Rod Johnson于2002年提出的开源Java企业级应用框架,旨在通过使用JavaBean替代传统EJB实现方式降低企业级编程开发的复杂性。该框架基于简单性、可测试性和松耦合性设计理念,提供核心容器、应用上下文、数据访问集成等模块,支持整合Hibernate、Struts等第三方框架,其适用范围不仅限于服务器端开发,绝大多数Java应用均可从中受益。

Rocky Linux

Rocky Linux

Rocky Linux(中文名:洛基)是由Gregory Kurtzer于2020年12月发起的企业级Linux发行版,作为CentOS稳定版停止维护后与RHEL(Red Hat Enterprise Linux)完全兼容的开源替代方案,由社区拥有并管理,支持x86_64、aarch64等架构。其通过重新编译RHEL源代码提供长期稳定性,采用模块化包装和SELinux安全架构,默认包含GNOME桌面环境及XFS文件系统,支持十年生命周期更新。

Sublime Text

Sublime Text

Sublime Text具有漂亮的用户界面和强大的功能,例如代码缩略图,Python的插件,代码段等。还可自定义键绑定,菜单和工具栏。Sublime Text 的主要功能包括:拼写检查,书签,完整的 Python API , Goto 功能,即时项目切换,多选择,多窗口等等。Sublime Text 是一个跨平台的编辑器,同时支持Windows、Linux、Mac OS X等操作系统。

用户登录
用户注册