环境 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()