{"id":21,"date":"2025-08-02T22:15:39","date_gmt":"2025-08-02T14:15:39","guid":{"rendered":"https:\/\/22z.top\/?p=21"},"modified":"2025-08-02T22:15:40","modified_gmt":"2025-08-02T14:15:40","slug":"marshmallow%e5%9f%ba%e7%a1%80%e4%bd%bf%e7%94%a8","status":"publish","type":"post","link":"https:\/\/22z.top\/?p=21","title":{"rendered":"Marshmallow\u57fa\u7840\u4f7f\u7528"},"content":{"rendered":"\n<h1 class=\"wp-block-heading\">\u5b98\u65b9\u6587\u6863\uff1a<a href=\"https:\/\/marshmallow.readthedocs.io\/en\/latest\/\">https:\/\/marshmallow.readthedocs.io\/en\/latest\/<\/a><\/h1>\n\n\n\n<p>Marshmallow\uff0c\u4e2d\u6587\u8bd1\u4f5c\uff1a\u68c9\u82b1\u7cd6\u3002\u662f\u4e00\u4e2a\u8f7b\u91cf\u7ea7\u7684\u6570\u636e\u683c\u5f0f\u8f6c\u6362\u7684\u6a21\u5757\uff0c\u4e5f\u53eb\u5e8f\u5217\u5316\u548c\u53cd\u5e8f\u5217\u5316\u6a21\u5757\uff0c\u5e38\u7528\u4e8e\u5c06\u590d\u6742\u7684orm\u6a21\u578b\u5bf9\u8c61\u4e0epython\u539f\u751f\u6570\u636e\u7c7b\u578b\u4e4b\u95f4\u76f8\u4e92\u8f6c\u6362\u3002marshmallow\u63d0\u4f9b\u4e86\u4e30\u5bcc\u7684api\u529f\u80fd\u3002\u5982\u4e0b\uff1a<\/p>\n\n\n\n<blockquote class=\"wp-block-quote is-layout-flow wp-block-quote-is-layout-flow\">\n<ol class=\"wp-block-list\">\n<li><strong>Serializing<\/strong>\u5e8f\u5217\u5316[\u53ef\u4ee5\u628a\u6570\u636e\u5bf9\u8c61\u8f6c\u5316\u4e3a\u53ef\u5b58\u50a8\u6216\u53ef\u4f20\u8f93\u7684\u6570\u636e\u7c7b\u578b\uff0c\u4f8b\u5982\uff1aobjects\/object->list\/dict\uff0cdict\/list->string]<\/li>\n\n\n\n<li><strong>Deserializing<\/strong>\u53cd\u5e8f\u5217\u5316\u5668[\u628a\u53ef\u5b58\u50a8\u6216\u53ef\u4f20\u8f93\u7684\u6570\u636e\u7c7b\u578b\u8f6c\u6362\u6210\u6570\u636e\u5bf9\u8c61\uff0c\u4f8b\u5982\uff1alist\/dict->objects\/object\uff0cstring->dict\/list]<\/li>\n\n\n\n<li><strong>Validation<\/strong>\u6570\u636e\u6821\u9a8c\uff0c\u53ef\u4ee5\u5728\u53cd\u5e8f\u5217\u5316\u9636\u6bb5\uff0c\u9488\u5bf9\u8981\u8f6c\u6362\u6570\u636e\u7684\u5185\u5bb9\u8fdb\u884c\u7c7b\u578b\u9a8c\u8bc1\u6216\u81ea\u5b9a\u4e49\u9a8c\u8bc1\u3002<\/li>\n<\/ol>\n<\/blockquote>\n\n\n\n<p>Marshmallow\u672c\u8eab\u662f\u4e00\u4e2a\u5355\u72ec\u7684\u5e93\uff0c\u57fa\u4e8e\u6211\u4eec\u5f53\u524d\u9879\u76ee\u4f7f\u7528\u6846\u67b6\u662fflask\u5e76\u4e14\u6570\u636e\u5e93ORM\u6846\u67b6\u4f7f\u7528SQLAlchemy\uff0c\u6240\u4ee5\u6211\u4eec\u53ef\u4ee5\u901a\u8fc7\u5b89\u88c5flask-sqlalchemy\u548cmarshmallow-sqlalchemy\u96c6\u6210\u5230\u9879\u76ee\u5c31\u53ef\u4ee5\u4e86\u3002<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">\u57fa\u672c\u5b89\u88c5\u548c\u914d\u7f6e<\/h2>\n\n\n\n<p>\u6a21\u5757\u5b89\u88c5\uff1a<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">pip install -U marshmallow-sqlalchemy<br>pip install -U flask-sqlalchemy<br>pip install -U flask-marshmallow<\/pre>\n\n\n\n<p>Marshmallow\u6a21\u5757\u5feb\u901f\u4f7f\u7528\uff0c\u6211\u4eec\u5355\u72ec\u521b\u5efa\u4e00\u4e2apython\u6587\u4ef6\u8fdb\u884c\u57fa\u672c\u7684\u4f7f\u7528\uff0cdocs\/main.py\uff1a<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">from datetime import datetime<br>\u200b<br>from flask import Flask<br>from flask_sqlalchemy import SQLAlchemy<br>from flask_marshmallow import Marshmallow<br>\u200b<br>\u200b<br>app = Flask(__name__)<br>app.config[\"DEBUG\"] = True<br>app.config[\"SQLALCHEMY_DATABASE_URI\"]=\"mysql:\/\/root:123@127.0.0.1:3306\/mofang?charset=utf8mb4\"<br>app.config[\"SQLALCHEMY_TRACK_MODIFICATIONS\"] = False<br>\u200b<br>db = SQLAlchemy()<br>db.init_app(app)<br>\u200b<br>ma = Marshmallow()<br>ma.init_app(app)<br>\u200b<br>\u200b<br>class User(db.Model):<br> &nbsp; &nbsp;__tablename__ = \"tb_user\"<br> &nbsp; &nbsp;id = db.Column(db.Integer, primary_key=True, comment=\"\u4e3b\u952eID\")<br> &nbsp; &nbsp;username = db.Column(db.String(255), index=True, comment=\"\u7528\u6237\u540d\")<br> &nbsp; &nbsp;password = db.Column(db.String(255), comment=\"\u767b\u5f55\u5bc6\u7801\")<br> &nbsp; &nbsp;mobile = db.Column(db.String(15), index=True, comment=\"\u624b\u673a\u53f7\u7801\")<br> &nbsp; &nbsp;sex = db.Column(db.Boolean, default=True, comment=\"\u6027\u522b\")<br> &nbsp; &nbsp;email = db.Column(db.String(255), index=True, comment=\"\u90ae\u7bb1\")<br> &nbsp; &nbsp;created_time = db.Column(db.DateTime, default=datetime.now, comment=\"\u521b\u5efa\u65f6\u95f4\")<br> &nbsp; &nbsp;updated_time = db.Column(db.DateTime, default=datetime.now, onupdate=datetime.now, comment=\"\u66f4\u65b0\u65f6\u95f4\")<br>\u200b<br> &nbsp; &nbsp;def __repr__(self):<br> &nbsp; &nbsp; &nbsp; &nbsp;return \"&lt;%s: %s&gt;\" % (self.__class__.name,self.username)<br>\u200b<br>\u200b<br>@app.route(\"\/\")<br>def index():<br> &nbsp; &nbsp;return \"ok\"<br>\u200b<br>\u200b<br>if __name__ == '__main__':<br> &nbsp; &nbsp;with app.app_context():<br> &nbsp; &nbsp; &nbsp; &nbsp;db.create_all()<br> &nbsp; &nbsp;app.run(debug=True,port=5555)<\/pre>\n\n\n\n<h2 class=\"wp-block-heading\">\u57fa\u672c\u6784\u9020\u5668(Schema)<\/h2>\n\n\n\n<p>\u4e5f\u53ef\u4ee5\u53eb\u57fa\u672c\u6a21\u5f0f\u7c7b\u6216\u57fa\u672c\u5e8f\u5217\u5316\u5668\u7c7b\u3002<\/p>\n\n\n\n<p>marshmallow\u8f6c\u6362\u6570\u636e\u683c\u5f0f\u4e3b\u8981\u901a\u8fc7\u6784\u9020\u5668\u7c7b\uff08\u5e8f\u5217\u5316\u5668\uff09\u6765\u5b8c\u6210\u3002\u5728marshmallow\u4f7f\u7528\u8fc7\u7a0b\u4e2d\u6240\u6709\u7684\u6784\u9020\u5668\u7c7b\u5fc5\u987b\u76f4\u63a5\u6216\u95f4\u63a5\u7ee7\u627f\u4e8eSchema\u57fa\u7c7b\uff0c\u800cSchema\u57fa\u7c7b\u63d0\u4f9b\u4e86\u6570\u636e\u8f6c\u6362\u7684\u57fa\u672c\u529f\u80fd\uff1a\u5e8f\u5217\u5316\uff0c\u9a8c\u8bc1\u6570\u636e\u548c\u53cd\u5e8f\u5217\u5316\u3002<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">\u57fa\u4e8eSchema\u5b8c\u6210\u6570\u636e\u5e8f\u5217\u5316\u8f6c\u6362<\/h3>\n\n\n\n<pre class=\"wp-block-preformatted\">from datetime import datetime<br>\u200b<br>from flask import Flask<br>from flask_sqlalchemy import SQLAlchemy<br>from flask_marshmallow import Marshmallow<br>\u200b<br>app = Flask(__name__)<br>app.config[\"DEBUG\"] = True<br>app.config[\"SQLALCHEMY_DATABASE_URI\"]=\"mysql:\/\/root:123@127.0.0.1:3306\/yingming?charset=utf8mb4\"<br>app.config[\"SQLALCHEMY_TRACK_MODIFICATIONS\"] = False<br>app.config[\"SQLALCHEMY_ECHO\"] = True<br>\u200b<br>db = SQLAlchemy()<br>db.init_app(app)<br>\u200b<br>ma = Marshmallow()<br>ma.init_app(app)<br>\u200b<br>\u200b<br>\"\"\"\u6a21\u578b\"\"\"<br>class User(db.Model):<br> &nbsp; &nbsp;__tablename__ = \"desc_user\"<br> &nbsp; &nbsp;id = db.Column(db.Integer, primary_key=True, comment=\"\u4e3b\u952eID\")<br> &nbsp; &nbsp;username = db.Column(db.String(255), index=True, comment=\"\u7528\u6237\u540d\")<br> &nbsp; &nbsp;password = db.Column(db.String(255), comment=\"\u767b\u5f55\u5bc6\u7801\")<br> &nbsp; &nbsp;mobile = db.Column(db.String(15), index=True, comment=\"\u624b\u673a\u53f7\u7801\")<br> &nbsp; &nbsp;sex = db.Column(db.Boolean, default=True, comment=\"\u6027\u522b\")<br> &nbsp; &nbsp;email = db.Column(db.String(255), index=True, comment=\"\u90ae\u7bb1\")<br> &nbsp; &nbsp;created_time = db.Column(db.DateTime, default=datetime.now, comment=\"\u521b\u5efa\u65f6\u95f4\")<br> &nbsp; &nbsp;updated_time = db.Column(db.DateTime, default=datetime.now, onupdate=datetime.now, comment=\"\u66f4\u65b0\u65f6\u95f4\")<br>\u200b<br> &nbsp; &nbsp;def __repr__(self):<br> &nbsp; &nbsp; &nbsp; &nbsp;return \"&lt;%s: %s&gt;\" % (self.__class__.__name__, self.username)<br>\u200b<br>\u200b<br>\"\"\"\u5e8f\u5217\u5316\u5668\"\"\"<br>\u200b<br>from marshmallow import Schema, fields<br>\u200b<br>\u200b<br>class UserSchema(Schema):<br> &nbsp; &nbsp;username = fields.String()<br> &nbsp; &nbsp;mobile = fields.String()<br> &nbsp; &nbsp;sex = fields.Boolean()<br> &nbsp; &nbsp;email = fields.Email()<br> &nbsp; &nbsp;created_time = fields.DateTime()<br> &nbsp; &nbsp;updated_time = fields.DateTime()<br>\u200b<br>\u200b<br>\u200b<br>@app.route(\"\/1\")<br>def index1():<br> &nbsp; &nbsp;\"\"\"\u5e8f\u5217\u5316\u4e00\u4e2a\u5bf9\u8c61\u6210\u5b57\u5178\u6216\u5b57\u7b26\u4e32\"\"\"<br> &nbsp; &nbsp;# \u6a21\u62df\u4ece\u6570\u636e\u5e93\u4e2d\u8bfb\u53d6\u51fa\u6765\u7684\u6a21\u578b\u7c7b<br> &nbsp; &nbsp;user = User(<br> &nbsp; &nbsp; &nbsp; &nbsp;username=\"xiaoming\",<br> &nbsp; &nbsp; &nbsp; &nbsp;mobile=\"13312345677\",<br> &nbsp; &nbsp; &nbsp; &nbsp;sex=True,<br> &nbsp; &nbsp; &nbsp; &nbsp;email=\"133123456@qq.com\",<br> &nbsp; &nbsp; &nbsp; &nbsp;created_time=datetime.now(),<br> &nbsp; &nbsp; &nbsp; &nbsp;updated_time=datetime.now()<br> &nbsp;  )<br>\u200b<br> &nbsp; &nbsp;db.session.add(user)<br> &nbsp; &nbsp;db.session.commit()<br> &nbsp; &nbsp;print(user)<br>\u200b<br> &nbsp; &nbsp;# \u5e8f\u5217\u5316\u6210\u4e00\u4e2a\u5b57\u5178<br> &nbsp; &nbsp;us = UserSchema()<br> &nbsp; &nbsp;result = us.dump(user)<br> &nbsp; &nbsp;print(result, type(result))<br>\u200b<br> &nbsp; &nbsp;# \u5e8f\u5217\u5316\u5668\u6210\u4e00\u4e2a\u5b57\u7b26\u4e32[\u7b26\u5408json\u8bed\u6cd5]<br> &nbsp; &nbsp;result = us.dumps(user)<br> &nbsp; &nbsp;print(result, type(result))<br>\u200b<br> &nbsp; &nbsp;# \u5982\u679c\u8981\u5e8f\u5217\u5316\u591a\u4e2a\u6a21\u578b\u5bf9\u8c61\uff0c\u53ef\u4ee5\u4f7f\u7528many=True<br> &nbsp; &nbsp;result = us.dump([user,user,user], many=True)<br> &nbsp; &nbsp;print(result)<br> &nbsp; &nbsp;result = us.dumps([user,user,user], many=True)<br> &nbsp; &nbsp;print(result)<br> &nbsp; &nbsp;return \"ok\"<br>\u200b<br>\u200b<br>if __name__ == '__main__':<br> &nbsp; &nbsp;with app.app_context():<br> &nbsp; &nbsp; &nbsp; &nbsp;db.create_all()<br> &nbsp; &nbsp;app.run(debug=True, port=5555)<\/pre>\n\n\n\n<p><strong>schema\u5e38\u7528\u5c5e\u6027\u6570\u636e\u7c7b\u578b<\/strong><\/p>\n\n\n\n<figure class=\"wp-block-table\"><table class=\"has-fixed-layout\"><thead><tr><th>\u7c7b\u578b<\/th><th>\u63cf\u8ff0<\/th><\/tr><\/thead><tbody><tr><td>fields.<a href=\"https:\/\/marshmallow.readthedocs.io\/en\/stable\/marshmallow.fields.html#marshmallow.fields.Dict\"><code>Dict<\/code><\/a>(keys, type]] = None, values, \u2026)<\/td><td>\u5b57\u5178\u7c7b\u578b\uff0c\u5e38\u7528\u4e8e\u63a5\u6536json\u7c7b\u578b\u6570\u636e<\/td><\/tr><tr><td>fields.<a href=\"https:\/\/marshmallow.readthedocs.io\/en\/stable\/marshmallow.fields.html#marshmallow.fields.List\"><code>List<\/code><\/a>(cls_or_instance, type], **kwargs)<\/td><td>\u5217\u8868\u7c7b\u578b\uff0c\u5e38\u7528\u4e8e\u63a5\u6536\u6570\u7ec4\u6570\u636e<\/td><\/tr><tr><td>fields.<a href=\"https:\/\/marshmallow.readthedocs.io\/en\/stable\/marshmallow.fields.html#marshmallow.fields.Tuple\"><code>Tuple<\/code><\/a>(tuple_fields, *args, **kwargs)<\/td><td>\u5143\u7ec4\u7c7b\u578b<\/td><\/tr><tr><td>fields.<a href=\"https:\/\/marshmallow.readthedocs.io\/en\/stable\/marshmallow.fields.html#marshmallow.fields.String\"><code>String<\/code><\/a>(*, default, missing, data_key, \u2026)<\/td><td>\u5b57\u7b26\u4e32\u7c7b\u578b<\/td><\/tr><tr><td>fields.<a href=\"https:\/\/marshmallow.readthedocs.io\/en\/stable\/marshmallow.fields.html#marshmallow.fields.UUID\"><code>UUID<\/code><\/a>(*, default, missing, data_key, \u2026)<\/td><td>UUID\u683c\u5f0f\u7c7b\u578b\u7684\u5b57\u7b26\u4e32<\/td><\/tr><tr><td>fields.<a href=\"https:\/\/marshmallow.readthedocs.io\/en\/stable\/marshmallow.fields.html#marshmallow.fields.Number\"><code>Number<\/code><\/a>(*, as_string, **kwargs)<\/td><td>\u6570\u503c\u57fa\u672c\u7c7b\u578b<\/td><\/tr><tr><td>fields.<a href=\"https:\/\/marshmallow.readthedocs.io\/en\/stable\/marshmallow.fields.html#marshmallow.fields.Integer\"><code>Integer<\/code><\/a>(*, strict, **kwargs)<\/td><td>\u6574\u578b<\/td><\/tr><tr><td>fields.<a href=\"https:\/\/marshmallow.readthedocs.io\/en\/stable\/marshmallow.fields.html#marshmallow.fields.Decimal\"><code>Decimal<\/code><\/a>(places, rounding, *, allow_nan, \u2026)<\/td><td>\u6570\u503c\u578b<\/td><\/tr><tr><td>fields.<a href=\"https:\/\/marshmallow.readthedocs.io\/en\/stable\/marshmallow.fields.html#marshmallow.fields.Boolean\"><code>Boolean<\/code><\/a>(*, truthy, falsy, **kwargs)<\/td><td>\u5e03\u5c14\u578b<\/td><\/tr><tr><td>fields.<a href=\"https:\/\/marshmallow.readthedocs.io\/en\/stable\/marshmallow.fields.html#marshmallow.fields.Float\"><code>Float<\/code><\/a>(*, allow_nan, as_string, **kwargs)<\/td><td>\u6d6e\u70b9\u6570\u7c7b\u578b<\/td><\/tr><tr><td>fields.<a href=\"https:\/\/marshmallow.readthedocs.io\/en\/stable\/marshmallow.fields.html#marshmallow.fields.DateTime\"><code>DateTime<\/code><\/a>(format, **kwargs)<\/td><td>\u65e5\u671f\u65f6\u95f4\u7c7b\u578b<\/td><\/tr><tr><td>fields.<a href=\"https:\/\/marshmallow.readthedocs.io\/en\/stable\/marshmallow.fields.html#marshmallow.fields.Time\"><code>Time<\/code><\/a>(format, **kwargs)<\/td><td>\u65f6\u95f4\u7c7b\u578b<\/td><\/tr><tr><td>fields.<a href=\"https:\/\/marshmallow.readthedocs.io\/en\/stable\/marshmallow.fields.html#marshmallow.fields.Date\"><code>Date<\/code><\/a>(format, **kwargs)<\/td><td>\u65e5\u671f\u7c7b\u578b<\/td><\/tr><tr><td>fields.<a href=\"https:\/\/marshmallow.readthedocs.io\/en\/stable\/marshmallow.fields.html#marshmallow.fields.Url\"><code>Url<\/code><\/a>(*, relative, schemes, Set[str]]] = None, \u2026)<\/td><td>url\u7f51\u5740\u5b57\u7b26\u4e32\u7c7b\u578b\uff0c\u81ea\u5e26url\u5730\u5740\u7684\u6821\u9a8c\u89c4\u5219<\/td><\/tr><tr><td>fields.<a href=\"https:\/\/marshmallow.readthedocs.io\/en\/stable\/marshmallow.fields.html#marshmallow.fields.Email\"><code>Email<\/code><\/a>(*args, **kwargs)<\/td><td>\u90ae\u7bb1\u5b57\u7b26\u4e32\u7c7b\u578b\uff0c\u81ea\u5e26email\u5730\u5740\u7684\u6821\u9a8c\u89c4\u5219<\/td><\/tr><tr><td>fields.<a href=\"https:\/\/marshmallow.readthedocs.io\/en\/stable\/marshmallow.fields.html#marshmallow.fields.IP\"><code>IP<\/code><\/a>(*args[, exploded])<\/td><td>IP\u5730\u5740\u5b57\u7b26\u4e32\u7c7b\u578b<\/td><\/tr><tr><td>fields.<a href=\"https:\/\/marshmallow.readthedocs.io\/en\/stable\/marshmallow.fields.html#marshmallow.fields.IPv4\"><code>IPv4<\/code><\/a>(*args[, exploded])<\/td><td>IPv4\u5730\u5740\u5b57\u7b26\u4e32\u7c7b\u578b<\/td><\/tr><tr><td>fields.<a href=\"https:\/\/marshmallow.readthedocs.io\/en\/stable\/marshmallow.fields.html#marshmallow.fields.IPv6\"><code>IPv6<\/code><\/a>(*args[, exploded])<\/td><td>IPv6\u5730\u5740\u5b57\u7b26\u4e32\u7c7b\u578b<\/td><\/tr><tr><td>fields.<a href=\"https:\/\/marshmallow.readthedocs.io\/en\/stable\/marshmallow.fields.html#marshmallow.fields.Method\"><code>Method<\/code><\/a>(serialize, deserialize, **kwargs)<\/td><td>\u57fa\u4e8eSchema\u7c7b\u65b9\u6cd5\u8fd4\u56de\u503c\u7684\u5b57\u6bb5<\/td><\/tr><tr><td>fields.<a href=\"https:\/\/marshmallow.readthedocs.io\/en\/stable\/marshmallow.fields.html#marshmallow.fields.Function\"><code>Function<\/code><\/a>(serialize, Any], Callable[[Any, \u2026)<\/td><td>\u57fa\u4e8e\u51fd\u6570\u8fd4\u56de\u503c\u5f97\u5b57\u6bb5<\/td><\/tr><tr><td>fields.<a href=\"https:\/\/marshmallow.readthedocs.io\/en\/stable\/marshmallow.fields.html#marshmallow.fields.Nested\"><code>Nested<\/code><\/a>(nested, type, str, Callable[[], \u2026)<\/td><td>\u5d4c\u5957\u7c7b\u578b\u6216\u5916\u952e\u7c7b\u578b<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<p><strong>Schema\u6570\u636e\u7c7b\u578b\u7684\u5e38\u7528\u901a\u7528\u5c5e\u6027<\/strong><\/p>\n\n\n\n<figure class=\"wp-block-table\"><table class=\"has-fixed-layout\"><thead><tr><th>\u5c5e\u6027\u540d<\/th><th>\u63cf\u8ff0<\/th><\/tr><\/thead><tbody><tr><td><strong>default<\/strong><\/td><td>\u5e8f\u5217\u5316\u9636\u6bb5\u4e2d\u8bbe\u7f6e\u5b57\u6bb5\u7684\u9ed8\u8ba4\u503c<\/td><\/tr><tr><td><strong>missing<\/strong><\/td><td>\u53cd\u5e8f\u5217\u5316\u9636\u6bb5\u4e2d\u8bbe\u7f6e\u5b57\u6bb5\u7684\u9ed8\u8ba4\u503c<\/td><\/tr><tr><td><strong>validate<\/strong><\/td><td>\u53cd\u5e8f\u5217\u5316\u9636\u6bb5\u8c03\u7528\u7684\u5185\u7f6e\u6570\u636e\u9a8c\u8bc1\u5668\u6216\u8005\u5185\u7f6e\u9a8c\u8bc1\u96c6\u5408<\/td><\/tr><tr><td><strong>required<\/strong><\/td><td>\u53cd\u5e8f\u5217\u5316\u9636\u6bb5\u8c03\u7528\u7684\uff0c\u8bbe\u7f6e\u5f53\u524d\u5b57\u6bb5\u7684\u5fc5\u586b\u5b57\u6bb5<\/td><\/tr><tr><td><strong>allow_none<\/strong><\/td><td>\u53cd\u5e8f\u5217\u5316\u9636\u6bb5\u8c03\u7528\u7684\uff0c\u662f\u5426\u5141\u8bb8\u4e3a\u7a7a<\/td><\/tr><tr><td><strong>load_only<\/strong><\/td><td>\u662f\u5426\u5728\u53cd\u5e8f\u5217\u5316\u9636\u6bb5\u624d\u4f7f\u7528\u5230\u5f53\u524d\u5b57\u6bb5\uff0c\u76f8\u5f53\u4e8edrf\u6846\u67b6\u7684write_only<\/td><\/tr><tr><td><strong>dump_omly<\/strong><\/td><td>\u662f\u5426\u5728\u5e8f\u5217\u5316\u9636\u6bb5\u624d\u4f7f\u7528\u5230\u5f53\u524d\u5b57\u6bb5\uff0c\u76f8\u5f53\u4e8edrf\u6846\u67b6\u7684read_only<\/td><\/tr><tr><td><strong>error_messages<\/strong><\/td><td>\u4f7f\u7528\u6821\u9a8c\u503cvalidate\u9009\u9879\u4ee5\u540e\u8bbe\u7f6e\u7684\u9519\u8bef\u63d0\u793a\uff0c\u5b57\u5178\u7c7b\u578b\uff0c\u53ef\u4ee5\u7528\u6765\u66ff\u4ee3\u9ed8\u8ba4\u7684\u5b57\u6bb5\u5f02\u5e38\u63d0\u793a\u8bed\uff0c\u683c\u5f0f\uff1a error_messages={\u201crequired\u201d: \u201c\u7528\u6237\u540d\u4e3a\u5fc5\u586b\u9879\u3002\u201d}<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<h4 class=\"wp-block-heading\">\u6784\u9020\u5668\u5d4c\u5957\u4f7f\u7528<\/h4>\n\n\n\n<pre class=\"wp-block-preformatted\">from datetime import datetime<br>\u200b<br>from flask import Flask<br>from flask_sqlalchemy import SQLAlchemy<br>from flask_marshmallow import Marshmallow<br>\u200b<br>app = Flask(__name__)<br>app.config[\"DEBUG\"] = True<br>app.config[\"SQLALCHEMY_DATABASE_URI\"]=\"mysql:\/\/root:123@127.0.0.1:3306\/yingming?charset=utf8mb4\"<br>app.config[\"SQLALCHEMY_TRACK_MODIFICATIONS\"] = False<br>app.config[\"SQLALCHEMY_ECHO\"] = True<br>\u200b<br>db = SQLAlchemy()<br>db.init_app(app)<br>\u200b<br>ma = Marshmallow()<br>ma.init_app(app)<br>\u200b<br>\u200b<br>\"\"\"\u6a21\u4effORM\u7684\u6a21\u578b\"\"\"<br>class Model(object):<br> &nbsp; &nbsp;pass<br>\u200b<br>class User(Model):<br> &nbsp; &nbsp;def __init__(self, name, email):<br> &nbsp; &nbsp; &nbsp; &nbsp;self.name = name<br> &nbsp; &nbsp; &nbsp; &nbsp;self.email = email<br> &nbsp; &nbsp; &nbsp; &nbsp;self.created_at = datetime.now()<br> &nbsp; &nbsp; &nbsp; &nbsp;self.books = [] &nbsp; &nbsp;# \u7528\u6765\u4ee3\u66ffMySQL\u4e2d\u7684\u5916\u68c0\u5173\u7cfb\uff0c\u5b9e\u73b01\u5bf9\u591a\u6216\u591a\u5bf9\u591a<br> &nbsp; &nbsp; &nbsp; &nbsp;self.friends = [] &nbsp;# \u7528\u6765\u4ee3\u66ffMySQL\u4e2d\u7684\u5916\u68c0\u5173\u7cfb\uff0c\u5b9e\u73b0\u81ea\u5173\u8054<br>\u200b<br>\u200b<br>class Book(Model):<br> &nbsp; &nbsp;def __init__(self, title, author):<br> &nbsp; &nbsp; &nbsp; &nbsp;self.title = title<br> &nbsp; &nbsp; &nbsp; &nbsp;self.author = author &nbsp;# \u7528\u6765\u4ee3\u66ffMySQL\u4e2d\u7684\u5916\u952e\u5173\u7cfb\uff0c1\u5bf91<br>\u200b<br>\"\"\"\u5e8f\u5217\u5316\u5668\"\"\"<br>from marshmallow import Schema, fields<br>\u200b<br>\u200b<br>class UserSchema(Schema):<br> &nbsp; &nbsp;\"\"\"\u7528\u6237\u7684\u5e8f\u5217\u5316\u5668\"\"\"<br> &nbsp; &nbsp;name = fields.String()<br> &nbsp; &nbsp;email = fields.Email()<br> &nbsp; &nbsp;\"\"\"1\u5bf9\u591a\uff0c\u591a\u5bf9\u591a\"\"\"<br> &nbsp; &nbsp;# \u5728fields.Nested\u5916\u56f4\u5305\u88f9\u4e00\u4e2aList\u5217\u8868\u5b57\u6bb5\uff0c\u5219\u53ef\u4ee5\u8fd4\u56de\u591a\u4e2a\u7ed3\u679c\u4e86\u3002exclude\u8868\u793a\u6392\u9664<br> &nbsp; &nbsp;# books = fields.List(fields.Nested(lambda: BookSchema(exclude=[\"author\"])))<br> &nbsp; &nbsp;# \u7b80\u5199\u65b9\u5f0f:<br> &nbsp; &nbsp;books = fields.Nested(lambda : BookSchema(many=True, exclude=[\"author\"]))<br> &nbsp; &nbsp;\"\"\"\u81ea\u5173\u8054\"\"\"<br> &nbsp; &nbsp;# \u81ea\u5173\u8054\u5c31\u662f\u4e00\u4e2a\u6a21\u578b\u4e2d\u65e2\u5b58\u5728\u4e3b\u952e\u5173\u7cfb\uff0c\u4e5f\u5b58\u5728\u5916\u952e\u5173\u7cfb\u7684\u60c5\u51b5<br> &nbsp; &nbsp;# \u65b9\u5f0f1\uff1a\u4f7f\u7528\u81ea\u8eab\"self\"\u4f5c\u4e3a\u5916\u952e\u7684\u65b9\u5f0f\uff0c\u5e76\u53ef\u4ee5\u6307\u5b9a\u5e8f\u5217\u5316\u6a21\u578b\u7684\u591a\u4e2a\u5b57\u6bb5<br> &nbsp; &nbsp;# friends = fields.Nested(lambda: \"self\", only=(\"name\", \"email\", \"books\"), many=True)<br> &nbsp; &nbsp;# \u65b9\u5f0f2\uff1a\u4f7f\u7528Pluck\u5b57\u6bb5\u53ef\u4ee5\u7528\u5355\u4e2a\u503c\u6765\u66ff\u6362\u5d4c\u5957\u7684\u6570\u636e\uff0c\u53ea\u53ef\u4ee5\u5f97\u5230\u6a21\u578b\u7684\u5355\u4e2a\u5b57\u6bb5\u503c<br> &nbsp; &nbsp;friends = fields.Pluck(lambda: \"self\", \"name\", many=True)<br>\u200b<br>class BookSchema(Schema):<br> &nbsp; &nbsp;\"\"\"\u56fe\u4e66\u7684\u5e8f\u5217\u5316\u5668\"\"\"<br> &nbsp; &nbsp;title = fields.String()<br> &nbsp; &nbsp;author = fields.Nested(lambda: UserSchema(exclude=[\"books\"]))<br>\u200b<br>@app.route(\"\/1\")<br>def index1():<br> &nbsp; &nbsp;\"\"\"\u6784\u9020\u5668\u5d4c\u5957\u4f7f\u7528\"\"\"<br> &nbsp; &nbsp;# \u5047\u8bbe\u6839\u636e\u5f53\u524d\u4f5c\u8005\uff0c\u67e5\u627e\u5bf9\u5e94\u7684\u4f5c\u8005\u53d1\u5e03\u7684\u56fe\u4e66\u5217\u8868<br> &nbsp; &nbsp;user0 = User(name=\"\u5357\u6d3e\u4e09\u53d4\", email=\"sanshu@163.com\")<br>\u200b<br> &nbsp; &nbsp;book1 = Book(title=\"\u76d7\u5893\u7b14\u8bb01\", author=user0)<br> &nbsp; &nbsp;book2 = Book(title=\"\u76d7\u5893\u7b14\u8bb02\", author=user0)<br> &nbsp; &nbsp;book3 = Book(title=\"\u76d7\u5893\u7b14\u8bb03\", author=user0)<br> &nbsp; &nbsp;user0.books = [book1, book2, book3]<br>\u200b<br> &nbsp; &nbsp;us = UserSchema()<br> &nbsp; &nbsp;result = us.dump(user0)<br> &nbsp; &nbsp;print(result)<br>\u200b<br> &nbsp; &nbsp;bs = BookSchema()<br> &nbsp; &nbsp;result = bs.dump([book1, book2, book3], many=True)<br> &nbsp; &nbsp;print(result)<br>\u200b<br> &nbsp; &nbsp;return \"ok\"<br>\u200b<br>\u200b<br>@app.route(\"\/2\")<br>def index2():<br> &nbsp; &nbsp;\"\"\"\u81ea\u5173\u8054\"\"\"<br> &nbsp; &nbsp;user0 = User(name=\"\u5357\u6d3e\u4e09\u53d4\", email=\"sanshu@163.com\")<br> &nbsp; &nbsp;user1 = User(name=\"\u5218\u6148\u6b23\", email=\"sanshu@163.com\")<br> &nbsp; &nbsp;user2 = User(name=\"\u5929\u4e0b\u9738\u5531\", email=\"sanshu@163.com\")<br> &nbsp; &nbsp;user0.friends = [user1, user2]<br>\u200b<br> &nbsp; &nbsp;us = UserSchema()<br> &nbsp; &nbsp;result = us.dump(user0)<br> &nbsp; &nbsp;print(result)<br>\u200b<br> &nbsp; &nbsp;return \"ok\"<br>\u200b<br>if __name__ == '__main__':<br> &nbsp; &nbsp;with app.app_context():<br> &nbsp; &nbsp; &nbsp; &nbsp;db.create_all()<br> &nbsp; &nbsp;app.run(debug=True, port=5555)<\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">\u57fa\u4e8eSchema\u5b8c\u6210\u6570\u636e\u53cd\u5e8f\u5217\u5316\u8f6c\u6362<\/h3>\n\n\n\n<p>\u4ee3\u7801\uff1a<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">import re<br>from flask import Flask<br>from flask_sqlalchemy import SQLAlchemy<br>from flask_marshmallow import Marshmallow<br>\u200b<br>app = Flask(__name__)<br>app.config[\"DEBUG\"] = True<br>app.config[\"SQLALCHEMY_DATABASE_URI\"]=\"mysql:\/\/root:123@127.0.0.1:3306\/yingming?charset=utf8mb4\"<br>app.config[\"SQLALCHEMY_TRACK_MODIFICATIONS\"] = False<br>app.config[\"SQLALCHEMY_ECHO\"] = True<br>\u200b<br>db = SQLAlchemy()<br>db.init_app(app)<br>\u200b<br>ma = Marshmallow()<br>ma.init_app(app)<br>\u200b<br>\"\"\"\u5e8f\u5217\u5316\u5668\"\"\"<br>from marshmallow import Schema, fields, validate, ValidationError<br>\"\"\"<br>validate \u662fmarshMallow\u5185\u7f6e\u6821\u9a8c\u5668\u6a21\u5757\uff0c\u63d0\u4f9b\u4e86\u90e8\u5206\u5185\u7f6e\u5199\u597d\u7684\u9a8c\u8bc1\u89c4\u5219\u3002<br>validate.Length \u5b57\u7b26\u4e32\u957f\u5ea6\u9a8c\u8bc1\uff0c\u6216\u8005\u6587\u4ef6\u5185\u5bb9\u957f\u5ea6\u9a8c\u8bc1<br>validate.Range  \u6570\u503c\u8303\u56f4\u9a8c\u8bc1<br>validate.Regexp \u6b63\u5219\u9a8c\u8bc1\uff0c\u5e95\u5c42\u4f7f\u7528\u7684\u662fpython\u5185\u7f6e\u7684re\u6a21\u5757<br>validate.OneOf  \u9009\u9879\u53d6\u503c\uff0c\u901a\u8fc7choices\u9009\u9879\u6307\u5b9a\u503c\u53ea\u80fd\u662f\u5176\u4e2d\u4e00\u4e2a<br>validate.Email &nbsp;  \u90ae\u7bb1\u89c4\u5219\u6821\u9a8c\uff0c\u5e95\u5c42\u5b9e\u9645\u4e0a\u5c31\u662f\u4e00\u4e2a\u90ae\u7bb1\u7684\u6b63\u5219\u6821\u9a8c<br>validate.URL &nbsp; &nbsp;  \u7f51\u5740\u89c4\u5219\u6821\u9a8c\uff0c\u5e95\u5c42\u5b9e\u9645\u4e0a\u5c31\u662f\u4e00\u4e2a\u7f51\u5740\u7684\u6b63\u5219\u6821\u9a8c<br>validate.Equal &nbsp;  \u5224\u65ad\u662f\u5426\u4e0e\u6307\u5b9a\u7684\u503c\u76f8\u7b49<br>\"\"\"<br>\u200b<br>class UserSchema(Schema):<br> &nbsp; &nbsp;\"\"\"\u7528\u6237\u7684\u5e8f\u5217\u5316\u5668\"\"\"<br> &nbsp; &nbsp;# required = True, \u8bbe\u7f6e\u5f53\u524d\u5b57\u6bb5\u4e3a\u5fc5\u586b\u9879<br> &nbsp; &nbsp;name = fields.String(required=True, validate=validate.Length(min=3, max=16, error=\"\u7528\u6237\u540d\u6709\u8bef\uff01name\u5fc5\u987b\u5728{min}~{max}\u4e2a\u5b57\u7b26\u957f\u5ea6\u4e4b\u95f4\"))<br> &nbsp; &nbsp;age = fields.Integer(validate=validate.Range(min=12, max=55, error=\"\u7528\u6237\u5e74\u9f84\u5fc5\u987b\u5728{min}~{max}\u5c81\u4e4b\u95f4!\"))<br> &nbsp; &nbsp;role = fields.String(validate=validate.OneOf(choices=[\"\u8001\u5e08\", \"\u5b66\u751f\", \"\u8def\u4eba\"], error=\"\u8eab\u4efd\u53ea\u80fd\u5728{choices}\u4e2d\u9009\u62e9\u5176\u4e2d\u4e00\u4e2a\uff01\"))<br> &nbsp; &nbsp;email = fields.Email(validate=validate.Email(error=\"\u90ae\u4ef6\u683c\u5f0f\u6709\u8bef\uff01\uff01\"))<br> &nbsp; &nbsp;mobile = fields.String(validate=validate.Regexp(regex=\"1[3-9]\\d{9}\", error=\"\u624b\u673a\u53f7\u683c\u5f0f\u6709\u8bef\uff01\"))<br>\u200b<br>\u200b<br>@app.route(\"\/1\")<br>def index1():<br> &nbsp; &nbsp;\"\"\"\u53cd\u5e8f\u5217\u5316\"\"\"<br> &nbsp; &nbsp;# \u6a21\u62df\u5ba2\u6237\u7aef\u63d0\u4ea4\u8fc7\u6765\u7684\u6570\u636e<br> &nbsp; &nbsp;user_data = {\"name\": \"xi\",\"role\": \"teacher\", \"email\": \"ronnie@stones.com\", \"age\": 12, \"mobile\": \"13311234455\"}<br> &nbsp; &nbsp;us = UserSchema()<br> &nbsp; &nbsp;# try:<br> &nbsp; &nbsp;# &nbsp; &nbsp; # \u6821\u9a8c\u4e00\u4e2a\u6570\u636e<br> &nbsp; &nbsp;# &nbsp; &nbsp; result = us.load(user_data)<br> &nbsp; &nbsp;# &nbsp; &nbsp; print(\"\u6821\u9a8c\u901a\u8fc7\uff0c\u6821\u9a8c\u7ed3\u679cresult=\", result)<br> &nbsp; &nbsp;# except ValidationError as e:<br> &nbsp; &nbsp;# &nbsp; &nbsp; return f\"\u6821\u9a8c\u5931\u8d25\uff1a{e}\"<br>\u200b<br> &nbsp; &nbsp;data_list = [user_data, user_data, user_data]<br> &nbsp; &nbsp;try:<br> &nbsp; &nbsp; &nbsp; &nbsp;# \u6821\u9a8c\u591a\u4e2a\u6570\u636e<br> &nbsp; &nbsp; &nbsp; &nbsp;result = us.load(data_list, many=True)<br> &nbsp; &nbsp; &nbsp; &nbsp;print(\"\u6821\u9a8c\u901a\u8fc7\uff0c\u6821\u9a8c\u7ed3\u679cresult=\", result)<br> &nbsp; &nbsp;except ValidationError as e:<br> &nbsp; &nbsp; &nbsp; &nbsp;return f\"\u6821\u9a8c\u5931\u8d25\uff1a{e}\"<br>\u200b<br> &nbsp; &nbsp;return \"ok\"<br>\u200b<br>\u200b<br>if __name__ == '__main__':<br> &nbsp; &nbsp;with app.app_context():<br> &nbsp; &nbsp; &nbsp; &nbsp;db.create_all()<br> &nbsp; &nbsp;app.run(debug=True, port=5555)<br>\u200b<\/pre>\n\n\n\n<h4 class=\"wp-block-heading\">\u57fa\u4e8e\u5185\u7f6e\u9a8c\u8bc1\u5668\u8fdb\u884c\u6570\u636e\u9a8c\u8bc1<\/h4>\n\n\n\n<figure class=\"wp-block-table\"><table class=\"has-fixed-layout\"><thead><tr><th>\u5185\u7f6e\u9a8c\u8bc1\u5668<\/th><th>\u63cf\u8ff0<\/th><\/tr><\/thead><tbody><tr><td>validate.<a href=\"https:\/\/marshmallow.readthedocs.io\/en\/stable\/marshmallow.validate.html#marshmallow.validate.Email\"><code>Email<\/code><\/a>(*, error)<\/td><td>\u90ae\u7bb1\u9a8c\u8bc1<\/td><\/tr><tr><td>validate.<a href=\"https:\/\/marshmallow.readthedocs.io\/en\/stable\/marshmallow.validate.html#marshmallow.validate.Equal\"><code>Equal<\/code><\/a>(comparable, *, error)<\/td><td>\u5224\u65ad\u503c\u662f\u5426\u76f8\u7b49<\/td><\/tr><tr><td>validate.<a href=\"https:\/\/marshmallow.readthedocs.io\/en\/stable\/marshmallow.validate.html#marshmallow.validate.Length\"><code>Length<\/code><\/a>(min, max, *, equal, error)<\/td><td>\u503c\u957f\u5ea6\/\u5927\u5c0f\u9a8c\u8bc1<\/td><\/tr><tr><td>validate.<a href=\"https:\/\/marshmallow.readthedocs.io\/en\/stable\/marshmallow.validate.html#marshmallow.validate.OneOf\"><code>OneOf<\/code><\/a>(choices, labels, *, error)<\/td><td>\u9009\u9879\u9a8c\u8bc1<\/td><\/tr><tr><td>validate.<a href=\"https:\/\/marshmallow.readthedocs.io\/en\/stable\/marshmallow.validate.html#marshmallow.validate.Range\"><code>Range<\/code><\/a>([min, max])<\/td><td>\u8303\u56f4\u9a8c\u8bc1<\/td><\/tr><tr><td>validate.<a href=\"https:\/\/marshmallow.readthedocs.io\/en\/stable\/marshmallow.validate.html#marshmallow.validate.Regexp\"><code>Regexp<\/code><\/a>(regex, bytes, Pattern][, flags])<\/td><td>\u6b63\u5219\u9a8c\u8bc1<\/td><\/tr><tr><td>validate.<a href=\"https:\/\/marshmallow.readthedocs.io\/en\/stable\/marshmallow.validate.html#marshmallow.validate.URL\"><code>URL<\/code><\/a>(*, relative, schemes, Set[str]]] = None, \u2026)<\/td><td>\u9a8c\u8bc1\u662f\u5426\u4e3aURL<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<p>\u4ee3\u7801\uff1a<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">from marshmallow import Schema, fields, validate, ValidationError<br>class UserSchema(Schema):<br> &nbsp; &nbsp;name = fields.Str(validate=validate.Length(min=1))<br> &nbsp; &nbsp;permission = fields.Str(validate=validate.OneOf([\"read\", \"write\", \"admin\"]))<br> &nbsp; &nbsp;age = fields.Int(validate=validate.Range(min=18, max=40))<br>\u200b<br>if __name__ == '__main__':<br> &nbsp; &nbsp;data = {\"name\": \"\", \"permission\": \"hello\", \"age\": 71}<br>    try:<br> &nbsp;      UserSchema().load(data)<br>    except ValidationError as err:<br> &nbsp;      pprint(err.messages)<\/pre>\n\n\n\n<h4 class=\"wp-block-heading\">\u53cd\u5e8f\u5217\u5316\u65f6\u5bf9\u6307\u5b9a\u90e8\u5206\u5b57\u6bb5\u5ffd\u7565\u4e0d\u6821\u9a8c<\/h4>\n\n\n\n<pre class=\"wp-block-preformatted\">import re<br>from flask import Flask<br>from flask_sqlalchemy import SQLAlchemy<br>from flask_marshmallow import Marshmallow<br>\u200b<br>app = Flask(__name__)<br>app.config[\"DEBUG\"] = True<br>app.config[\"SQLALCHEMY_DATABASE_URI\"]=\"mysql:\/\/root:123@127.0.0.1:3306\/yingming?charset=utf8mb4\"<br>app.config[\"SQLALCHEMY_TRACK_MODIFICATIONS\"] = False<br>app.config[\"SQLALCHEMY_ECHO\"] = True<br>\u200b<br>db = SQLAlchemy()<br>db.init_app(app)<br>\u200b<br>ma = Marshmallow()<br>ma.init_app(app)<br>\u200b<br>\"\"\"\u5e8f\u5217\u5316\u5668\"\"\"<br>from marshmallow import Schema, fields, validate, ValidationError<br>\u200b<br>class UserSchema(Schema):<br> &nbsp; &nbsp;\"\"\"\u7528\u6237\u7684\u5e8f\u5217\u5316\u5668\"\"\"<br> &nbsp; &nbsp;name = fields.String(required=True, validate=validate.Length(min=3, max=16, error=\"\u7528\u6237\u540d\u6709\u8bef\uff01name\u5fc5\u987b\u5728{min}~{max}\u4e2a\u5b57\u7b26\u957f\u5ea6\u4e4b\u95f4\"))<br> &nbsp; &nbsp;age = fields.Integer(required=True)<br> &nbsp; &nbsp;avatar = fields.String(required=True, error_messages={\"required\": \"avatar\u5fc5\u987b\u586b\u5199\uff01\"})<br>\u200b<br>@app.route(\"\/1\")<br>def index1():<br> &nbsp; &nbsp;\"\"\"\u53cd\u5e8f\u5217\u5316\u65f6\u5bf9\u90e8\u5206\u5b57\u6bb5\u8fdb\u884c\u5ffd\u7565\u4e0d\u6821\u9a8c\"\"\"<br> &nbsp; &nbsp;# \u6a21\u62df\u5ba2\u6237\u7aef\u63d0\u4ea4\u7684\u6570\u636e<br> &nbsp; &nbsp;user_data = {\"name\": \"xiaoming\", \"age\": 12}<br> &nbsp; &nbsp;us = UserSchema()<br> &nbsp; &nbsp;result = us.load(user_data, partial=[\"avatar\",])<br> &nbsp; &nbsp;print(result)<br> &nbsp; &nbsp;return \"ok\"<br>\u200b<br>\u200b<br>if __name__ == '__main__':<br> &nbsp; &nbsp;with app.app_context():<br> &nbsp; &nbsp; &nbsp; &nbsp;db.create_all()<br> &nbsp; &nbsp;app.run(debug=True, port=5555)<br>\u200b<\/pre>\n\n\n\n<h4 class=\"wp-block-heading\">\u8bbe\u7f6e\u6307\u5b9a\u5b57\u6bb5\u53ea\u5728\u5e8f\u5217\u5316\u6216\u53cd\u5e8f\u5217\u5316\u9636\u6bb5\u624d\u542f\u7528<\/h4>\n\n\n\n<p>\u5c31\u662f\u8bbe\u7f6e\u5e8f\u5217\u5316\u5668\u4e2d\u7684\u5b57\u6bb5\u53ea\u8bfb(dump_only\uff0c\u76f8\u5f53\u4e8edrf\u7684read_only)\u6216\u53ea\u5199(load_only\uff0c\u76f8\u5f53\u4e8edrf\u7684write_only)<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">import re<br>from datetime import datetime<br>from flask import Flask<br>from flask_sqlalchemy import SQLAlchemy<br>from flask_marshmallow import Marshmallow<br>\u200b<br>app = Flask(__name__)<br>app.config[\"DEBUG\"] = True<br>app.config[\"SQLALCHEMY_DATABASE_URI\"]=\"mysql:\/\/root:123@127.0.0.1:3306\/yingming?charset=utf8mb4\"<br>app.config[\"SQLALCHEMY_TRACK_MODIFICATIONS\"] = False<br>app.config[\"SQLALCHEMY_ECHO\"] = True<br>\u200b<br>db = SQLAlchemy()<br>db.init_app(app)<br>\u200b<br>ma = Marshmallow()<br>ma.init_app(app)<br>\u200b<br>\"\"\"\u6a21\u578b\"\"\"<br>class Model(object):<br> &nbsp; &nbsp;pass<br>\u200b<br>class User(Model):<br> &nbsp; &nbsp;def __init__(self, username, password):<br> &nbsp; &nbsp; &nbsp; &nbsp;self.username = username<br> &nbsp; &nbsp; &nbsp; &nbsp;self.password = password<br> &nbsp; &nbsp; &nbsp; &nbsp;self.created_time = datetime.now()<br>\u200b<br>\"\"\"\u5e8f\u5217\u5316\u5668\"\"\"<br>from marshmallow import Schema, fields, validate, ValidationError<br>class UserSchema(Schema):<br> &nbsp; &nbsp;username = fields.String()<br> &nbsp; &nbsp;password = fields.String(required=True, load_only=True) &nbsp;# \u76f8\u5f53\u4e8e\u53ea\u5199\u5b57\u6bb5 \"write-only\"<br> &nbsp; &nbsp;created_time = fields.DateTime(dump_only=True) # \u76f8\u5f53\u4e8e\u53ea\u8bfb\u5b57\u6bb5 \"read-only\"<br>\u200b<br>@app.route(\"\/1\")<br>def index1():<br> &nbsp; &nbsp;\"\"\"\u8bbe\u7f6e\u6307\u5b9a\u5b57\u6bb5\u53ea\u80fd\u7528\u4e8e\u5e8f\u5217\u5316\u6216\u53cd\u5e8f\u5217\u5316\u4e2d\"\"\"<br> &nbsp; &nbsp;# \u53cd\u5e8f\u5217\u5316\u9636\u6bb5<br> &nbsp; &nbsp;# user_data = {\"username\": \"xiaoming\", \"password\": \"123456\"}<br> &nbsp; &nbsp;# us = UserSchema()<br> &nbsp; &nbsp;# result = us.load(user_data)<br>\u200b<br> &nbsp; &nbsp;# \u5e8f\u5217\u5316\u9636\u6bb5<br> &nbsp; &nbsp;user = User(username=\"xiaohong\", password=\"123456\")<br> &nbsp; &nbsp;us = UserSchema()<br> &nbsp; &nbsp;result = us.dump(user)<br> &nbsp; &nbsp;print(result)<br>\u200b<br> &nbsp; &nbsp;return \"ok\"<br>\u200b<br>\u200b<br>if __name__ == '__main__':<br> &nbsp; &nbsp;with app.app_context():<br> &nbsp; &nbsp; &nbsp; &nbsp;db.create_all()<br> &nbsp; &nbsp;app.run(debug=True, port=5555)<br>\u200b<\/pre>\n\n\n\n<h4 class=\"wp-block-heading\">MarshMallow\u63d0\u4f9b\u7684\u94a9\u5b50\u65b9\u6cd5<\/h4>\n\n\n\n<p>marshmallow\u63d0\u4f9b\u4e866\u4e2a\u94a9\u5b50\u5728\u53cd\u5e8f\u5217\u5316\u6216\u8005\u5e8f\u5217\u5316\u9636\u6bb5\u65f6\u81ea\u52a8\u6267\u884c\uff0c\u8fd9\u4e9b\u94a9\u5b50\u90fd\u662f\u4ee5\u88c5\u9970\u5668\u7684\u5f62\u5f0f\u63d0\u4f9b\u51fa\u6765\u7684\u3002<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\"># \u5e8f\u5217\u5316\u4e4b\u524d\u6267\u884c\u7684\u94a9\u5b50\u65b9\u6cd5<br>pre_dump([fn\uff0cpass_many]) \u6ce8\u518c\u8981\u5728\u5e8f\u5217\u5316\u5bf9\u8c61\u4e4b\u524d\u8c03\u7528\u7684\u65b9\u6cd5\uff0c\u5b83\u4f1a\u5728\u5e8f\u5217\u5316\u5bf9\u8c61\u4e4b\u524d\u88ab\u8c03\u7528\u3002<br># \u5e8f\u5217\u5316\u4e4b\u540e\u6267\u884c\u7684\u94a9\u5b50\u65b9\u6cd5<br>post_dump([fn\uff0cpass_many\uff0cpass_original]) \u6ce8\u518c\u8981\u5728\u5e8f\u5217\u5316\u5bf9\u8c61\u540e\u8c03\u7528\u7684\u65b9\u6cd5\uff0c\u5b83\u4f1a\u5728\u5bf9\u8c61\u5e8f\u5217\u5316\u540e\u88ab\u8c03\u7528\u3002<br>\u200b<br># \u53cd\u5e8f\u5217\u5316\u4e4b\u524d\u6267\u884c\u7684\u94a9\u5b50\u65b9\u6cd5<br>pre_load([fn\uff0cpass_many]) \u5728\u53cd\u5e8f\u5217\u5316\u5bf9\u8c61\u4e4b\u524d\uff0c\u6ce8\u518c\u8981\u8c03\u7528\u7684\u65b9\u6cd5\uff0c\u5b83\u4f1a\u5728\u9a8c\u8bc1\u6570\u636e\u4e4b\u524d\u8c03\u7528<br># \u53cd\u5e8f\u5217\u5316\u4e4b\u540e\u6267\u884c\u7684\u94a9\u5b50\u65b9\u6cd5<br>post_load([fn\uff0cpass_many\uff0cpass_original]) \u6ce8\u518c\u53cd\u5e8f\u5217\u5316\u5bf9\u8c61\u540e\u8981\u8c03\u7528\u7684\u65b9\u6cd5\uff0c\u5b83\u4f1a\u5728\u9a8c\u8bc1\u6570\u636e\u4e4b\u540e\u88ab\u8c03\u7528\u3002<br>\u200b<br># \u6821\u9a8c\u6307\u5b9a\u5b57\u6bb5\u7684\u88c5\u9970\u5668\uff0c\u76f8\u5f53\u4e8edrf\u7684 \u5355\u5b57\u6bb5\u6821\u9a8c validate_&lt;\u5b57\u6bb5\u540d&gt;(data)<br>validates(field_name)<br>\u200b<br># \u6821\u9a8c\u6574\u4e2a\u6784\u9020\u5668\u4e2d\u6240\u6709\u6570\u636e\u7684\u88c5\u9970\u5668\uff0c\u76f8\u5f53\u4e8edrf\u7684\u5168\u5b57\u6bb5\u6821\u9a8c validate(data)<br>validates_schema([fn, pass_many, ...])<\/pre>\n\n\n\n<pre class=\"wp-block-preformatted\">import re<br>from datetime import datetime<br>from flask import Flask, request<br>from flask_sqlalchemy import SQLAlchemy<br>from flask_marshmallow import Marshmallow<br>\u200b<br>\u200b<br>app = Flask(__name__)<br>app.config[\"DEBUG\"] = True<br>app.config[\"SQLALCHEMY_DATABASE_URI\"]=\"mysql:\/\/root:123@127.0.0.1:3306\/yingming?charset=utf8mb4\"<br>app.config[\"SQLALCHEMY_TRACK_MODIFICATIONS\"] = False<br>app.config[\"SQLALCHEMY_ECHO\"] = True<br>\u200b<br>db = SQLAlchemy()<br>db.init_app(app)<br>\u200b<br>ma = Marshmallow()<br>ma.init_app(app)<br>\u200b<br>\u200b<br>\"\"\"\u6a21\u578b\"\"\"<br>class Model(object):<br> &nbsp; &nbsp;pass<br>\u200b<br>\u200b<br>class User(Model):<br> &nbsp; &nbsp;def __init__(self, username, password, avatar):<br> &nbsp; &nbsp; &nbsp; &nbsp;self.username = username<br> &nbsp; &nbsp; &nbsp; &nbsp;self.password = password<br> &nbsp; &nbsp; &nbsp; &nbsp;self.avatar = avatar<br> &nbsp; &nbsp; &nbsp; &nbsp;self.created_time = datetime.now()<br> &nbsp; &nbsp; &nbsp; &nbsp;self.views_count = 0<br>\u200b<br> &nbsp; &nbsp;def __str__(self):<br> &nbsp; &nbsp; &nbsp; &nbsp;return f\"&lt;{self.__class__.__name__} [{self.username}]&gt;\"<br>\u200b<br>\u200b<br>\"\"\"\u5e8f\u5217\u5316\u5668\"\"\"<br>from marshmallow import Schema, fields, validate, ValidationError, \\<br> &nbsp; &nbsp;pre_dump, pre_load, post_dump, post_load, validates, validates_schema<br>from werkzeug.security import generate_password_hash, check_password_hash<br>\u200b<br>\u200b<br>class UserSchema(Schema):<br> &nbsp; &nbsp;username = fields.String()<br> &nbsp; &nbsp;password = fields.String(required=True, load_only=True) &nbsp;# \u76f8\u5f53\u4e8e\u53ea\u5199\u5b57\u6bb5 \"write-only\"<br> &nbsp; &nbsp;re_password = fields.Str(required=True)<br> &nbsp; &nbsp;created_time = fields.DateTime(dump_only=True) &nbsp;# \u76f8\u5f53\u4e8e\u53ea\u8bfb\u5b57\u6bb5 \"read-only\"<br> &nbsp; &nbsp;avatar = fields.String()<br>\u200b<br> &nbsp; &nbsp;# # pass_many \u8868\u793a\u662f\u5426\u63a5\u53d7\u4f20\u9012\u8fdb\u6765\u7684many\u53c2\u6570<br> &nbsp; &nbsp;# @pre_dump(pass_many=True)<br> &nbsp; &nbsp;# def pre_dump(self, instance, many, **kwargs):<br> &nbsp; &nbsp;# &nbsp; &nbsp; \"\"\"\u5e8f\u5217\u5316\u4e4b\u524d\u81ea\u52a8\u6267\u884c\u7684\u94a9\u5b50\u51fd\u6570\"\"\"<br> &nbsp; &nbsp;# &nbsp; &nbsp; print(\"\u5e8f\u5217\u5316\u4e4b\u524d\uff0cdata\u662f\u6a21\u578b\u5bf9\u8c61\uff0c\u5bf9\u670d\u52a1\u7aef\u8981\u8fd4\u56de\u7ed9\u5ba2\u6237\u7aef\u7684\u6570\u636e\u8fdb\u884c\u9884\u5904\u7406-1\")<br> &nbsp; &nbsp;# &nbsp; &nbsp; instance.avatar = f\"\/\/{request.environ['HTTP_HOST']}{instance.avatar}\"<br> &nbsp; &nbsp;# &nbsp; &nbsp; # \u6b64\u5904\u53ef\u4ee5\u8c03\u7528\u6a21\u578b\u5bf9\u8c61\uff0c\u4fdd\u5b58\u6216\u64cd\u4f5c\u6a21\u578b\u6570\u636e\uff0c\u4fdd\u5b58\u5230\u6570\u636e\u5e93<br> &nbsp; &nbsp;# &nbsp; &nbsp; instance.views_count = instance.views_count+1<br> &nbsp; &nbsp;# &nbsp; &nbsp; return instance<br>\u200b<br> &nbsp; &nbsp;# @post_dump(pass_many=True)<br> &nbsp; &nbsp;# def post_dump(self, data, many, **kwargs):<br> &nbsp; &nbsp;# &nbsp; &nbsp; \"\"\"\u5e8f\u5217\u5316\u4e4b\u540e\u81ea\u52a8\u6267\u884c\u7684\u94a9\u5b50\u51fd\u6570\"\"\"<br> &nbsp; &nbsp;# &nbsp; &nbsp; print(\"\u5e8f\u5217\u5316\u4e4b\u540e\uff0cdata\u662f\u5b57\u5178\uff0c\u5bf9\u670d\u52a1\u7aef\u8981\u8fd4\u56de\u7ed9\u5ba2\u6237\u7aef\u7684\u6570\u636e\u8fdb\u884c\u9884\u5904\u7406-2\")<br> &nbsp; &nbsp;# &nbsp; &nbsp; # \u6b64\u5904\u65e0\u6cd5\u8c03\u7528\u5230\u6a21\u578b\u5bf9\u8c61<br> &nbsp; &nbsp;# &nbsp; &nbsp; data[\"test\"] = \"abc\"<br> &nbsp; &nbsp;# &nbsp; &nbsp; return data<br>\u200b<br> &nbsp; &nbsp;# @pre_load(pass_many=True)<br> &nbsp; &nbsp;# def pre_load(self, data, *args, **kwargs):<br> &nbsp; &nbsp;# &nbsp; &nbsp; \"\"\"\u53cd\u5e8f\u5217\u5316\u4e4b\u524d\uff0c\u6821\u9a8c\u6570\u636e\u4e4b\u524d\u7684\u94a9\u5b50\u64cd\u4f5c\"\"\"<br> &nbsp; &nbsp;# &nbsp; &nbsp; print(\"\u53cd\u5e8f\u5217\u5316\u4e4b\u524d\uff0cdata\u662f\u5b57\u5178\uff0c\u5bf9\u5ba2\u6237\u7aef\u63d0\u4ea4\u7684\u6570\u636e\u8fdb\u884c\u6821\u9a8c\u524d\u7684\u8c03\u6574\u6216\u4fee\u6539-1\")<br> &nbsp; &nbsp;# &nbsp; &nbsp; print(f\"\u4fdd\u5b58\u4e0a\u4f20\u6587\u4ef6\uff1adata['avatar']={data['avatar']}\")<br> &nbsp; &nbsp;# &nbsp; &nbsp; data[\"avatar\"] = f\"\/\/{request.environ['HTTP_HOST']}{data['avatar']}\"<br> &nbsp; &nbsp;# &nbsp; &nbsp; return data<br>\u200b<br> &nbsp; &nbsp;@post_load(pass_many=True)<br> &nbsp; &nbsp;def post_load(self, data, *args, **kwargs):<br> &nbsp; &nbsp; &nbsp; &nbsp;\"\"\"\u53cd\u5e8f\u5217\u5316\u4e4b\u540e\uff0c\u6821\u9a8c\u6570\u636e\u4e4b\u540e\u7684\u94a9\u5b50\u64cd\u4f5c\"\"\"<br> &nbsp; &nbsp; &nbsp; &nbsp;# print(\"\u53cd\u5e8f\u5217\u5316\u4e4b\u524d\uff0cdata\u662f\u5b57\u5178\uff0c\u4e00\u822c\u5728\u8fd9\u4e2a\u94a9\u5b50\u91cc\u9762\u8fdb\u884c\u6570\u636e\u5e93\u7684\u64cd\u4f5c\uff0c\u628a\u5b57\u5178\u8f6c\u6362\u6210\u6a21\u578b-2\")<br> &nbsp; &nbsp; &nbsp; &nbsp;data.pop(\"re_password\") # \u4f8b\u5982\u5220\u9664\u4e0d\u5fc5\u8981\u7684\u5b57\u6bb5<br> &nbsp; &nbsp; &nbsp; &nbsp;data[\"password\"] = generate_password_hash(password=data[\"password\"]) # \u4f8b\u5982\u5bc6\u7801\u52a0\u5bc6\uff0c<br> &nbsp; &nbsp; &nbsp; &nbsp;user = User(**data)<br> &nbsp; &nbsp; &nbsp; &nbsp;return user<br>\u200b<br> &nbsp; &nbsp;# @validates(field_name=\"username\")<br> &nbsp; &nbsp;# def validates1(self, data):<br> &nbsp; &nbsp;# &nbsp; &nbsp; \"\"\"\u5355\u5b57\u6bb5\u6821\u9a8c\uff1a\u6821\u9a8c\u7684\u5b57\u6bb5\u540d\u5fc5\u987b\u5199\u5728\u88c5\u9970\u5668\uff0c\u4e0e\u51fd\u6570\u540d\u6ca1\u6709\u4ec0\u4e48\u5173\u7cfb1\"\"\"<br> &nbsp; &nbsp;# &nbsp; &nbsp; print(f\"username={data}\")<br> &nbsp; &nbsp;# &nbsp; &nbsp; if data == \"root\":<br> &nbsp; &nbsp;# &nbsp; &nbsp; &nbsp; &nbsp; raise ValidationError(message=\"\u7528\u6237\u540d\u4e0d\u80fd\u53ebroot\uff01\uff01\uff01\", field_name=\"username\")<br> &nbsp; &nbsp;# &nbsp; &nbsp; return data<br> &nbsp; &nbsp;#<br> &nbsp; &nbsp;# @validates(field_name=\"avatar\")<br> &nbsp; &nbsp;# def validates2(self, data):<br> &nbsp; &nbsp;# &nbsp; &nbsp; \"\"\"\u5355\u5b57\u6bb5\u6821\u9a8c\uff1a\u6821\u9a8c\u7684\u5b57\u6bb5\u540d\u5fc5\u987b\u5199\u5728\u88c5\u9970\u5668\uff0c\u4e0e\u51fd\u6570\u540d\u6ca1\u6709\u4ec0\u4e48\u5173\u7cfb2\"\"\"<br> &nbsp; &nbsp;# &nbsp; &nbsp; print(f\"avatar={data}\")<br> &nbsp; &nbsp;# &nbsp; &nbsp; type_list = [\"png\", \"jpeg\", \"jpg\"]<br> &nbsp; &nbsp;# &nbsp; &nbsp; if data.split(\".\")[-1] not in type_list:<br> &nbsp; &nbsp;# &nbsp; &nbsp; &nbsp; &nbsp; raise ValidationError(message=f\"\u5934\u50cf\u683c\u5f0f\u6709\u8bef\uff01\u53ea\u5141\u8bb8\u4f7f\u7528{type_list}\u4e4b\u4e2d\u7684\u4e00\u79cd\u683c\u5f0f\uff01\uff01\uff01\uff01\", field_name=\"username\")<br> &nbsp; &nbsp;# &nbsp; &nbsp; return data<br>\u200b<br> &nbsp; &nbsp;@validates_schema(pass_many=True)<br> &nbsp; &nbsp;def validates_schema(self, data, *args, **kwargs):<br> &nbsp; &nbsp; &nbsp; &nbsp;\"\"\"\u5168\u5b57\u6bb5\u6821\u9a8c\uff1a\"\"\"<br> &nbsp; &nbsp; &nbsp; &nbsp;print(f\"data={data}\")<br> &nbsp; &nbsp; &nbsp; &nbsp;# \u591a\u4e2a\u5b57\u6bb5\u4e4b\u95f4\u8fdb\u884c\u76f8\u4e92\u6821\u9a8c\uff0c\u4f8b\u5982\uff1a\u5bc6\u7801\u4e0e\u786e\u8ba4\u5bc6\u7801<br> &nbsp; &nbsp; &nbsp; &nbsp;if data[\"password\"] != data[\"re_password\"]:<br> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;raise ValidationError(message=\"\u5bc6\u7801\u4e0e\u786e\u8ba4\u5bc6\u7801\u4e0d\u4e00\u81f4\uff01\", field_name=\"password\")<br> &nbsp; &nbsp; &nbsp; &nbsp;return data<br>\u200b<br>@app.route(\"\/1\")<br>def index1():<br> &nbsp; &nbsp;\"\"\"marshmallow\u63d0\u4f9b\u7684\u94a9\u5b50\u64cd\u4f5c\"\"\"<br> &nbsp; &nbsp;# # \u6a21\u62df\u4ece\u6570\u636e\u5e93\u5f97\u5230\u7684\u6a21\u578b\u5bf9\u8c61<br> &nbsp; &nbsp;# user = User(username=\"\u5c0f\u660e\", password=\"123456\", avatar=\"\/1.png\")<br> &nbsp; &nbsp;# us = UserSchema()<br> &nbsp; &nbsp;# result = us.dump(user)<br> &nbsp; &nbsp;# print(result)<br> &nbsp; &nbsp;# print(user.views_count)<br>\u200b<br> &nbsp; &nbsp;# \u6a21\u62df\u5ba2\u6237\u7aef\u63d0\u4ea4\u8fc7\u6765\u7684\u6570\u636e<br> &nbsp; &nbsp;user_data = {\"username\": \"xiaohong\", \"password\": \"123456\", \"re_password\": \"1123456\", \"avatar\": \"2.gif\"}<br> &nbsp; &nbsp;us = UserSchema()<br> &nbsp; &nbsp;instance = us.load(user_data)<br> &nbsp; &nbsp;print(instance.password)<br>\u200b<br> &nbsp; &nbsp;return \"ok\"<br>\u200b<br>\u200b<br>if __name__ == '__main__':<br> &nbsp; &nbsp;with app.app_context():<br> &nbsp; &nbsp; &nbsp; &nbsp;db.create_all()<br> &nbsp; &nbsp;app.run(debug=True, port=5555)<br>\u200b<\/pre>\n\n\n\n<h2 class=\"wp-block-heading\">\u6a21\u578b\u6784\u9020\u5668(ModelSchema)<\/h2>\n\n\n\n<p>\u7c7b\u4f3cdrf\u63d0\u4f9b\u7684ModelSerializer\uff0cModelSchema\u4e3b\u8981\u662f\u65b9\u4fbf\u5f00\u53d1\u8005\u53ef\u4ee5\u65b9\u4fbf\u7684\u64cd\u4f5c\u6570\u636e\u5e93\u7684\u3002<\/p>\n\n\n\n<p>\u5b98\u65b9\u63d0\u4f9b\u4e86<strong>SQLAlchemyAutoSchema<\/strong>\u548c<strong>SQLAlchemySchema<\/strong>\u8fd92\u4e2a\u6a21\u578b\u6784\u9020\u7c7b\u63d0\u4f9b\u7ed9\u6211\u4eec\u7528\u4e8e\u7f16\u5199\u6a21\u578b\u6784\u9020\u5668\u3002<\/p>\n\n\n\n<p>\u5b98\u65b9\u6587\u6863\uff1a<a href=\"https:\/\/github.com\/marshmallow-code\/marshmallow-sqlalchemy\">https:\/\/github.com\/marshmallow-code\/marshmallow-sqlalchemy<\/a><\/p>\n\n\n\n<figure class=\"wp-block-embed\"><div class=\"wp-block-embed__wrapper\">\nhttps:\/\/marshmallow-sqlalchemy.readthedocs.io\/en\/latest\n<\/div><\/figure>\n\n\n\n<h3 class=\"wp-block-heading\">SQLAlchemySchema<\/h3>\n\n\n\n<pre class=\"wp-block-preformatted\">import re<br>from datetime import datetime<br>from flask import Flask, request<br>from flask_sqlalchemy import SQLAlchemy<br>from flask_marshmallow import Marshmallow<br>\u200b<br>\u200b<br>app = Flask(__name__)<br>app.config[\"DEBUG\"] = True<br>app.config[\"SQLALCHEMY_DATABASE_URI\"]=\"mysql:\/\/root:123@127.0.0.1:3306\/yingming?charset=utf8mb4\"<br>app.config[\"SQLALCHEMY_TRACK_MODIFICATIONS\"] = False<br>app.config[\"SQLALCHEMY_ECHO\"] = True<br>\u200b<br>db = SQLAlchemy()<br>db.init_app(app)<br>\u200b<br>ma = Marshmallow()<br>ma.init_app(app)<br>\u200b<br>\u200b<br>class User(db.Model):<br> &nbsp; &nbsp;__tablename__ = \"tb_user\"<br> &nbsp; &nbsp;id = db.Column(db.Integer, primary_key=True, comment=\"\u4e3b\u952eID\")<br> &nbsp; &nbsp;username = db.Column(db.String(255), index=True, comment=\"\u7528\u6237\u540d\")<br> &nbsp; &nbsp;password = db.Column(db.String(255), comment=\"\u767b\u5f55\u5bc6\u7801\")<br> &nbsp; &nbsp;mobile = db.Column(db.String(15), index=True, comment=\"\u624b\u673a\u53f7\u7801\")<br> &nbsp; &nbsp;sex = db.Column(db.Boolean, default=True, comment=\"\u6027\u522b\")<br> &nbsp; &nbsp;email = db.Column(db.String(255), index=True, comment=\"\u90ae\u7bb1\")<br> &nbsp; &nbsp;created_time = db.Column(db.DateTime, default=datetime.now, comment=\"\u521b\u5efa\u65f6\u95f4\")<br> &nbsp; &nbsp;updated_time = db.Column(db.DateTime, default=datetime.now, onupdate=datetime.now, comment=\"\u66f4\u65b0\u65f6\u95f4\")<br>\u200b<br> &nbsp; &nbsp;def __repr__(self):<br> &nbsp; &nbsp; &nbsp; &nbsp;return \"&lt;%s: %s&gt;\" % (self.__class__.__name__, self.username)<br>\u200b<br>\"\"\"\u6a21\u578b\u7c7b\u5e8f\u5217\u5316\u5668\"\"\"<br>from marshmallow_sqlalchemy import SQLAlchemySchema, auto_field, fields<br>from marshmallow import post_load<br>\u200b<br>\u200b<br>class UserModelSchema(SQLAlchemySchema):<br> &nbsp; &nbsp;\"\"\"<br> &nbsp;  SQLAlchemySchema\u63d0\u4f9b\u4e86\u4e00\u4e2aauto_field\u65b9\u6cd5\u53ef\u4ee5\u81ea\u52a8\u4ece\u6a21\u578b\u4e2d\u63d0\u53d6\u5f53\u524d\u5bf9\u5e94\u5b57\u6bb5\u58f0\u660e\u4fe1\u606f\u5230\u6784\u9020\u5668\u4e2d\uff0c<br> &nbsp;  \u4f46\u662f\uff0c\u6211\u4eec\u9700\u8981\u624b\u52a8\u58f0\u660e\u5e8f\u5217\u5316\u5668\u4e2d\u8c03\u7528\u7684\u54ea\u4e9b\u5b57\u6bb5\uff0c\u6bcf\u4e00\u4e2a\u90fd\u8981\u5199\u4e0a<br> &nbsp;  \"\"\"<br> &nbsp; &nbsp;id = auto_field()<br> &nbsp; &nbsp;username = auto_field()<br> &nbsp; &nbsp;password = auto_field(load_only=True)<br> &nbsp; &nbsp;mobile = auto_field()<br> &nbsp; &nbsp;email = auto_field()<br> &nbsp; &nbsp;created_time = auto_field()<br> &nbsp; &nbsp;sex = auto_field()<br>\u200b<br> &nbsp; &nbsp;class Meta:<br> &nbsp; &nbsp; &nbsp; &nbsp;model = User &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;# \u8bbe\u7f6e\u5f53\u524d\u5e8f\u5217\u5316\u5668\u7ed1\u5b9a\u64cd\u4f5c\u7684\u6a21\u578b\u5bf9\u8c61<br> &nbsp; &nbsp; &nbsp; &nbsp;load_instance = True &nbsp;# \u662f\u5426\u5728\u5e8f\u5217\u5316\u5668\u4e2d\u81ea\u52a8\u5b9e\u4f8b\u5316\u6a21\u578b\u5b9e\u4f8b\u5bf9\u8c61<br>\u200b<br>@app.route(\"\/1\")<br>def index1():<br> &nbsp; &nbsp;\"\"\"\u6a21\u578b\u7c7b\u6784\u9020\u5668\uff1aSQLAlchemySchema\"\"\"<br> &nbsp; &nbsp;# # \u6a21\u62df\u5ba2\u6237\u7aef\u63d0\u4ea4\u7684\u6570\u636e<br> &nbsp; &nbsp;# user_data1 = {'username': '\u5c0f\u660e', 'email': '123@qq.com',\"password\": \"123456\", 'sex': True, 'mobile': '13312345678'}<br> &nbsp; &nbsp;# user_data2 = {'username': '\u5c0f\u7ea2', 'email': '456@qq.com',\"password\": \"123456\", 'sex': False, 'mobile': '13355545678'}<br> &nbsp; &nbsp;# user1 = User(**user_data1)<br> &nbsp; &nbsp;# user2 = User(**user_data2)<br> &nbsp; &nbsp;# db.session.add_all([user1, user2])<br> &nbsp; &nbsp;# db.session.commit()<br>\u200b<br> &nbsp; &nbsp;\"\"\"\u5e8f\u5217\u5316\u4e00\u4e2a\u6570\u636e\"\"\"<br> &nbsp; &nbsp;# # \u8bfb\u53d6\u6570\u636e\u5e93\u4e2d\u7684\u7528\u6237<br> &nbsp; &nbsp;# user = User.query.get(1)<br> &nbsp; &nbsp;# us = UserModelSchema()<br> &nbsp; &nbsp;# data = us.dump(user)<br> &nbsp; &nbsp;# print(data)<br>\u200b<br> &nbsp; &nbsp;# \"\"\"\u5e8f\u5217\u5316\u591a\u4e2a\u6570\u636e\"\"\"<br> &nbsp; &nbsp;# user_list = User.query.all()<br> &nbsp; &nbsp;# us = UserModelSchema()<br> &nbsp; &nbsp;# data = us.dump(user_list, many=True)<br> &nbsp; &nbsp;# print(data)<br>\u200b<br> &nbsp; &nbsp;# \"\"\"\u53cd\u5e8f\u5217\u5316\u4e00\u4e2a\u6570\u636e\"\"\"<br> &nbsp; &nbsp;# user_data = {'username': '\u5c0f\u8f89', 'email': '123@qq.com', \"password\": \"123456\", 'sex': True, 'mobile': '13312345678'}<br> &nbsp; &nbsp;# us = UserModelSchema()<br> &nbsp; &nbsp;# user = us.load(user_data, session=db.session)<br> &nbsp; &nbsp;# db.session.add(user)<br> &nbsp; &nbsp;# db.session.commit()<br> &nbsp; &nbsp;# print(user)<br>\u200b<br> &nbsp; &nbsp;\"\"\"\u53cd\u5e8f\u5217\u5316\u591a\u4e2a\u6570\u636e\"\"\"<br> &nbsp; &nbsp;user_data = {'username': '\u5c0f\u8f89', 'email': '123@qq.com', \"password\": \"123456\", 'sex': True, 'mobile': '13312345678'}<br> &nbsp; &nbsp;us = UserModelSchema()<br> &nbsp; &nbsp;user_list = us.load([user_data, user_data, user_data], session=db.session, many=True)<br> &nbsp; &nbsp;db.session.add_all(user_list)<br> &nbsp; &nbsp;db.session.commit()<br> &nbsp; &nbsp;print(user_list)<br>\u200b<br>\u200b<br>\u200b<br> &nbsp; &nbsp;return \"ok\"<br>\u200b<br>\u200b<br>if __name__ == '__main__':<br> &nbsp; &nbsp;with app.app_context():<br> &nbsp; &nbsp; &nbsp; &nbsp;db.create_all()<br> &nbsp; &nbsp;app.run(debug=True, port=5555)<br>\u200b<\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">SQLAlchemyAutoSchema<\/h3>\n\n\n\n<pre class=\"wp-block-preformatted\">import re<br>from datetime import datetime<br>from flask import Flask, request<br>from flask_sqlalchemy import SQLAlchemy<br>from flask_marshmallow import Marshmallow<br>\u200b<br>\u200b<br>app = Flask(__name__)<br>app.config[\"DEBUG\"] = True<br>app.config[\"SQLALCHEMY_DATABASE_URI\"]=\"mysql:\/\/root:123@127.0.0.1:3306\/yingming?charset=utf8mb4\"<br>app.config[\"SQLALCHEMY_TRACK_MODIFICATIONS\"] = False<br>app.config[\"SQLALCHEMY_ECHO\"] = True<br>\u200b<br>db = SQLAlchemy()<br>db.init_app(app)<br>\u200b<br>ma = Marshmallow()<br>ma.init_app(app)<br>\u200b<br>\u200b<br>class User(db.Model):<br> &nbsp; &nbsp;__tablename__ = \"tb_user\"<br> &nbsp; &nbsp;id = db.Column(db.Integer, primary_key=True, comment=\"\u4e3b\u952eID\")<br> &nbsp; &nbsp;username = db.Column(db.String(255), index=True, comment=\"\u7528\u6237\u540d\")<br> &nbsp; &nbsp;password = db.Column(db.String(255), comment=\"\u767b\u5f55\u5bc6\u7801\")<br> &nbsp; &nbsp;mobile = db.Column(db.String(15), index=True, comment=\"\u624b\u673a\u53f7\u7801\")<br> &nbsp; &nbsp;sex = db.Column(db.Boolean, default=True, comment=\"\u6027\u522b\")<br> &nbsp; &nbsp;email = db.Column(db.String(255), index=True, comment=\"\u90ae\u7bb1\")<br> &nbsp; &nbsp;created_time = db.Column(db.DateTime, default=datetime.now, comment=\"\u521b\u5efa\u65f6\u95f4\")<br> &nbsp; &nbsp;updated_time = db.Column(db.DateTime, default=datetime.now, onupdate=datetime.now, comment=\"\u66f4\u65b0\u65f6\u95f4\")<br>\u200b<br> &nbsp; &nbsp;def __repr__(self):<br> &nbsp; &nbsp; &nbsp; &nbsp;return \"&lt;%s: %s&gt;\" % (self.__class__.__name__, self.username)<br>\u200b<br>\u200b<br>\"\"\"\u6a21\u578b\u7c7b\u5e8f\u5217\u5316\u5668\"\"\"<br>from marshmallow_sqlalchemy import SQLAlchemyAutoSchema, auto_field, fields<br>from marshmallow import post_load<br>\u200b<br>\u200b<br>class UserModelSchema(SQLAlchemyAutoSchema):<br> &nbsp; &nbsp;password = auto_field(load_only=True)<br>\u200b<br> &nbsp; &nbsp;class Meta:<br> &nbsp; &nbsp; &nbsp; &nbsp;model = User<br> &nbsp; &nbsp; &nbsp; &nbsp;include_relationships = True &nbsp;# \u8f93\u51fa\u6a21\u578b\u5bf9\u8c61\u65f6\u540c\u65f6\u5bf9\u5916\u952e\uff0c\u662f\u5426\u4e5f\u4e00\u5e76\u8fdb\u884c\u5904\u7406\uff0cTrue\u8868\u793a\u4e00\u5e76\u8fdb\u884c\u5e8f\u5217\u5316\u5668\uff0c\u7528\u4e8e\u9488\u5bf9\u5e8f\u5217\u5316\u5668\u5d4c\u5957\u8c03\u7528\u7684\u60c5\u51b5<br> &nbsp; &nbsp; &nbsp; &nbsp;include_fk = True &nbsp;# \u5e8f\u5217\u5316\u9636\u6bb5\u662f\u5426\u4e5f\u4e00\u5e76\u8fd4\u56de\u4e3b\u952e<br> &nbsp; &nbsp; &nbsp; &nbsp;sqla_session = db.session &nbsp;# \u6570\u636e\u5e93\u8fde\u63a5\u4f1a\u8bdd\u5bf9\u8c61\uff0c\u9488\u5bf9\u5728\u94a9\u5b50\u88c5\u9970\u5668\u4e2d\u5982\u679c\u5e0c\u671b\u8c03\u7528db\u6570\u636e\u5e93\u56de\u8bdd\u5bf9\u8c61\uff0c\u53ef\u4ee5\u5728\u6b64\u5904\u58f0\u660e\u5b8c\u6210\u4ee5\u540e\uff0c\u4f7f\u7528\u65f6\u901a\u8fc7sql_session\u76f4\u63a5\u8c03\u7528<br> &nbsp; &nbsp; &nbsp; &nbsp;fields = [\"id\", \"username\", \"mobile\", \"email\", \"created_time\", \"sex\", \"password\"]<br>\u200b<br> &nbsp; &nbsp;@post_load(pass_many=True)<br> &nbsp; &nbsp;def post_load(self, data, *args, **kwargs):<br> &nbsp; &nbsp; &nbsp; &nbsp;if type(data) is list:<br> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;\"\"\"\u6279\u91cf\u6dfb\u52a0\u6a21\u578b\"\"\"<br> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;instance = []<br> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;for item in data:<br> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;instance.append(self.Meta.model(**item))<br> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;self.session.add_all(instance)<br> &nbsp; &nbsp; &nbsp; &nbsp;else:<br> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;\"\"\"\u5355\u4e2a\u6dfb\u52a0\u6a21\u578b\"\"\"<br> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;instance = self.Meta.model(**data)<br> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;self.session.add(instance)<br> &nbsp; &nbsp; &nbsp; &nbsp;self.session.commit()<br> &nbsp; &nbsp; &nbsp; &nbsp;return instance<br>\u200b<br>@app.route(\"\/1\")<br>def index1():<br> &nbsp; &nbsp;\"\"\"\u6a21\u578b\u7c7b\u6784\u9020\u5668\uff1aSQLAlchemyAutoSchema\"\"\"<br> &nbsp; &nbsp;# \"\"\"\u5e8f\u5217\u5316\u4e00\u4e2a\u6570\u636e\"\"\"<br> &nbsp; &nbsp;# user = User.query.get(1)<br> &nbsp; &nbsp;# us = UserModelSchema()<br> &nbsp; &nbsp;# data = us.dump(user)<br> &nbsp; &nbsp;# print(data)<br>\u200b<br> &nbsp; &nbsp;# \"\"\"\u5e8f\u5217\u5316\u591a\u4e2a\u6570\u636e\"\"\"<br> &nbsp; &nbsp;# user_list = User.query.all()<br> &nbsp; &nbsp;# us = UserModelSchema()<br> &nbsp; &nbsp;# data = us.dump(user_list, many=True)<br> &nbsp; &nbsp;# print(data)<br>\u200b<br>\u200b<br> &nbsp; &nbsp;\"\"\"\u53cd\u5e8f\u5217\u5316\u4e00\u4e2a\u6570\u636e\"\"\"<br> &nbsp; &nbsp;user_data = {'email': '123@qq.com', 'username': 'xiaoming', 'sex': True, 'mobile': '13312345678', 'password': '56566666'}<br> &nbsp; &nbsp;us = UserModelSchema()<br> &nbsp; &nbsp;instance = us.load(user_data)<br> &nbsp; &nbsp;print(instance)<br>\u200b<br> &nbsp; &nbsp;# \"\"\"\u53cd\u5e8f\u5217\u5316\u591a\u4e2a\u6570\u636e\"\"\"<br> &nbsp; &nbsp;# user_data = {'email': '123@qq.com', 'username': 'xiaoming', 'sex': True, 'mobile': '13312345678', 'password': '56566666'}<br> &nbsp; &nbsp;# us = UserModelSchema()<br> &nbsp; &nbsp;# instance_list = us.load([user_data, user_data, user_data], many=True)<br> &nbsp; &nbsp;# print(instance_list)<br>\u200b<br> &nbsp; &nbsp;return \"ok\"<br>\u200b<br>if __name__ == '__main__':<br> &nbsp; &nbsp;with app.app_context():<br> &nbsp; &nbsp; &nbsp; &nbsp;db.create_all()<br> &nbsp; &nbsp;app.run(debug=True, port=5555)<br>\u200b<\/pre>\n","protected":false},"excerpt":{"rendered":"<p>\u5b98\u65b9\u6587\u6863\uff1ahttps:\/\/marshmallow.readthedocs.io\/en\/latest\/ Mars [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"closed","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[1],"tags":[],"class_list":["post-21","post","type-post","status-publish","format-standard","hentry","category-uncategorized"],"_links":{"self":[{"href":"https:\/\/22z.top\/index.php?rest_route=\/wp\/v2\/posts\/21","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/22z.top\/index.php?rest_route=\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/22z.top\/index.php?rest_route=\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/22z.top\/index.php?rest_route=\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/22z.top\/index.php?rest_route=%2Fwp%2Fv2%2Fcomments&post=21"}],"version-history":[{"count":1,"href":"https:\/\/22z.top\/index.php?rest_route=\/wp\/v2\/posts\/21\/revisions"}],"predecessor-version":[{"id":22,"href":"https:\/\/22z.top\/index.php?rest_route=\/wp\/v2\/posts\/21\/revisions\/22"}],"wp:attachment":[{"href":"https:\/\/22z.top\/index.php?rest_route=%2Fwp%2Fv2%2Fmedia&parent=21"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/22z.top\/index.php?rest_route=%2Fwp%2Fv2%2Fcategories&post=21"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/22z.top\/index.php?rest_route=%2Fwp%2Fv2%2Ftags&post=21"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}