首页 文章 精选 留言 我的

精选列表

搜索[个人博客],共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

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

[雪峰磁针石博客]机器学习工具pytorch中文英文工具书籍下载-持续更新

书籍 深度学习之PyTorch实战计算机视觉 - 2018.pdf 计算机视觉、自然语言处理和语音识别是目前深度学习领域很热门的三大应用方向,本书旨在帮助零基础或基础较为薄弱的读者入门深度学习,达到能够独立使用深度学习知识处理计算机视觉问题的水平。通过阅读本书,读者将学到人工智能的基础概念及Python编程技能,掌握PyTorch的使用方法,学到深度学习相关的理论知识,比如卷积神经网络、循环神经网络、自动编码器,等等。在掌握深度学习理论和编程技能之后,读者还会学到如何基于PyTorch深度学习框架实战计算机视觉。本书中的大量实例可让读者在循序渐进地学习的同时,不断地获得成就感。本书面向对深度学习技术感兴趣、但是相关基础知识较为薄弱或者零基础的读者。 深度学习之Pytorch - 2017.pdf 深度学习如今已经成为了科技领域最炙手可热的技术,在本书中,我们将帮助你入门深度学习的领域。本书将从人工智能的介绍入手,了解机器学习和深度学习的基础理论,并学习如何用PyTorch框架对模型进行搭建。通过阅读本书,你将会学习到机器学习中的线性回归和logistic回归,深度学习的优化方法,多层全连接神经网络,卷积神经网络,循环神经网络以及生成对抗网络,同时从零开始对PyTorch进行学习,了解PyTorch基础及如何用其进行模型的搭建,最后通过实战了解最前沿的研究成果和PyTorch在实际项目中的应用。 PyTorch深度学习实战 - 2017.pdf Deep Learning with PyTorch - 2018.pdf Deep Learning Toolkits II pytorch example - 2017.pdf 参考资料 讨论qq群144081101 591302926 567351477 钉钉免费群21745728 本文最新版本地址 本文涉及的python测试开发库 谢谢点赞! 本文相关海量书籍下载 在线文档 官方教程:https://pytorch.org/tutorials/ 中文文档:https://pytorch-cn.readthedocs.io/zh/latest/ 英文文档:https://pytorch.org/docs/stable/index.html 论坛: https://discuss.pytorch.org/ 很棒的第三方教程 https://github.com/yunjey/pytorch-tutorial https://github.com/carpedm20/DiscoGAN-pytorch PyTorch implementation of "Learning to Discover Cross-Domain Relations with Generative Adversarial Networks" 实例: https://github.com/pytorch/examples https://github.com/bharathgs/Awesome-pytorch-list https://www.analyticsvidhya.com/blog/2018/02/pytorch-tutorial

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

[雪峰磁针石博客]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测试开发库 谢谢点赞! 本文代码地址

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

[雪峰磁针石博客]使用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

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

腾讯云软件源

腾讯云软件源

为解决软件依赖安装时官方源访问速度慢的问题,腾讯云为一些软件搭建了缓存服务。您可以通过使用腾讯云软件源站来提升依赖包的安装速度。为了方便用户自由搭建服务架构,目前腾讯云软件源站支持公网访问和内网访问。

Sublime Text

Sublime Text

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

WebStorm

WebStorm

WebStorm 是jetbrains公司旗下一款JavaScript 开发工具。目前已经被广大中国JS开发者誉为“Web前端开发神器”、“最强大的HTML5编辑器”、“最智能的JavaScript IDE”等。与IntelliJ IDEA同源,继承了IntelliJ IDEA强大的JS部分的功能。

用户登录
用户注册