zoukankan      html  css  js  c++  java
  • flask入门 快速入门后台写接口【API】【Python3】【无前端】【json格式】

    学习地址:
    https://www.bilibili.com/video/BV1v7411M7us?from=search&seid=13948293183709374198&spm_id_from=333.337.0.0

    flash官网手册地址:
    https://dormousehole.readthedocs.io/en/latest/#api

    https://github.com/BeyondLam/bili

    新建项目

    1)虚拟环境

    1. pycharm创建
    2. Linux下创建(服务器)
      • python3 -m venv venv(创建虚拟环境)
      • source venv/bin/activate(激活环境)


    安装flask插件包

    1)方式一:pycharm安装

    2)方式二:命令行安装

    $ pip install flask

    新建hello_world.py

    from flask import Flask
    
    app = Flask(__name__)
    
    @app.route('/')
    def hello_world():
        return "Hello World!"
    
    
    if __name__ == '__main__':
        app.run()
    

    运行

    访问: http://127.0.0.1:5000/

    返回 Hello World!

    debug调适

    打断点--》debug运行 --》访问打断点的路由器http://127.0.0.1:5000/--》进入断点的位置--》单步调适

    四、flask应用

    from flask import Flask
    
    app = Flask(__name__)
    
    # http://127.0.0.1:5000/index
    @app.route('/index')
    def hello_index():
        return "Hello Index!"
    
    
    # http://127.0.0.1:5000/
    @app.route('/')
    def hello_world():
        return "Hello World!"
    
    
    if __name__ == '__main__':
        # 在服务器上,不加host=’0.0.0.0‘只能本服务器内网访问
        app.run(host='0.0.0.0')
    
    

    flask路由

    # http://127.0.0.1:5000/index
    @app.route('/index')
    def hello_index():
        return "Hello Index!"
    
    
    # http://127.0.0.1:5000/
    @app.route('/')
    def hello_world():
        return "Hello World!"
    

    变量规则

    通过把 URL 的一部分标记为 <variable_name> 就可以在 URL 中添加变量。标记的 部分会作为关键字参数传递给函数。通过使用 converter:variable_name ,可以 选择性的加上一个转换器,为变量指定规则。请看下面的例子:

    from markupsafe import escape
    
    @app.route('/user/<username>')
    def show_user_profile(username):
        # show the user profile for that user
        return f'User {escape(username)}'
    
    @app.route('/post/<int:post_id>')
    def show_post(post_id):
        # show the post with the given id, the id is an integer
        return f'Post {post_id}'
    
    @app.route('/path/<path:subpath>')
    def show_subpath(subpath):
        # show the subpath after /path/
        return f'Subpath {escape(subpath)}'
    

    转换器类型:

    类型 说明
    string (缺省值) 接受任何不包含斜杠的文本
    int 接受正整数
    float 接受正浮点数
    path 类似 string ,但可以包含斜杠
    uuid 接受 UUID 字符串

    唯一的 URL / 重定向行为

    以下两条规则的不同之处在于是否使用尾部的斜杠。:

    @app.route('/projects/')
    def projects():
        return 'The project page'
    
    @app.route('/about')
    def about():
        return 'The about page'
    

    projects 的 URL 是中规中矩的,尾部有一个斜杠,看起来就如同一个文件 夹。访问一个没有斜杠结尾的 URL ( /projects )时 Flask 会自动进行重 定向,帮您在尾部加上一个斜杠( /projects/ )。

    about 的 URL 没有尾部斜杠,因此其行为表现与一个文件类似。如果访问这 个 URL 时添加了尾部斜杠(/about/ )就会得到一个 404 “未找到” 错 误。这样可以保持 URL 唯一,并有助于搜索引擎重复索引同一页面。

    flask重定向

    # http://192.168.0.106:5000/baidu
    # 重定向 需要引入 from flask import redirect
    @app.route('/baidu') ## 加int后,参数只能传int
    def baidu():
        return redirect("https://baidu.com")
    

    JSON 格式的 API demo1

    @app.route("/me")
    def me_api():
        userInfo = {
            "username": "lisi",
            "theme": "user.theme",
            "age": "30",
        }
        return userInfo
    

    访问:

    http://192.168.0.106:5000/me

    返回:

    {
      "age": "30",
      "theme": "user.theme",
      "username": "lisi"
    }
    

    JSON 格式的 API demo2

    # http://192.168.0.106:5000/post_first
    # post请求
    """
    请求参考 post raw
    {
        "age": 30,
        "theme": "user.theme",
        "username": "lisi"
    }
        
    返回数据
    # return rs
    
    {
        "age": 40,
        "code": 200,
        "data": null
    }
     =========================================================
    # return jsonify(age=age, code=rs["code"], qData=qData)
    {
        "age": 30,
        "code": 200,
        "qData": {
            "age": 30,
            "theme": "user.theme",
            "username": "lisi"
        }
    }
    """
    from flask import Flask, request, jsonify
    
    @app.route('/post_first', methods=["POST"])
    def post_first():
        try:
            qData = request.get_json()
            print(qData)  # {'age': '30', 'theme': 'user.theme', 'username': 'lisi'}
            username = qData.get("username1")
            age = qData.get("age")
            if not all([username,age]):
                return jsonify(msg="username or age is not empty")
    
            print(username)  # 没有key的参数  打印None  返回给前端null
            rs = {
                "code": 200,
                "data": username,
                "age": age + 10,
            }
            # 以下返回json格式的数据
            # return rs
            # return jsonify(age=age, code=rs["code"], qData=qData)
            return jsonify({"age": age, "code": rs["code"], "qData": qData})
    
    
        except Exception as e:
            errMsg = f"出错了, e:{e}"
            print(errMsg)
            return jsonify(msg=errMsg)
    
    
    

    Cookies

    要访问 cookies ,可以使用 cookies 属性。可以使用响应 对象 的 set_cookie 方法来设置 cookies 。请求对象的 cookies 属性是一个包含了客户端传输的所有 cookies 的字典。在 Flask 中,如果使用 会话 ,那么就不要直接使用 cookies ,因为 会话 比较安全一些。

    读取 cookies:

    from flask import request
    
    @app.route('/')
    def index():
        username = request.cookies.get('username')
        # use cookies.get(key) instead of cookies[key] to not get a
        # KeyError if the cookie is missing.
    

    储存 cookies:

    from flask import make_response
    
    @app.route('/')
    def index():
        resp = make_response(render_template(...))
        resp.set_cookie('username', 'the username')
        return resp
    

    注意 cookies 设置在响应对象上。通常只是从视图函数返回字符串, Flask 会把它们转换为响应对象。如果您想显式地转换,那么可以使用 make_response() 函数,然后再修改它。

    会话

    除了请求对象之外还有一种称为 session 的对象,允许您在不同请求 之间储存信息。这个对象相当于用密钥签名加密的 cookie ,即用户可以查看您的 cookie ,但是如果没有密钥就无法修改它。

    使用会话之前您必须设置一个密钥。举例说明:

    Set the secret key to some random bytes. Keep this really secret!
    app.secret_key = b'_5#y2L"F4Q8z\n\xec]/'

    code demo

    from flask import Flask, request, jsonify
    from flask import redirect
    from flask import session
    
    # from werkzeug.middleware.proxy_fix import ProxyFix
    # from flask_esearch import ESearch  # https://pypi.org/project/Flask-ESearch/
    app = Flask(__name__)
    app.secret_key = "12313123"
    
    # http://127.0.0.1:5000/try/login
    @app.route("/try/login", methods=["POST"])
    def login():
        '''
        username admin
        password 123455
        '''
    
        get_data = request.get_json()
        user_name = get_data.get("username")
        password = get_data.get("password")
    
        if not all([user_name,password]):
            return jsonify(errCode=400, msg="username or password not emtpy")
    
        if user_name == "admin" and password == "123456":
            session['user_name'] = "admin"
            session['admin_id'] = "111"
            session['avatar'] = "user_avatar.jpg"
            return jsonify(errCode=200, msg="login success")
        else:
            return jsonify(errCode=400, msg="username or password error")
    
    # http://127.0.0.1:5000/try/logout
    @app.route("/try/logout", methods=["GET"])
    def logout():
        # session.pop('user_name',None)
        session.clear()
        return jsonify(errCode=200, msg="logout success")
    
    # http://127.0.0.1:5000/session
    @app.route("/session", methods=["GET"])
    def check_session():
        # 查检登陆状态
        s_data = {
            "user_name": session.get("user_name"),
            "admin_id": session.get("admin_id"),
            "avatar": session.get("avatar"),
        }
        # 从session中获取用户数据
        if s_data["user_name"] is not None:
            return jsonify(errCode=200, msg="true", data=s_data)
        else:
            return jsonify(errCode=400, msg="not login", data=s_data)
    
    
    
    # http://127.0.0.1:5000/post_first
    # post请求
    """
    请求参考 post raw
    {
        "age": 30,
        "theme": "user.theme",
        "username": "lisi"
    }
        
    返回数据
    # return rs
    
    {
        "age": 40,
        "code": 200,
        "data": null
    }
     =========================================================
    # return jsonify(age=age, code=rs["code"], qData=qData)
    {
        "age": 30,
        "code": 200,
        "qData": {
            "age": 30,
            "theme": "user.theme",
            "username": "lisi"
        }
    }
    """
    
    
    @app.route('/post_first', methods=["POST"])
    def post_first():
        try:
            qData = request.get_json()
            print(qData)  # {'age': '30', 'theme': 'user.theme', 'username': 'lisi'}
            username = qData.get("username1")
            age = qData.get("age")
            if not all([username, age]):
                return jsonify(msg="username or age is not empty")
    
            print(username)  # 没有key的参数  打印None  返回给前端null
            rs = {
                "code": 200,
                "data": username,
                "age": age + 10,
            }
            # 以下返回json格式的数据
            # return rs
            # return jsonify(age=age, code=rs["code"], qData=qData)
            return jsonify({"age": age, "code": rs["code"], "qData": qData})
    
    
        except Exception as e:
            errMsg = f"出错了, e:{e}"
            print(errMsg)
            return jsonify(msg=errMsg)
    
    
    # http://192.168.0.106:5000/me
    @app.route("/me")
    def me_api():
        # app.wsgi_app = ProxyFix(app.wsgi_app)
    
        userInfo = {
            "username": "lisi",
            "theme": "user.theme",
            "age": "30",
        }
        app.logger.debug('A value for debugging')
        app.logger.warning('A warning occurred (%d apples)', 42)
        app.logger.error('An error occurred')
        return userInfo
    
    
    # http://192.168.0.106:5000/baidu
    # 重定向 需要引入 from flask import redirect
    @app.route('/baidu')  ## 加int后,参数只能传int
    def baidu():
        return redirect("https://baidu.com")
    
    
    # http://192.168.0.106:5000/number_int/2
    # 传递参数 规定参数类型 int / float / path / uuid
    @app.route('/number_int/<int:number>')  ## 加int后,参数只能传int
    def hello_number_int(number):
        return "number: %s!" % (number + number)  # number: 4!
    
    
    # http://192.168.0.106:5000/number_float/2.1
    # 传递参数 规定参数类型 int / float / path / uuid
    @app.route('/number_float/<float:number>')  # 加float后,参数只能传float
    def hello_number_float(number):
        return "number: %s!" % (number + number)  # number: 4.2!
    
    
    # http://127.0.0.1:5000/hello/haima
    # 传递参数
    @app.route('/hello/<username>')
    def hello_hello(username):
        return "Hello %s!" % username
    
    
    # http://127.0.0.1:5000/index
    @app.route('/index')
    def hello_index():
        return "Hello Index!"
    
    
    # http://127.0.0.1:5000/
    @app.route('/')
    def hello_world():
        return "Hello World!"
    
    
    if __name__ == '__main__':
        # 在服务器上,不加host=’0.0.0.0‘只能本服务器内网访问  port=5001 指定端口
        app.run(host='0.0.0.0', port=5000)
    
    

    flask扩展仓库

    https://pypi.org/search/?c=Framework+%3A%3A+Flask&o=&q=+Flask-mysql&page=4

    [Haima的博客] http://www.cnblogs.com/haima/
  • 相关阅读:
    阿里P8聊并发编程:线程中断和终止
    浅谈Java中的锁:Synchronized、重入锁、读写锁
    史上最全Java面试题!进程,线程相关部分下篇(带全部答案)
    @史上最全Java面试题!关于volatile关键字篇(带全部答案)
    @史上最全Java面试题!进程,线程相关部分上篇(带全部答案)
    一道号称“史上最难”java面试题引发的线程安全思考,掌握了吗?
    stopWatch
    mysql语句及执行计划
    Awr
    文件下载
  • 原文地址:https://www.cnblogs.com/haima/p/15547228.html
Copyright © 2011-2022 走看看