[后端-Flask总结]-flask学习总结

1.flask开发基础与入门:
1.1web开发基础
1.1.1 前端框架:
bootstrap, j-query, angular, react
1.2 flask 路由
from flask import Flask
# 从flask引入request实例
from flask import request, url_for

app = Flask(__name__)


@app.route('/')
def hello_world():
return 'Hello World!'

# 换请求方式
@app.route('/user', methods=['POST'])
def hello_user():
return 'Hello User!'

# 传递参数
@app.route('/user/<id>')
def hello_id(id):
return 'Hello id:{}'.format(id)

@app.route('/query_user')
def query_id():
id = request.args.get('id')
# 访问:http://127.0.0.1:5000/query_user?id=12345
return 'query_user id:{}'.format(id)

# 方向路由:通过视图函数,反找出url地址
@app.route('/query_url')
def query_url():
# 访问:http://127.0.0.1:5000/query_url
return 'query_url:{}'.format(url_for('query_id'))

if __name__ == '__main__':
app.run()

1.3 flask 模版
1.3.1 html中条件语句
{% if user %}
user_name: {{ user.user_name }}
{% else %}
no this user
{% endif %}

1.3.2 html循环语句
{% for user in user_li %}
{{ user.user_id }}--{{ user.user_name }}<br>
{% endfor %}

1.3.3 html 继承
> 父类
<div>
<h1>header</h1>
</div>
{% block content %}
{% endblock %}
<div>
<h1>footer</h1>
</div>
> 子类
{% extends "base.html" %}
{% block content %}
<h2>this is page one</h2>
{% endblock %}
> 调用
@app.route('/base_two')
def base_two():
return render_template('base_two.html')

@app.route('/base_one')
def base_one():
return render_template('base_one.html')

1.4 flask 消息提示与异常处理-flash
> from flask import flash, render_template, request, abort
# 使用flash时,需要使用app.secret_key='123'加密
app.secret_key = "123"
@app.errorhandler(404)
def not_found(e):
return render_template('404.html')

<h2>{{ get_flashed_messages()[0] }}</h2>
1.5 python web 开发
1.5.1 get和post方法:
>get 请求可被浏览器缓存
>get 请求会保存在历史记录中
>get 请求有长度限制
>get 请求不应用与敏感场合
>post 请求不会显示在URL中,包含在http请求头中,使用ssh加密
1.5.2 python中的web服务器
>python自带包创建服务器:
> BaseHTTPServer->提供基本的web服务和处理类
> SimpleHTTPServer -> 包含执行get请求SimpleHTTPRequestHandler
> CGIHTTPServer->包含处理post请求和执行CGIHTTPRequestHandler
>
>在根目录下执行:
>在python2.6里启动CGI服务命令是:
python -m CGIHTTPServer 8080
>在python3.4里则是:
python -m http.server --cgi 8083
[[在Python2.6版本里,/usr/bin/lib/python2.6/ 目录下会有 BaseHTTPServer.py, SimpleHTTPServer.py, CGIHTTPServer.py,但是在Python3.4里,就没有上面的3个文件,而是合闭到了 /usr/bin/python3.4/http/server.py文件里了。]]
> 创建文件夹cgi-bin, views
> 在cgi-bin 中创建main.js
> #!/usr/bin/python //必须加这一行才能在命令行中执行脚本
print("Content-type:text/html \n\n")
print("hello web development")
> 访问: http://localhost:8083/cgi-bin/main.py
> get请求
> #!/usr/bin/python
#coding:utf-8
import cgi, cgitb

form1 = cgi.FieldStorage() #创建一个实例
name = form1.getvalue("name")

print("Content-type:text/html \n\n")
print("hello {}".format(name))

> 访问: http://localhost:8083/cgi-bin/main.py?name=hahaha
1.5.3 表单
1.5.3.1 表单种类
<form name="form1">
//文本框<input type="text" placeholder="text" name="text1" />
//密码框<input type="password" placeholder="password"/>
//文本输入框<textarea style="resize: none" placeholder="textarea"></textarea>
//文件上传<input type="file"/>
//单选框<input type="radio" name="Option" value="Option1"/>Option 1
<input type="radio" name="Option" value="Option2"/>Option 2
//复选框<input type="checkbox" name="Option" value="Option1"/>Option 3
<input type="checkbox" name="Option" value="Option2"/>Option 4
<input type="submit">
<input type="reset">
<input type="button" value="button">
</form>
1.5.3.2 表单提交方式
>get:
>请求可以被缓存
>请求有长度限制
>请求数据暴露在url中 ,存在安全问题
>适用场合:
>单纯请求数据,如:查询数据,不用插入数据库时
>表单数据较短,不超过1024个字符
>post:
>url可以被缓存,但数据不会被缓存
>请求不便于分享
>没有长度限制
>适用场合:
>不仅请求数据,如:需将数据插入数据库中
>表单数据过长,超过1024个字符
>要传送的数据不是ascii编码
1.5.3.3 表单扩展Flask-wtf:
> 安装:
> 使用:
from wtforms import Form, TextField, PasswordField, validators

1.5.4 数据库-python连接数据库mysql
1.5.4.1 python 操作mysql
1.5.4.1.1连接数据库
import pymysql

#连接数据库
# db = pymysql.connect(host,port,user,passwd,db)

db = pymysql.connect("localhost","root","666666","test")

#使用cursor()方法创建一个游标对象
cursor = db.cursor()

#使用execute()方法执行SQL语句
cursor.execute("SELECT * FROM userinfo")

#使用fetall()获取全部数据
data = cursor.fetchall()

#打印获取到的数据
print(data)

#关闭游标和数据库的连接
cursor.close()
db.close()
1.5.4.1.2 数据库增删改操作 // commit()方法:在数据库里增、删、改的时候,必须要进行提交,否则插入的数据不生效。
1.5.4.1.2.1 增
import pymysql
config={
"host":"127.0.0.1",
"user":"root",
"password":"LBLB1212@@",
"database":"dbforpymysql"
}
db = pymysql.connect(**config)
cursor = db.cursor()
sql = "INSERT INTO userinfo (username,passwd) VALUES('jack','123')"
cursor.execute(sql)
db.commit() #提交数据
cursor.close()
db.close()
1.5.4.1.2.2 增
import pymysql
config={
"host":"127.0.0.1",
"user":"root",
"password":"LBLB1212@@",
"database":"dbforpymysql"
}
db = pymysql.connect(**config)
cursor = db.cursor()
sql = "INSERT INTO userinfo(username,passwd) VALUES(%s,%s)"
cursor.execute(sql,("bob","123"))
db.commit() #提交数据
cursor.close()
db.close()
1.5.4.1.2.3 增加多条
import pymysql
config={
"host":"127.0.0.1",
"user":"root",
"password":"LBLB1212@@",
"database":"dbforpymysql"
}
db = pymysql.connect(**config)
cursor = db.cursor()
sql = "INSERT INTO userinfo(username,passwd) VALUES(%s,%s)"
cursor.executemany(sql,[("tom","123"),("alex",'321')])
db.commit() #提交数据
cursor.close()
db.close()
1.5.4.1.2.4 查 fetchone():获取下一行数据,第一次为首行;
import pymysql
config={
"host":"127.0.0.1",
"user":"root",
"password":"LBLB1212@@",
"database":"dbforpymysql"
}
db = pymysql.connect(**config)
cursor = db.cursor()
sql = "SELECT * FROM userinfo"
cursor.execute(sql)
res = cursor.fetchone() #第一次执行
print(res)
res = cursor.fetchone() #第二次执行
print(res)
cursor.close()
db.close()
1.5.4.1.2.6 查 fetchall() 获取所有行数据源
import pymysql
config={
"host":"127.0.0.1",
"user":"root",
"password":"LBLB1212@@",
"database":"dbforpymysql"
}
db = pymysql.connect(**config)
cursor = db.cursor()
sql = "SELECT * FROM userinfo"
cursor.execute(sql)
res = cursor.fetchall() #第一次执行
print(res)
res = cursor.fetchall() #第二次执行
print(res)
cursor.close()
db.close()
#运行结果
((1, 'frank', '123'), (2, 'rose', '321'), (3, 'jeff', '666'), (5, 'bob', '123'), (8, 'jack', '123'), (10, 'zed', '123'))
()
1.5.4.1.2.7 查 fetchmany(4):获取下4行数据
> cursor = db.cursor(cursor=pymysql.cursors.DictCursor) #在实例化的时候,将属性cursor设置为pymysql.cursors.DictCursor
> cursor.scroll(1,mode='relative') # 相对当前位置移动,正数为光标向后移动,负数为光标向前移动;1,当前光标向后移动1个位置
cursor.scroll(-1, mode='relative') #表示当前光标向前移动一个位置

cursor.scroll(2,mode='absolute') # 相对绝对位置移动,表示光标移到第二位
第一个值为移动的行数,整数为向下移动,负数为向上移动,mode指定了是相对当前位置移动,还是相对于首行移动
1.5.4.1.2.8 改
1.5.4.1.2.9 删

1.5.4.1.3 上下文协议:
import pymysql
config={
"host":"127.0.0.1",
"user":"root",
"password":"LBLB1212@@",
"database":"dbforpymysql"
}
db = pymysql.connect(**config)
with db.cursor(cursor=pymysql.cursors.DictCursor) as cursor: #获取数据库连接的对象
sql = "SELECT * FROM userinfo"
cursor.execute(sql)
res = cursor.fetchone()
print(res)
cursor.scroll(2,mode='relative')
res = cursor.fetchone()
print(res)
cursor.close()
db.close()
1.5.5 数据库-orm:
1.5.1 flask扩展- Flask-SQLALchemy
1.5.2
1.5.3
1.5.4
1.5.5
1.5.6
1.5.7
1.6 数据库使用介绍
-1.6.1 flask 外部脚本
-1.6.1.1 Flask-Script安装与使用
> pip install flask-script
-1.6.1.2 Flask使用sqlite

1.6.2 flask 使用mysql

1.6.3 flask 使用mongodb
1.6.3.1 MongoDB 驱动:
1.6.3.1.1 Pymongo
>manage.py
from flask_script import Manager
from app import app
from modules import User
manager = Manager(app)

@manager.command
def save():
user = User('jike', 'jike@jikexueyuan.com')
user.save()

@manager.command
def query_users():
users = User.query_users()
for user in users:
print(user)

if __name__ == "__main__":
manager.run()

>modules.py
import pymongo

MONGO_URL = '127.0.0.1'
MONGO_DB = "jikexueyuan" #数据库名称
MONGO_TABLE = "user_collection" #表单名称

def get_collection():
client = pymongo.MongoClient(MONGO_URL)
db = client[MONGO_DB]
user_collection = db[MONGO_TABLE]
return user_collection

class User():
def __init__(self, name, email):
self.name = name
self.email = email

def save(self):
user_info = {
"name": self.name,
"email": self.email
}

collection = get_collection()
id = collection.insert(user_info)
print(id)

@staticmethod
def query_users():
users = get_collection().find()
return user

>app.py
from flask import Flask

app = Flask(__name__)

@app.route('/')
def hello_world():
return 'Hello World'

if __name__ == "__main__":
app.run()

>运行:
->python manage.py save
->python manage.py query_users

1.6.3.1 MongoDB中的orm:
1.6.3.1.1 MongoEngine:
>安装: pip install flask-mongoengine

posted @ 2019-08-12 12:18  mezc  阅读(461)  评论(0编辑  收藏  举报