(⼩菜鸟专属)flask+pycharm初学与配置(⼆,数据库的配置和使⽤sqlite3)@[TOC](flask+pycharm 初学与配置 (⼆,数据库的配置和使⽤sqlite3) )
Flask – 创建并配置数据库
将项⽬虚拟环境venv⽂件夹配置到项⽬根⽬录,⽅便更改。菜鸟教程python2
1. 在项⽬根⽬录⽂件夹下创建app.sql,(⽂件名随意),settings(必须为此⽂件名,配置⽂件,同于django的settings)。
app.sql写⼊创建数据库和表语句
drop table if exists entries;
create table student (
id integer primary key autoincrement,
name string not null,
text string not null
);
setting写⼊sqlite3的配置
# configuration
DATABASE = 'app.db'
DEBUG = True
SECRET_KEY = 'development key'
USERNAME = 'admin'
PASSWORD = 'default'
2. 配置 app.py(py⽂件随意)。
from flask import Flask
import sqlite3,json,settings
from flask import Flask, request, session, g, redirect, url_for, \
abort, render_template, flash,jsonify
app = Flask(__name__)
#将settings.py⽂件中的配置参数写⼊
⽅法⼀:
⽅法⼆:
#fig.from_envvar('FLASKR_SETTINGS', silent=True)
#打印出我们的配置
fig['DATABASE'])
与数据库创建连接  connect:连接
@ute('/')
def connect_db():
fig['DATABASE'])
# @ute('/'):
# def hello_world():
#    return 'Hello World!'
#
#
if __name__ == '__main__':
app.run()
# connect_db()
3. 个⼈使⽤的是pycharm,在Terminal运⾏命令
python app.py
sqlite3 app.db < app.sql (’<’ :这⾥的⼩于号指写⼊的意思)
在运⾏这段sqlite3代码时,⽤于没有sqlite3,pip也没法下载,后来在菜鸟教程收集到:
4. 数据库请求连接
正所谓,做完事把门关上,
#请求前调⽤(开门)
@app.before_request
def before_request():
g.db = connect_db()
#请求后调⽤(关门)
@ardown_request
def teardown_request(exception):
g.db.close()
5.
Flask – 数据库的增删查改(接⼝)
所⽤知识点(这些会在下⼀章讲到):
RESTful风格做flask项⽬
(这样单独运⾏html⽂件就可以操作数据库喽)
#以下为⼩编初学所写:
from contextlib import closing
from flask import Flask, jsonify
from flask_cors import CORS
import sqlite3
from flask import Flask, request, session, g
from flask_restful import Api, Resource
import settings
app = Flask(__name__)
CORS(app)
api = Api(app)
#连接数据库
def connect_db():
fig['DATABASE'])
#创建数据库另⼀种⽅法
def init_db():
with closing(connect_db()) as db:
with app.open_resource('schema.sql') as f:
print(ad()))
db.cursor().ad().decode('GBK'))
dbmit()
@app.before_request
def before_request():
g.db = connect_db()
@ardown_request
def teardown_request(exception):
g.db.close()
class StudentList(Resource):
# 获得所有学⽣
def get(self):
cur = ute("select id,username,age from student")
students = cur.fetchall()
return jsonify([{"id": student[0], "name": student[1], "age": student[2]} for student in students])
# 添加⼀个学⽣
def post(self):
data = _json()
ute('insert into student (username, age) values (?, ?)',
[data['name'], data['age']])
g.dbmit()
return jsonify(data)
class Student(Resource):
def get(self, stu_id):
cur = ute("select username,age from student where id=?", [stu_id])
student = cur.fetchone()
return jsonify(student)
#修改
def put(self, stu_id):
data = _json()
username = data['name']
age = data['age']
ute("update student set username=?,age=?", [username, age])
g.dbmit()
return jsonify({"msg":"修改成功!"})
#删除
def delete(self, stu_id):
ute("delete from student where id=?", [stu_id])
g.dbmit()
return jsonify({"msg":"删除成功!"})
api.add_resource(StudentList, '/students')
api.add_resource(Student, '/student/<stu_id>')
if __name__ == '__main__':
app.run()
index.html(运⾏此⽂件即可)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<script src="js/vue2.6.js" type="text/javascript" charset="utf-8"></script>
<script src="js/axios.js" type="text/javascript" charset="utf-8"></script>
<link rel="stylesheet" type="text/css" href="css/bootstrap-3.3.7.css" />
</head>
<body>
<div id="app">
<div class="panel panel-primary">
<div class="panel-heading">
<h3 class="panel-title">学⽣管理</h3>
</div>
<div class="panel-body form-inline">
<label>
姓名:
<input type="text" class="form-control" v-model="name" ref="name">
</label>
<label>
年龄:
<input type="text" class="form-control" v-model="age" @="add()" ref="age">    </label>
<input type="button" value="添加" class="btn btn-primary" v-on:click="add()">
<label>
<input type="text" class="form-control" v-model="keywords">
<button type="button">搜索</button>
</label>
</div>
</div>
<table class="table table-bordered table-hover table-striped">
<thead>
<tr>
<th>id</th>
<th>姓名</th>

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。