• 使用flask写移动端API


    环境 python 3.7

    使用pip 安装falsk

    pip3 install flask
    #!flask/bin/python
    from flask import Flask, jsonify, render_template, Request, Response
    from flask import flask_bootstrap
    from flask import g
    import sqlite3
    import time
    import datetime
    
    import dbInit
    
    app = Flask(__name__)
    
    def connect_db():
        conn = sqlite3.connect("testDB.db3",check_same_thread = False)
        return conn
    
    conn = connect_db()
    cursor = conn.cursor()
    
    #通过在before_request/teardown_request hook方法可以在每次请求连接开始之前和结束时候连接和断开数据库
    @app.before_request
    def before_request():
        g.db = connect_db()
    
    @app.teardown_request
    def teardown_request(exception):
        if hasattr(g, 'db'):
            g.db.close()
    
    #但是该方法的缺陷在于没有请求就没法连接数据库,所以如果要在脚本或者python的交互式终端中访问数据库需要这样做
    with app.test_request_context():
        app.preprocess_request()
            #now you can use the g.db object
            # dbInit.init_db()
    
    #缺点,不能离开请求上下文依赖,解决方法
    def get_connection():
        db = getattr(g, '_db', None)
        if db is None:
            db = g._db = connect_db()
        return db
    #缺点必须使用 db = get_connection() 而不是仅仅直接使用g.db 来访问数据库连接
    
    def initSqliteBD():
        connect_db()
        createUserTable()
    
    def createUserTable():
        cursor.execute('create table user (id varchar(20) primary key, name varchar(20))')
        conn.commit()
    
    def deleteTable(tableName):
        cursor.execute('delete table')
        conn.commit()
    
    def insertAnUser(id, name):
        cursor.execute('insert into user values(?,?)',(id,name))
        conn.commit()
    
    def queryAllUser():
        cursor.execute('select id, name from user')
        conn.commit()
        return cursor.fetchone()
    
    #===========page route==========
    @app.route('/')
    def index():
        return "Hello, World!"
    
    @app.route('/index/<name>')
    def home(name=None):
        return render_template('index.html',name = name)
    
    @app.route('/register')
    def regiser():
        return render_template('register.html')
    
    #===========api route==========
    @app.route('/todo/api/v1.0/user/register', methods=['GET'])
    def createAnUser():
        insertAnUser(1,'Jarvis')
        return jsonify('ok')
    
    @app.route('/todo/api/v1.0/users',methods=['GET'])
    def get_users():
        # return jsonify({"users":users})
        return jsonify(queryAllUser())
    
    @app.route('/todo/api/v1.0/users/<string:userName>',methods=['GET'])
    def get_user(userName):
        users = [{"userName":"Jarvis","age":"24"},{"userName":"Mike","age":"23"}]
        user = filter(lambda t: t[userName] == userName, users)
        if len(user) == 0:
            abort(404)
        return jsonify({"task":task[0]})
    
    if __name__ == '__main__':
        app.run(debug=True)
        initSqliteBD()
  • 相关阅读:
    解析大型.NET ERP系统 20条数据库设计规范
    vi显示行号
    shell awk
    Linux使用Shell脚本实现ftp的自动上传下载
    MySQL Replication的Reset slave重置命令
    怎么样调整FreeBSD时区问题
    Basic Memory Structures
    States of Integrity Constraints
    Merging into a Table: Example
    oracle 单独开始一个事物的写法 。
  • 原文地址:https://www.cnblogs.com/wjw-blog/p/10279424.html
Copyright © 2020-2023  润新知