[后端-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
[后端-Flask总结]-flask学习总结的更多相关文章
- 【Flask】 python学习第一章 - 6.0 WTF表单 数据库 蓝图
WTF表单 wtf.py pip install flask-wtf # 安装 from flask_wtf import FlaskForm from wtform import StringF ...
- flask 基础语法学习
回顾 #6行flask from flask import Flask app = Flask(__name__) @app.route("/") def index(): ret ...
- Flask框架的学习与实战(一):开发环境搭建
Flask是一个使用 Python 编写的轻量级 Web 应用框架.其 WSGI 工具箱采用 Werkzeug ,模板引擎则使用 Jinja2.很多功能的实现都参考了django框架.由于项目需要,在 ...
- 【Flask】 python学习第一章 - 2.0 视图方式和返回值
路由参数与请求方式制定 ALT+回车 pycharm 快速导包 demo3 指定访问地址 与请求方式 # 给路由传入参数 使用尖括号 ,视图函数需要接收参数 @app.route(&q ...
- flask部署深度学习模型
flask部署深度学习模型 作为著名Python web框架之一的Flask,具有简单轻量.灵活.扩展丰富且上手难度低的特点,因此成为了机器学习和深度学习模型上线跑定时任务,提供API的首选框架. 众 ...
- Flask SSTI | Python3 学习记录
Flask SSTI | Python3 引言 昨天原本是打算继续python的每日一练的,这次按日程一样是要练习用一个web框架写一个留言板的,于是打算用flask搞一下,但是正打算写的时候,突然想 ...
- 【Flask】Flask学习笔记(一) 应用基本结构
初始化 使用前必须创建一个应用实例 from flask import Flask app = Flask(__name__) 路由和视图函数 请求流程 客户端(web浏览器)--> web服 ...
- flask框架的学习
---恢复内容开始--- 第一个flask程序讲解:1. 第一次创建项目的时候,要添加flask的虚拟环境.添加虚拟环境的时候,一定要选择到python这个执行文件.比如你的flask的虚拟环境的目录 ...
- Flask 的系统学习
详细看地址: http://www.cnblogs.com/wupeiqi/articles/7552008.html 一. 说明 Flask是一个基于Python开发并且依赖jinja2模板和Wer ...
- Flask框架的学习与实战(二):实战小项目
昨天写了一篇flask开发环境搭建,今天继续,进行一个实战小项目-blog系统. blog系统很简单,只有一个页面,然而麻雀虽小五脏俱全.这里目的不是为了做项目而做项目,这篇文章本意是通过这次练习传达 ...
随机推荐
- 神奇的DEBUG:因为异常导致MongoDB容器无法启动
越来越多的项目使用docker进行环境搭建,统一了开发和运行环境,好处颇多.但同时也引入了许多复杂性,比如一些容器服务突然无法启动,那么debug起来就比物理机安装的服务麻烦一些. 这段时间Mac P ...
- shape {select ...} append ({select ...} RELATE ID TO PARAMETER 0,ID TO PARAMETER 1)
1.问题描述 最近在写vb.net的时候,碰到了一个有点棘手的问题.就是在vb里面去解决一对多的关系. 对应关系如下,一个合同会对应多个开票. 最简单暴力的方法就是循环查询了,但是这样子肯定不行的.如 ...
- 后端流传输excel文件到前端
场景 公司有个需求,请求接口返回一个对应的excel数据 方法 1.可以使用后端生成excel后,返回一个下载地址 2.可以把数据吐给前端,前端使用对应的插件转换成excel数据 3.使用流式传输 优 ...
- react 高效高质量搭建后台系统 系列 —— antd和样式
其他章节请看: react 高效高质量搭建后台系统 系列 antd 后续要做登录模块(主页),不仅要解决请求数据的问题,还需要完成 antd 配置以及样式的准备. antd 多种主题风格 详情请看 这 ...
- 如何在Github上创建一个新仓库
Hi,欢迎大家在有空的时候做客[江涛学编程],这里是2023年的第6篇原创文章,新年新气象,在这里我祝读者朋友们都好好的, 老规矩,拍拍手,上菜. 今天没有啥东西要跟家人们分享,就两个字,看图!!! ...
- 从Babel开始认识AST抽象语法树
前言 AST抽象语法树想必大家都有听过这个概念,但是不是只停留在听过这个层面呢.其实它对于编程来讲是一个非常重要的概念,当然也包括前端,在很多地方都能看见AST抽象语法树的影子,其中不乏有vue.re ...
- WPF-3D图形
WPF-3D图形 WPF的3D功能可以在不编写任何c#代码的情况下进行绘制,只需要使用xaml即可完成3D图形的渲染.本文主要讲述了WPF-3D中的关键概念, 以及常用到的命中测试.2d控件如何在3D ...
- 字节输出流OutputStream类-字节输出流写入数据到文件
字节输出流OutputStream类 java.io.OutputStream抽象类是表示字节输出流的所有类的超类,将指定的字节信息写出到目的地.它定义了字节输出流的基本共性功能方法.public v ...
- Entry键值对对象-Map集合遍历键值对方式
Entry键值对对象 我们已经知道,Map中存放的是两种对象,一种称为key(键),一种称为value(值),它们在在[Map中是-对应关系,这一对对象又称做Map 中的一个 Entry(项).Ent ...
- DNA
思路一: 这题需要桶+哈希(简化版像A 1 B 2 ......) 具体: 先把数据输入 再枚举可能的右端点,再由右端点得到左端点(l和r相差k) 在 l到r 区间内将这一段区间哈希成一个4进制数 ...