An Introduction to Flask 16~18

来源:互联网 发布:朝鲜扫码软件 编辑:程序博客网 时间:2024/05/18 13:04

视频中用的是SQLite,CS50中用的也是SQLite,Django中默认使用的也是SQLite。
反正数据库、关系型数据库这些概念都是一样的。

SQLite databases do not have a server, so hostname, username, and password are omitted and database is the filename of a disk file.

有篇笔记讲SQL,比较详细:CS50 2016 Week9 学习笔记

视频中用了flask-sqlalchemy来管理数据库。
然后又有flask_login帮助写用户注册、登录等。
还有flask_mail能发邮件给用户来确认登录。
再加上flask_bootstrapflask_wtf这些,天啊真的好多扩展

flask文档中:

Flask is a microframework for Python based on Werkzeug, Jinja 2 and good intentions.


书中讲的好详细。

A database stores application data in an organized way. The application then issues queries to retrieve specific portions as they are needed.

The most commonly used databases for web applications are those based on the relational model, also called SQL databases in reference to the Structured Query Language they use.

书中接着讲了SQL数据库和NoSQL数据库的区别。
然后接着讲关系型数据库。
又讲到讲Flask中使用第三方包,可以操作各种数据库。或者使用SQLAlchemy直接处理python对象,而不用处理如表、文档或查询语言此类的数据库实体。

Python has packages for most database engines, both open source and commercial. Flask puts no restrictions on what database packages can be used, so you can work with MySQL, Postgres, SQLite, Redis, MongoDB, or CouchDB if any of these is your favorite.

接着是flask-sqlalchemy

Flask-SQLAlchemy is a Flask extension that simplifies the use of SQLAlchemy inside Flask applications. SQLAlchemy is a powerful relational database framework that supports several database backends.

In Flak-SQLAlchemy, a database is specified as a URL.
(这里用了SQLite,数据库是一个文件,URL就是文件路径)


Using Flask-SQLAlchely

遇到了小问题,flask应用总是报错,找不到users表。
还好找到了解决办法,写完代码(创建User类)后,在打开python shell:

>>> from hello import db  #导入数据库>>>db.create_all()  #创建关系表

这里数据库是一个文件data.sqlite3,关系表对应着文件中的数据:

这里写图片描述

然后flask代码:

from flask import Flask, render_template, requestfrom flask_bootstrap import Bootstrapfrom flask_wtf import FlaskFormfrom wtforms import StringField, SubmitField, validatorsfrom flask_sqlalchemy import SQLAlchemyapp = Flask(__name__)# 这里设置的是SQLite数据库(文件)的绝对路径。app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///C:\\Users\\Administrator\\Desktop\\OREILLY\\6a\\data.sqlite3'app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True   # 运行时根据命令行提示设置的。bootstrap = Bootstrap(app)db = SQLAlchemy(app)  #使用SQLAlchemy包装一下,实例化一个db对象,时候使用db对象创建一个关系表,就能存储、查询数据了。class NameForm(FlaskForm):    name = StringField("What's your name",[validators.required(),validators.Length(min=1,max=13)])    submit = SubmitField('Submit')#每一个关系表对应着一个类,类中的属性对应着表中的字段。class User(db.Model):    __tablename__ = "users"    id = db.Column(db.Integer, primary_key=True) #设置的表的第一列为id,同时设置为主键,能唯一确定一行元素。    name = db.Column(db.String(16), index=True, unique=True)  #表中的另一列记录着名字信息。    def __repr__(self):  #这个方法很多类中都会有,这里可以用来输出表的名字。        return '<User {0}>'.format(self.name)@app.route('/',methods=["GET","POST"])def index():    name = None  #刚开始不会显示 HELLO ,"Name"    new = False  # 对应着index.html模板中的 Happy to see you again(数据库中有了名字后)    form = NameForm()    if request.method == "POST" and form.validate_on_submit():        name = form.name.data  #将用户输入的名字存储在name变量中。        form.name.data = ''        # 如果数据库中的users表中差不到用户输入的名字,进行之后的操作(将名字写入数据库)        if User.query.filter_by(name=name).first() is None:            db.session.add(User(name=name))            db.session.commit()            new = True # 默认的new=False,这里改成了True,即用户第一次输入名字,会显示 pleased to meet you    return render_template("index.html", name=name, form=form, new=new)@app.errorhandler(404) def page_not_found(e):    return render_template("404.html"),404if __name__ == '__main__':    app.secret_key = "It's a  Secret key"    app.run(debug=True)

刚打开网页(没有提交表单),if语句不成立,只会显示这个Web表单:

这里写图片描述

然后第一次输入名字,提交后,数据库中查不到这个名字,会把名字写进数据库,同时显示pleased to meet you

这里写图片描述

输入相同的名字,提交表单。flask应用在数据库中查到了这个名字,会显示happy to see you again

这里写图片描述

然后视频中针对flask-sqlalchemy,讲了写入数据、查询数据、删除记录的方法。
官方文档中也有对应的说明。

写入数据:

>>> db.session.add(me)>>> db.session.commit()

查询数据:

>>> peter = User.query.filter_by(username='peter').first()>>> peter.id1>>> peter.emailu'peter@example.org'>>> User.query.filter(User.email.endswith('@example.com')).all()[<User u'admin'>, <User u'guest'>]

删除记录:

>>> db.session.delete(me)>>> db.session.commit()

Password Security

上面的SQLite数据库就是一个文件,甚至不需要登录名和密码。

如果在将网站中用户登录信息,特别是密码,直接写进文件里,会不安全。

视频中从werkzeug库中导入了包装密码的方法,不直接将密码写进数据库中。


Flask-Login

连用户登陆都有扩展包。

pip install flask_login

官方文档:Flask-Login

前辈们写好代码,别人根据API介绍来使用这些方法,就能做出东西。

但是,学习的话,只会使用别人写的代码,不会自己写代码,终究不是好事儿。

作者的github 中有各个版本代码的记录。
下载到本地后,使用git checkout 5a这样的命令,文件夹会变成对应版本代码。

没找到这个login in版本的。

以前,学习过这个用户注册、登录。
真需要用到flask_login 的时候,再查文档。

原创粉丝点击