Rust Shrugged

Programming and a free mind

Flask Web Development Notes

这是我暑假看 Miguel 的那本著名狗书时的笔记,书的版本是最新的 second edition。当时看的是原文版,以后会写一篇文章说阅读英语原文的经验

Ch2 Basic Application Structure

Run an app

1
2
3
export FLASK_APP=name.py
export FLASK_DEBUG=1
flask run

Dynamic route

Flask supports the types string, int, float, and path for routes. The path type is a special string type.

Response

view function could take as much as three arguments, status code and a dictionary of headers

1
2
3
@app.route('/')
def index():
return '<h1>Bad Request</h1>', 400

Compatibility with older version

app.run(debug=True)

app.add_url_rule(): builds the map between URL and view function

1
flask run --host 0.0.0.0
1
git reset --hard
1
sudo apt-get install sqlite3 libsqlite3-dev

Ch3 Templates

business logic and presentation logic, Jinja2 takes the work of presentation. More specifically, the application only sends variables to Jinja2, after that how the HTML page is presented is up to Jinja2.

What this chapter’s mainly about

Static web pages. Topics in this chapter:

  • What are templates; how to inherit
  • How to write URLs in Flask; url_for() helper function; relative & absolute URLs, the latter one less useful
  • How to send static files (in template format)
  • Miscellaneous: Bootstrap integration

Ch4 Web Forms

Form classes (technical)

FlaskForm defines the list of fields in each form, each represented by an object. Each field object have one or more validators attached. A validator is a function. Note the three terms here, FlaskForm, field, validator.

Form submission with GET

Bad. GET doesn’t have a body, so if submit with GET method, the data will be appended to the URL as a query string, and becomes visible in the browser’s address bar.

Therefore, in view function that deals with forms, add a POST method like that:

1
@app.route('/', methods=['GET', 'POST'])

Miscellaneous

This method returns True when form is submitted submitted using POST method, and the data accepted by all field validators; used to determine, whether the form needs to be rendered or processed.

1
2
if form.validate_on_submit():
###

The first and only required argument to url_for() is the endpoint name. By default, the endpoint of a route is the name of the view function attached to it.

1
return redirect(url_for('index'))

Ch5 Databases

Terms

column: attribute of the entity; row: actual data element that assigns values to columns.

table, record –> collection, document, from Relational to NoSQL

primary key: a special column; foreign keys: columns

Sum

  • With ORM middleman, one doesn’t have to SQL semantics
  • Apply different URLs in config could migrate from different (relational) databases
  • Databases migration:
    • Framework: Flask-Migrate, the Alembic wrapper
    • Procedures: flask db init, creates a migrations directory (optional, only on a new project); flask db migrate -m "message", automatically creates migration script, while revision manually; flask db upgrade
    • flask db downgrade and ... upgrade gives db migrations log history like git

Ch7 Large Application Structure

Add custom commands via click

1
2
3
4
@app.cli.command()
def thatWillBetheNameofCommand():
"""This will be shown in the help messages"""
pass

Blueprint detail

  • In chapter 7 about blueprint, the module where blueprint object is must import its routes’ view functions, because

    Importing these modules causes the routes and error handlers to be associated with the blueprint.

  • From Eg.7.7: the blueprint name before endpoint can be omitted, as url_for('.index'). Redirects within the same blueprint could use the shorter form, while crossing blueprints requires the fully qualified endpoint name that includes the blueprint name.

Ch8 User Authentication

Hashing functions are repeatable.

  • Q: How could the check_password_hash(hash, password) check pwd without knowing the salt of it?

WTForm: write your own validator with validate_ prefix

  • for wtforms validate_ prefix defines custom validators; while in Python standard library unittest the test_ prefix is used.
  • any function referred the database, is defined in model.py, as methods in those ORM models. They access the database using self.attribute.

Flask-Login detail

Flask-Login requires the application to designate a function to be invoked when the extension needs to load a user from the database given its identifier, registered with @login_manager.user_loader decorator.

_get_user() searches for a user ID in the user session –> invoke the function registered with the user_loader decorator, with the ID as argument

Ch14 API

The process of converting an internal representation to a transport format such as JSON is called serialization.

Todo

  • decorators in Python
    They are functions that takes a func as an arg then returns another arg

  • OOP concepts: constructor, method&attribute
    (so far I assume that) Methods are funcs, attributes are data.

  • How blocks are really defined in bootstrap/base.html

  • what <> means in Python code (<{'key1': v, 'k2': v2}>)

  • What is label in HTML
    makes the form text clickable; same style with it.

  • The remaining class variables are the attributes of the model, defined as instances of the db.Column class.

    what is instance, class variable, attribute

  • with keyword in Python

  • __name__, __file__ and other dunder variable (basedir = os.path.abspath(os.path.dirname(__file__)) )

    • __name__ has two values, "__main__" (when being executed) or the module’s name (when imported). With respect to Object, __name__ is the special attribute of a class, function, method, descriptor, or generator instance.
    • __file__, the absolute path of the module
  • functionality of the __init__.py file in a directory

  • OOP: @property decorator in a class

  • DB: users = db.relationship('User', backref='role', lazy='dynamic'). “users” is a column of the table role. What does lazy kwarg mean

  • DB: Role.query.filter_by(name='Administrator').first(), type of the return value

    1
    2
    3
    User.query.filter_by(username='galt').first()  # output: <User 'john'>
    a = User.query.filter_by(username='galt').first()
    type(a) # output: <class 'app.models.User'>

    On success, return value is the row in the table. a.id would return the id column of user galt.


  • Linux command export
  • form.hidden_tag() element for CSRF protection
  • How much freedom does ORM/ODM provide in choosing DB, only different rational databases?
    Yes.
  • {{ wtf.quick_form(form) }}, how will this template be rendered, search keyword in the book
    • {{ name }} construct references a variable, a placeholder
  • How to initialize SelectField, 7.31
  • Post.query.order_by will this query affect rows? 8.1

After Flask:

  • WTForm package validator source code, I assume it’s just RegEx

  • For example, the execution of the send_async_email() function can be sent to a Celery task queue. (p.107)

  • Decorator: How different orders affects the registered function

  • Thread: worker thread in Flask doc

  • Iterator and that:

    1
    2
    follows = [{'user': item.follower, 'timestamp': item.timestamp}
    for item in pagination.items]

Check yourself:

  • How to add a new row in a table, how to change a column of a row
  • Page 182, how the foreign key of a table is added

  • synopsis: brief summary

  • delimiter (programming)

  • miscellaneous

  • callable, page 65

  • cardinality alchemy, transparent (Ch5)

  • build a perfect replica of the virtual environment…

Appendix

Object in Python

type of methods:

  • instance method, the 1st argument of it must be self; any method taking self as the 1st arg is a instance method
  • class method, @classmethod, cls as the 1st arg. Calling: Obj().count(), where Obj is the name of a class
  • static method@staticmethod. E.g. Obj().someStaticMethod()

super() in Python2.x takes its own class as the first variable, like super(Child, self).__init__(age, height). Also the parent shall be defined as class Parent(object), having object as base class.

REST API

  • more business logic on client side
  • client could discover resources using different URL compositions
  • versioning for backward compatibility

Compare to Mage Tutorial

  1. _get
  2. plain text and HTML email
  3. from GitHub’s commit history you could view specifically what changed in every commit

Test & Caution

  1. Think of boundary values while designing programs.

    • current_user.confirmed
    • @login_required
    • self.email.lower() ensure that the string is lowercase
    • verify_password(email, password): before loading user from DB to check pwd, email must be checked first not to be ''
  2. Crucial cases where proxies provided by Flask likecurrent_app can’t fake:

    • current_app can’t fake its type as the actual object type
    • when sending Signals or passing data to a background thread

    best practice:

    1
    2
    app = current_app._get_current_object()
    my_signal.send(app)
  3.  from sqlalchemy.exc import IntegrityError
     try:
         db.session.commit()
     except IntegrityError:
         db.session.rollback()
    
  4. form.body.data = post.body; how to render page according to attributes of the user; Context processors make variables available to all templates during rendering

  5. from app.exceptions import

The power of Flask Shell

Page 214, static method add_self_follows() that manipulates existed rows

最近用上了 WSL,巨硬居然在 Win 上允许使用 Linux了
修改文件不可避免似乎就要学会 Vim 啊,后来才知道自带 nano

Motion

h, l: move left and right

j, k: move down and up

w: next beginning of word

e, ge: current, last end of word

b, B: previous beginning of word and WORD

0, ^: to the beginning of line

$: to the end of line

gg, G: beginning, end of file

nG: line n; :set nu to turn on line num

f<char>, F<char>: search forward, backward

Edit

cw: Change current word that the cursor’s at

cc: delete the whole line and enter INSERT mode

C: delete till the end of line, enter INSERT mode

r<char>: Replace cursor with <char>

R: replace successively, with each<char> typed; Esc to exit

un Undo for n times

U undo all changes in current line

Ctrl + r: redo

>>, <<: tab in NORMAL mode

:set shiftwidth?

:ce center the line

:ri, :le: to the right, left

/, ?: search next, last

n, N: next, last result

Insert

i, a: insert at and append cursor position

I, A: insert at the beginning and the end of current line

o, O: Open a new line after and before current line, and enter INSERT mode

Copy, Paste, and Cut

yy: Yank(copy) whole line

yw, ynw: copy one word, n words

y^, y0: copy till the beginning of line, current cursor not included

y$: copy till the end, char where the cursor’s at included

yG, y1G: copy till end, beginning of file

p: (lowercase) paste on next line

P: (uppercase) paste last line

dd: cut

ddp: swap this and next line

Delete

x: Delete char under cursor

X: delete char before cursor

dd: delete the entire line

dw: delete word after cursor; w + dw

D: delete till the end of line

d^: delete till the beginning

d1G, dG: delete till the beginning and end of file

Repeat

.: repeat last command (under NORMAL mode)

N<command>: e.g. 2dd, 10x

dnw: delete a word n times

Exit

:q: quit

:wq, :x: save and exit

:wq!: force to save and quit

:w, :saveas

Shift + zz: under NORMAL mode, save and exit

终于在极客时间上剁手了
这篇是耗子叔的那几篇入门指导的浓缩

[TOC]

入门篇

零基础启蒙

两份入门教程(Python & JS)

都是从零开始

Python 与 JavaScript 入门语言

Python 书籍

JavaScript 在线教程

操作系统入门 Linux

W3CSchool Linux 教程

(Microsoft) Visual Studio Code

中文手册,不一定非要。吸引我:在终端工具内打印 Debug 信息

Web 编程入门

前端基础

  • MDN CSS 文档 与 HTML 文档,参考而不是记忆
  • JS DOM 与动态网页 W3Schools 的 JavaScript HTML DOM 教程
  • 要点:
    • HTML 基本语法
    • CSS 如何选中 HTML 元素,应用一些基本样式
    • 用 Firefox + Firebug 或 Chrome 查看炫酷网页结构

后端(PHP)

实践项目

极简 Blog 系统,或是 BBS 系统,支持如下功能:

  • 用户登录和注册,无密码找回
  • 用户发帖,仅支持纯文本
  • 评论,纯文本

从前端到后端,从 HTML/CSS/JS 到 Python,再到数据库

注意的技术点:

  • 用户登录密码不保存为明文
  • 用户登录后,可对自己帖子 “重新编辑”、”删除“,但无权修改其它用户
  • 数据库设计。三张表:用户表,文章表,评论表,他们之间的关联

正式入门

编程技能

The Key to Accelerating Your Coding Skills,文章

  • 编程技巧:Code Complete
  • 编程语言:学习 Java
  • 操作系统:鸟哥的 Linux 私房菜
  • 网络协议:系统了解 HTTP 协议,MDN HTTP 文档,关键点:
    • HTTP 头、HTTP 请求方法、HTTP 返回码
    • Cookie,缓存,会话,连接管理
  • 数据库设计:慕课网在线课程;推荐学习 MySQL
  • 前端:jQuery,Bootstrap;Ajax 请求后端 API 接口方式;JS Promise 模式,阮一峰教程
  • 字符编码

编程工具

  • IDE:Eclipse,Intellij IDEA,VS Code
  • 版本管理工具:Git 使用资料
  • 调试前端:用 Chrome 调试,资料
  • 数据库设计工具:MySQL WorkBench,资料

实践项目

投票系统

业务需求:技术需求:

入门篇小结

  • 1 - 2 年时间
  • 不用精通,能独立做出实践项目即是真正入门(耗子叔对入门的定义)
  • 年薪 20万

修养篇

程序员修养

Quora 帖子

附录:编程规范

专业基础篇

编程语言

  • C 坑
  • C ++
  • Java
    • C –> C ++ –> Java
  • Go

理论学科

”计算机学科最精华的知识,人类智慧的精华“

数据结构与算法

  • 三本书推荐,先后顺序
  • LeetCode 使用
  • “如果想要有科班生理论基础”:
    • 数据结构与算法分析
  • 小结

系统知识

Wireshark 数据包分析实战

系统知识小程序

实践项目

  • 实现一个 telnet 版本的聊天服务器
    • telnet ip:port的方式连接服务器
    • 新连接需要用户名和密码登录,无则注册
    • 然后可以选择一个聊天室加入聊天
    • 管理员有权创建删除聊天室,普通人员只有 加入、退出、查询、聊天室
    • 聊天室人数限制;每个人发出来的其他人都能看到
  • 简单的 HTTP 服务器
    • 解释浏览器传来的 HTTP 协议,只处理 URL path
    • 然后列出所代理的目录
    • 浏览器上可以浏览目录里的文件,和下级目录
    • 点击文件,则文件传给浏览器(浏览器可自动显示图片、PDF、等)
    • 点击子目录,则进入子目录,并列出文件
  • 生产者 / 消费者消息队列服务

小结

  • 还有热情与成就感:恭喜,超过了绝大多数人;50 万
  • 术业有专攻,建议的方向

软件设计篇

软件设计

高手成长篇

系统底层知识

0%