|
| 1 | +import re |
| 2 | + |
| 3 | +from flask import Flask, jsonify, request |
| 4 | +from webargs import fields |
| 5 | +from webargs.flaskparser import use_args |
| 6 | + |
| 7 | +app = Flask("hello") |
| 8 | + |
| 9 | + |
| 10 | +@app.route("/api/login", methods=["POST"]) |
| 11 | +@use_args({"username": fields.Str(required=True)}, |
| 12 | + location="json") |
| 13 | +def login(args): |
| 14 | + name = args['username'] |
| 15 | + password = args['password'] |
| 16 | + return jsonify({"code": 200, "msg": "ok"}) |
| 17 | + |
| 18 | + |
| 19 | +@app.route("/api/login", methods=["POST"]) |
| 20 | +def login3(): |
| 21 | + data = request.get_json() |
| 22 | + email = data.get("email") |
| 23 | + if not email or re.match(r"(^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$)", email): |
| 24 | + return jsonify({"code": 400, "msg": "参数有误"}), 400 |
| 25 | + password = data.get("password") |
| 26 | + if not password or len(password) < 6: |
| 27 | + return jsonify({"code": 400, "msg": "参数有误"}), 400 |
| 28 | + # 数据库查询 |
| 29 | + return jsonify({"code": 200, "msg": "ok"}) |
| 30 | + |
| 31 | + |
| 32 | +from webargs import fields, ValidationError |
| 33 | + |
| 34 | + |
| 35 | +def must_exist_in_db(val): |
| 36 | + if val != 1: |
| 37 | + raise ValidationError("id not exist") |
| 38 | + |
| 39 | + |
| 40 | +hello_args = {"name": fields.Str(missing="Friend"), |
| 41 | + "id": fields.Integer(required=True, validate=must_exist_in_db)} |
| 42 | + |
| 43 | + |
| 44 | +@app.route("/", methods=["GET"]) |
| 45 | +@use_args(hello_args, location="query") |
| 46 | +def hello(args): |
| 47 | + """A welcome page.""" |
| 48 | + return jsonify({"message": "Welcome, {}!".format(args["name"])}) |
| 49 | + |
| 50 | + |
| 51 | +@app.errorhandler(422) |
| 52 | +@app.errorhandler(400) |
| 53 | +def handle_error(err): |
| 54 | + headers = err.data.get("headers", None) |
| 55 | + messages = err.data.get("messages", ["Invalid request."]) |
| 56 | + if headers: |
| 57 | + return jsonify({"errors": messages}), err.code, headers |
| 58 | + else: |
| 59 | + return jsonify({"errors": messages}), 400 |
| 60 | + |
| 61 | + |
| 62 | +# |
| 63 | + |
| 64 | +if __name__ == '__main__': |
| 65 | + app.run(port=5000) |
0 commit comments