Error in user YAML: (<unknown>): found a tab character that violate indentation while scanning a plain scalar at line 3 column 3
---
- oeasy Python 0587
- 这是 oeasy 系统化 Python 教程,从基础一步步讲,扎实、完整、不跳步。愿意花时间学,就能真正学会。
- 本教程同步发布在:
- 个人网站: `https://oeasy.org`
- 蓝桥云课: `https://www.lanqiao.cn/courses/3584`
- GitHub: `https://github.com/overmind1980/oeasy-python-tutorial`
- Gitee: `https://gitee.com/overmind1980/oeasypython`
---- 上次直接使用psycopg访问pg数据库
- 并且查询到了相应的数据
- 可以通过表单注册用户吗?🤔
<form action="/regist" method="POST">
username:<input name="username"/><br/>
password:<input name="password"/><br/>
<input type="submit" name="regist"><br/>
</form>- 建立这个网页文件之后
- 准备制作对于/regist的处理函数
- 注意是用的表格是login表
from flask import Flask
from flask import render_template
from flask import request
from flask import redirect
import traceback
import psycopg
app = Flask("__name__")
@app.route('/')
def hello():
conninfo = "postgres://postgres:oeasypg@localhost:5432/oeasydb"
with psycopg.connect(conninfo) as conn:
with conn.cursor() as cur:
cur.execute("SELECT * FROM login;")
records = cur.fetchall()
return render_template("show_data.html", l = records)
@app.route("/regist", methods=['POST', 'GET'])
def regist():
username = request.form["username"]
password = request.form["password"]
print(username)
conninfo = "postgres://postgres:oeasypg@localhost:5432/oeasydb"
with psycopg.connect(conninfo) as conn:
with conn.cursor() as cur:
try:
sql = "INSERT INTO login(username, password) VALUES(%s, %s)"""
t = (username,password)
cur.execute(sql,t)
conn.commit()
except Exception:
print(traceback.print_exc())
return username + " already exists"
else:
return redirect("/")
if __name__ == "__main__":
app.run(debug=True)-
这样就将pg数据库驱动起来了
-
为什么可以在后台驱动数据库呢?
-
因为psycopg可以驱动postgres
-
什么是驱动呢?
- driver驾驶员
- 最早来自于驾驶马车
- 后来工业革命后也指蒸汽机车
-
仪表盘的来历
- 仪表盘的作用是监控引擎运行情况
-
driver在电脑系统中也指驱动
- 硬件的驱动程序
- 文件系统驱动器
- 主动控制引擎的人
-
给用户名
- 添加唯一性约束
- 修改login表
ALTER TABLE login
ADD CONSTRAINT unique_user UNIQUE(username);
- 同样的用户名
- 无法重复插入了
- 尝试在网页中插入
- 可以看到网页插入已经有的用户名
- 会报错
- 违反了唯一性约束
- 这次 通过表单注册用户
- 顺利完成
- 数据库 连接语句 重复执行
- 可以提取出来吗?🤔
- 下次再说!
- 本文来自 oeasy Python 系统教程。
- 想完整、扎实学 Python,
- 搜索 oeasy 即可。








