赞
踩
data 数据
date 时间
form 表格
from 来自
Flask轻量级框架
Tornado 高并发处理框架
Django 企业级重量框架
https://www.cnblogs.com/yeminglong/p/5995421.html
写代码,按Tab | 生成代码 |
---|---|
Ctrl+/ 或 Ctrl+Shift+/ | 注释(// 或者/…/ ) |
Ctrl+Alt+L | 格式化代码 |
Ctrl+? | 生成注释 |
Alt加单击 | 多选共同编辑 |
1.自动生成虚拟环境(虚拟环境自动放到文件目录里)
2.使用提前生成的virtualenv,需要提前进到对应目录(推荐)
Windows terminal使用cmd不是powershell
https://blog.csdn.net/sinat_42194124/article/details/82819993
win安装虚拟环境
pip3 install virtualenvwrapper-win
pip3 list检查是否安装成功
切换到对应目录,mkvirtualenv创建虚拟环境
mkvirtualenv -p C:\Users\q2723\AppData\Local\Programs\Python\Python37-32\python3.exe flask
workon
使用mkvirtualenv命令来创建虚拟环境,环境目录路径为系统默认路径,C:\Users\q2723\Envs
workon name 进入虚拟环境
deactivate 退出虚拟环境
删除虚拟环境
rmvirtualenv
pycharm使用已创建虚拟环境
有这些的原因:当初创建项目的时候已经指定了flask,所以pycharm在创建项目的时候自动执行了pip install flask
项目名:
static 静态 js、css
templates 模板
app.py 运行|启动
MVC:
model
view
controler
MTV:
model 与数据库交互
template 显示页面
view 起控制作用
B/S
browser/sever
C/S
client/sever
win:
装完virtualenvwrapper可以直接使用,默认位置是c://user/q2723/Envs/
linux:
装完需要配置/.bashrc和/.bash_profile文件
mkvirtualenv 虚拟环境名称
创建
cdvirtualenv
切换到当前虚拟环境目录下
lsvirtualenv
显示所有虚拟环境==workon
rmvirtualenv 虚拟环境名称
删除虚拟环境
__name__
表示当前文件名称
__init__
创建对象时默认调用部分
WSGI
web服务器网管接口(python web sever gateway interface)
为python语言定义的web服务器和web应用程序或框架之间的一种简单通用的接口
from flask import Flask
app = Flask(__name__)
@app.route('/') #路由,必须以 / 开始否则报错
def hello_world(): #视图函数
return 'Hello World!'
if __name__ == '__main__':
app.run(host='0.0.0.0', port=8080, debug=True)
Flask 默认拥有内置服务器
看 python 源码,ctrl 加单击
host 默认127.0.0.1只能本机访问,允许外网访问则需改成0.0.0.0
Debug 模式:开启后更改源码实时更新,适用于开发环境
app.config
<Config {'ENV': 'production', 'DEBUG': False, 'TESTING': False, 'PROPAGATE_EXCEPTIONS': None, 'PRESERVE_CONTEXT_ON_EXCEPTION': None, 'SECRET_KEY': None, 'PERMANENT_S
ESSION_LIFETIME': datetime.timedelta(days=31), 'USE_X_SENDFILE': False, 'SERVER_NAME': None, 'APPLICATION_ROOT': '/', 'SESSION_COOKIE_NAME': 'session', 'SESSION_COOK
IE_DOMAIN': None, 'SESSION_COOKIE_PATH': None, 'SESSION_COOKIE_HTTPONLY': True, 'SESSION_COOKIE_SECURE': False, 'SESSION_COOKIE_SAMESITE': None, 'SESSION_REFRESH_EAC
H_REQUEST': True, 'MAX_CONTENT_LENGTH': None, 'SEND_FILE_MAX_AGE_DEFAULT': datetime.timedelta(seconds=43200), 'TRAP_BAD_REQUEST_ERRORS': None, 'TRAP_HTTP_EXCEPTIONS'
: False, 'EXPLAIN_TEMPLATE_LOADING': False, 'PREFERRED_URL_SCHEME': 'http', 'JSON_AS_ASCII': True, 'JSON_SORT_KEYS': True, 'JSONIFY_PRETTYPRINT_REGULAR': False, 'JSO
NIFY_MIMETYPE': 'application/json', 'TEMPLATES_AUTO_RELOAD': None, 'MAX_COOKIE_SIZE': 4093}>
修改环境
app.py
app.config['ENV']='development'
app.config['DEBUG']=True
或将配置文件独立为
settings.py
ENC = 'development'
DEBUG = True
在此文件中port端口设置无效
在app.py导入settings
from flask import Flask
app = Flask(__name__)
import settings
app.config.from_object(settings)
或者app.config.from_pyfile('settings.py')
@app.route('/') #路由
def hello_world(): #视图函数
return 'Hello World!'
if __name__ == '__main__':
app.run(port=8080)
#端口在这改有效
@app.route()
源码: def route(self, rule, **options): def decorator(f): endpoint = options.pop("endpoint", None) self.add_url_rule(rule, endpoint, f, **options) return f return decorator @app.route('/') def index(): return 'Index page' 就等效于 def index(): return 'hello' app.add_url_rule('/index',view_func=index)
from flask import Flask app = Flask(__name__) data = {'a': 'beijing', 'b': 'shanghai'} @app.route('/') def hello_world(): return 'Hello World!' @app.route('/getcity/<key>') #key是一个变量名,默认是字符串类型数据 def get_city(key): print(type(key)) return data.get(key) @app.route(/getnum/<int:num>) def calc(num) #num和上行num保持一致 result = num + 10 return str(result) #注意:上一行 return 返回值不能是 int 型,必须是 srting,dict,tuple,response instance,wsgi callable if __name__ == '__main__': app.run(host='0.0.0.0', port=8080, debug=True)
app.route(’*’)
允许转换器的类型:
string | (默认)接受任何不包含斜杠的文本 |
---|---|
int | 接受正整数 |
float | 接受正浮点数 |
path | 类似于string,但是可以包含斜杠 |
uuid | (通用唯一识别码),接受uuid字符串 |
python用于uuid的库
uuid有固定格式
特殊:
@app.route('/about') #没有斜杠,行为表现类似于一个文件,访问加斜杠就会出现404错误,这样可以保证url唯一,避免重复索引同一界面
def hello_world():
return 'Hello World!'
@app.route('/about/') #尾部有/,行为表现类似于一个文件夹,访问没有斜杠结尾的url也能成功flask会自动重定向,帮你在结尾加上一个斜杠
def hello_world():
return 'Hello World!'
路由自上而下加载
返回值不能是int型,必须是srting,dict,tuple,response instance,wsgi callable
data = {'a': 'beijing', 'b': 'shanghai'} @app.route('/string') def string(): return '<h1>beijing</h1>' #content-Type:text/html;charset=utf-8 #return后面返回的字符串其实也是做了一个response对象的数据,最终返回结果还是response对象,会被当作HTML解析 @app.route('/dict') def dict(): return {'a': 'beijing', 'b': 'shanghai'} #content-Type:application/json;charset=utf-8 def tup(): return 'aaa',200 a=tup() print(a) #输出信息为元组('aaa', 200) @app.route('/tuple') def tuple(): return 'hello world',200 @app.route('/response instance') def response instance(): return Response('<h1>beijing</h1>') #content-Type:text/html;charset=utf-8 response对象
导入make_response
from flask import Flask,make_response app = Flask(__name__) @app.route('/index') def index(): content=''' <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>首页</title> </head> <body> <div> <h1>wolcome</h1> <ul> <li> hello </li> </ul> </div> </body> </html> ''' response = make_response(content) #返回值就是一个response对象 response.headers['myheaders'] = '123abc' #定制响应头 print(response.content_type) print(response.status) print(response.status_code) return response if __name__ == '__main__': app.run(port='8080',debug=True)
导入request
from flask import Flask, request
import settings
app = Flask(__name__)
app.config.from_object(settings)
@app.route('/index')
def index():
print(request.headers)
print(request.path)
return 'ok'
if __name__ == '__main__':
app.run()
request对象,对象访问属性,也可以调用方法
if __name__ == '__main__':
print(app.url_map)
app.run()
Map([<Rule '/index' (HEAD, OPTIONS, GET) -> index>,
<Rule '/static/<filename>' (HEAD, OPTIONS, GET) -> static>])
#以列表形式返回
from flask import Flask, request, render_template
import settings
app = Flask(__name__)
app.config.from_pyfile('settings.py')
@app.route('/register')
def register():
r = render_template('register.html')
#默认去模板文件夹中找文件,通过jinja引擎转化为字符串即response对象
return r
if __name__ == '__main__':
print(app.url_map)
app.run()
register.html要放在templates目录下
为啥会默认在templates下
因为创建app时默认的
app=Flask(__name__)
def __init__(
self,
import_name,
static_url_path=None,
static_folder="static",
static_host=None,
host_matching=False,
subdomain_matching=False,
template_folder="templates",
instance_path=None,
instance_relative_config=False,
root_path=None,
):
f12加右击刷新
或:ctrl+shift+del
ctrl+?添加注释
register.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>注册</title> <style> div{ height: 200px; width: 100%; border: 2px solid blue; } </style> </head> <body> <div> <form action="register1" method="get"> <p> <input type="text" name="username" placeholder="username"> </p> <p> <input type="text" name="address" placeholder="address"> </p> <p> <input type="submit" value="提交"> </p> </form> </div> </body> </html>
app.py
from flask import Flask, request, render_template import settings app = Flask(__name__) app.config.from_pyfile('settings.py') @app.route('/register') def register(): r = render_template('register.html') return r @app.route('/register1') def register1(): print(request.full_path) #/register1?username=2019101763&address=aaa print(request.path) #/register1 print(request.args) #ImmutableMultiDict([('username', '2019101763'), ('address', 'aaa')]) 封装字典类型 print(request.args.get('username')) #2019101763 return 'ok' if __name__ == '__main__': print(app.url_map) app.run() 输出 /register1?username=2019101763&address=aaa /register1 ImmutableMultiDict([('username', '2019101763'), ('address', 'aaa')]) 2019101763
get是在url中传参
register.html
<form action="register1" method="post">
app.py
@app.route('/register1',methods=['GET','POST']) #post接收参数一定要添加methods def register1(): print(request.full_path) #/register1? print(request.path) #/register1 print(request.args) #ImmutableMultiDict([]) print(request.args.get('username')) #None print(request.form) #ImmutableMultiDict([('username', '2019101763'), ('address', 'aaa')]) print(request.form.get('username')) #2019101763 return 'ok'
此时request.args.get就取不到参数了
因为url中没有内容,信息在请求主体内
路由规则表也会更新
Map([<Rule '/register1' (POST, HEAD, GET, OPTIONS) -> register1>,
<Rule '/register' (HEAD, GET, OPTIONS) -> register>,
<Rule '/static/<filename>' (HEAD, GET, OPTIONS) -> static>])
错误写法
@app.route('/add/<int:a>/<int:b>')
def add(a,b):
if a>0 and b>0:
r=a+b
return str(r)
视图函数必须有返回值,否则报错
正确
@app.route('/add/<int:a>/<int:b>')
def add(a,b):
if a>0 and b>0:
r=a+b
return str(r)
return 'number wrong'
request.method
redirect
源码就是在响应头里添加location头
response.headers[‘Location’]=location addres
url=url_for(‘name’) 路径反向解析
根据名找路径
路由加endpoint app.route(’/’,endpoint=‘index’) 指定名字
from flask import Flask, url_for, redirect import settings app = Flask(__name__) app.config.from_object('settings') @app.route('/show', endpoint='index') #相当于给路由 /show ,起了一个别名叫 index def show(): name = 'ocean' gender = 'male' return name @app.route('/redir') def redir(): return redirect(url_for('index')) #使用 url_for 去反向解析别名 index #要注意的是 函数名 和redirect() 不能重名 #错误示范 #@app.route("/redirect") #def redirect(): # return redirect("https://www.baidu.com") if __name__ == '__main__': app.run()
response响应:
Jinja2 作为flask的默认模板引擎
在 HTML 中动态创建
在flask中,jinja2默认配置如下:
简单使用{{}}
show.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>show</title>
</head>
<body>
<p>
姓名:{{ name }}
</hr>
性别:{{ gender }}
</p>
</body>
</html>
app.py
from flask import Flask, request, render_template, url_for, redirect
import settings
app = Flask(__name__)
app.config.from_object('settings')
@app.route('/show', endpoint='index')
def show():
name = 'ocean'
gender = 'male'
return render_template('show.html', name=name, gender='ooooo')
#前边的name是变量名,后边name是变量值,只是在上方提前赋值而已
if __name__ == '__main__':
app.run()
模板的语法:
在模板中获取 view 中的传递的变量值:{{ 变量名key }}
render_template( ’ 模板文件名字 ’ , key = value , key = value )
在模板文件中:
{{ list.0 }} 同 {{ list[0] }}
{{ dict.key }} = {{ dict.get(key) }}
{{ class.name }} = {{ 对象.属性 }}
字符串,列表,元组,字典,对象等都可
注释块
{# #} 服务器可识别,浏览器不可识别
控制块
{% if(python语句) %}
{% for girl in girls %}
{% endfor %}
#成对出现,搭配使用
例:show.html
<!DOCTYPE html> <head> <meta charset="UTF-8"> <title>show</title> <style> .a{ font-weight: bolder; color: red; } </style> <!--类选择器--> </head> <p> {% for friend in friends %} {% if friend | length>6 %} <!--使用管道符而不是点--> <li class="a"> {{ friend }} </li> {% else %} <li> {{ friend }} </li> {% endif %} {% endfor %} <!--成对出现,搭配使用--> </p> </body> </html>
app.py
from flask import Flask, request, render_template, url_for, redirect
import settings
app = Flask(__name__)
app.config.from_object('settings')
@app.route('/show', endpoint='index')
def show():
friends = ['xioaming', 'xiaohua', 'xiaoli']
return render_template('show.html', friends=friends)
if __name__ == '__main__':
app.run()
例:如果是第一行就添加样式,否则没有样式
<!DOCTYPE html> <head> <meta charset="UTF-8"> <title>show</title> <style> .a{ font-weight: bolder; color: blue; } </style> </head> <p> {% for friend in friends %} {% if friend|length>6 %} <li {% if loop.first %} class="a" {% endif %} > #可以将jinja语句与html混编 {{ friend }} {{ loop.index }} {{ loop.first }} </li> {% else %} <li> {{ friend }} {{ loop.index }} {{ loop.last }} </li> {% endif %} {% endfor %} </p> </body> </html>
Filters 过滤器的本质就是函数
语法: {{ 变量名 | 过滤器 (*args) }}
常见过滤器:
字符串过滤器
safe :
如果渲染文本只有html标签jinja会自动进行实体转译,就自动防xss
@app.route('/show', endpoint='index')
def show():
friends = ['xioaming', 'xiaohua', 'xiaoli']
msg = '<h1>badapple</h1>'
return render_template('show.html', friends=friends,msg=msg)
<p>
当前共有{{ friends|length }}人
<br>
{{ msg }}
</p>
加了safe就不会被转译,出现对应效果
capitalize
单词首字母大写
lower ,upper
转换大小写
title
一句话中每个单词首字符大写
reverse
反转
format
{{'my name is %s ,i am %d years old '| format(friends.0 |title,17)}}
my name is Xioaming ,i am 17 years old
truncate()
字符串按长度截断
列表过滤器
字典
通过 flask 模块中的 app.add_template_filter 方法
定义函数,带有参数和返回值
添加过滤器 app.add_template_filter(function,name=’ ')
在模板中使用 {{ 变量 | 自定义过滤器 }}
使用装饰器完成
定义函数,带有参数和返回值
通过装饰器完成,@app.template_filter(’ 过滤器名字 ') 装饰步骤1的函数
在模板中使用 {{ 变量 | 自定义过滤器 }}
就像 app.route() 一样有两种方法
需要模板继承的情况
{% block name %}
{% endblock %}
有变化的地方挖坑
子模版继承父模板
类继承
class Person:
def run(self):
print('run...')
class Student(Person):
pass
s=Student()
s.run()
模板继承与类继承略有不同
父模板最好预留css样式,js脚本的位置
例:index.html是子模版,base.html是父模板
<!--子模版index.html--> {% extends 'base.html' %} <!--继承父模板base--> {% block title %} 首页 {% endblock %} <!--对应父模板里的坑--> {% block css %} <style> #head{ background-color: cadetblue; } </style> {% endblock %} <!--css--> {% block main %} <div> <button id="btn">main-part</button> <!--在子里面填写会替换父里边--> </div> {% endblock %} <!--页面替换内容部分--> {% block js %} <script> btn=document.getElementById('btn') btn.onclick=function (){ alert('dont touch me!') } </script> <!--js脚本部分--> {% endblock %}
<!--父模板base.html--> <!DOCTYPE html> <head> <meta charset="UTF-8"> <title> {% block title %} title {% endblock %} </title> <style> #head{ width: 100%; height: 50px; background-color: royalblue; } #head ul{ list-style: none; height: 50px; } #head ul li{ width: 25%; float: left; text-align: center; font-size: medium; line-height: 50px; } #foot{ width:100%; height: 50px; background-color: aquamarine; } #main{ width:100%; height: 500px; background-color: cadetblue; } </style> {% block css %} {% endblock %} </head> <body> <div id="head"> <ul> <li>index</li> <li>first</li> <li>third</li> <li>second</li> </ul> </div> <div id="main"> {% block main %} {% endblock%} </div> <div id="foot"> <il>1</il> <il>2</il> <il>3</il> <il>4</il> </div> {% block js %} {% endblock %} </body> </html>
#app.py
@app.route('/index')
def index():
return render_template('index.html')
父模板:
子模版
使用 url_for
if __name__ == '__main__':
print(app.url_map)
app.run()
Map([<Rule '/static/<filename>' (OPTIONS, HEAD, GET) -> static>])
#在路由里面默认就有 /static/<filename> 这条路由
加载静态文件,使用 url_for
例,加载 /static/images/1.jpg
......
{% block main %}
<div>
<button id="btn">main-part</button>
<img src="{{ url_for('static',filename='/images/1.jpg') }}" alt="">
</div>
{% endblock %}
......
例,加载样式文件
#/static/css/style.css
#head{
width: 100%;
height: 50px;
background-color: #ff0023;
}
<!--index.html-->
{% block css %}
<link rel="stylesheet"
ref="{{ url_for('static',filename='css/style.css') }}">
{% endblock %}
一个模板包含另一个模板
在A,B,C页面都共同有的部分,但其它页面没有这部分
这个时候就可以使用 include
步骤:
include 会包含整个 xxx.html
{% include 'basic.html' %}
macro 可以看作是 jinja2 的一个函数,这个函数可以返回一个 HTML 字符串
目的:代码可以复用,避免代码冗余
定义两种方式:
{% import 'macro.html' as f %}
{{ f.form('/welcome',value='注册')}}
定义宏方法1 单个文件中使用宏
macro1.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>user_macro</title> </head> <body> {% macro form(action,value='login',method='post') %} <form action={{ action }} method={{ method }}> <p> <input type="text" name="username" placeholder="username"> </p> <p> <input type="text" name="address" placeholder="address"> </p> <p> <input type="submit" value={{ value }}> </p> </form> {% endmacro %} 调用 {{ form('/','login')}} {#定义调用方法与函数类似,默认参数,可选参数 } </body> </html>
app.py
@app.route('macro')
def def_macro():
return render_template('macro/macro.html')
#调用文件时 render_template会默认以templates文件夹下开始
定义宏方法2:多个宏,将宏存放在单独文件macro.html
macro.html
{% macro form(action,value='login',method='post') %}
<form action={{ action }} method={{ method }}>
<p>
<input type="text" name="username" placeholder="username">
</p>
<p>
<input type="text" name="address" placeholder="address">
</p>
<p>
<input type="submit" value={{ value }}>
</p>
</form>
{% endmacro %}
{#可以写多个宏#}
<!--调用宏--> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>user_macro</title> </head> <body> {% import 'macro/macro.html' as f %} <!--先import宏,注意文件路径以templates文件夹开始,as f相当于起别名--> {{ f.form(action='/',value='logout') }} {{ f.form('/','logout') }} 这两种都可以 <!--使用宏,使用macro.html文件中的名为form的宏--> <!--注意:导入宏使用控制块{% %},使用宏用变量块{{ }}--> </body> </html>
app.py
@app.route('/macro')
def def_macro():
return render_template('macro/macro1.html')
{% set username='zhangsan' %}
{{ username }}
{% with num=1000 %}
{{ num }}
#可以使用
{% endwith %}
{{ num }}
#不可使用
#变量: {{ 变量 }} #块: {% if 条件 %}...{% endif %} {% for 条件 %}...{% endfor %} {% block name %}...{% endblock%} {% macro 条件 %}...{% endmacro %} {% include '' %} 包含文件 {% import '' %} 导入宏 {% extends '' %} 继承 {{ url_for('static',filename=' ' ) }} {{ marconame(xxx) }} #view: @app.route('/',endpoint='',method=['GET','POST']) def index(): return response/''/render_template('xxx.html')
https://blog.csdn.net/xrinosvip/article/details/89647884
init 方法的第一个参数永远是 self ,表示创建的实例本身,因此,在 init 方法的内部,就可以把各种属性绑定到 self,因为 self 就指向创建的 实例本身
将 app.py 文件按功能进行拆分
apps
__init__.py
包的初始化文件
from flask import Flask
import settings
def create_app():
app = Flask(__name__) #app是一个核心对象
app.config.from_object(settings)
return app
app.py
from apps import create_app
app = create_app()
if __name__ == '__main__':
app.run()
视图是一个应用对请求进行相应的函数,Flask 通过模型把进来的请求 URL 匹配到对应的处理视图。试图返回数据,Flask 把数据变成出去的响应。Flask 也可以反过来,根据视图的名称和参数生成 URL
蓝图 Blueprint 是一种组织一组相关视图及其他代码的方式。与把视图及其他代码直接注册到应用的方式不同,蓝图方式是把他们注册到蓝图,然后到工厂函数中把蓝图注册到应用。
蓝图是路由的一种表现方式
用户信息注册,更新,删除功能实现
app.py
from apps import create_app
app = create_app()
if __name__ == '__main__':
app.run()
setting.py
ENC = 'development'
DEBUG = True
apps/__init__.py
实现了把 app.py 功能拆分,导入配置文件,注册蓝图函数
from flask import Flask import settings from apps.user.view import user_bp def create_app(): app = Flask(__name__, template_folder='../templates', static_folder='../templates') # app是一个核心对象 # 用这种写法,因为 app 是在 apps/user 目录创建所以默认 templates static等目录 实在同级,所以需要手动指定 app.config.from_object(settings) app.register_blueprint(user_bp) # 将app.user.view user_bp蓝图注册到app.py print(app.url_map) return app
apps/user/view.py
实现:创建蓝图对象,路由,视图函数,整个逻辑功能实现
from flask import Blueprint, render_template, request, redirect, url_for from apps.user.model import User user_bp = Blueprint('user', __name__) # 创建蓝图对象 user_bp users = [] #对象列表 @user_bp.route('/') def user_center(): return render_template('user/show.html', users=users) @user_bp.route('/del') def delete(): username = request.args.get('username') # 从url中获取 username 的值 for user in users: if user.username == username: users.remove(user) return redirect('/') else: return 'username is not exist' @user_bp.route('/register', methods=['GET', 'POST']) def user_register(): if request.method == 'POST': # post 提交数据 username = request.form.get('username') password = request.form.get('password') repassword = request.form.get('repassword') phone = request.form.get('phone') if password == repassword: for user in users: # 遍历判断用户名是否存在 if user.username == username: return render_template('user/register.html', msg='username is exist') user = User(username, password, phone) # 创建 user 对象 users.append(user) # 添加到用户列表 users return redirect('/') # 此处添 路由 不是页面 else: return 'password is different' return render_template('user/register.html') @user_bp.route('/update', methods=['GET', 'POST'], endpoint='update') def user_update(): if request.method == 'POST': #此处 POST 必须为大写 GET、POST尽量都是大写 realname = request.form.get('realname') username = request.form.get('username') password = request.form.get('password') phone = request.form.get('phone') for user in users: if realname == user.username: user.username = username user.password = password user.phone = phone return redirect('/') else: old_username = request.args.get('username') for user in users: if old_username == user.username: return render_template('user/update.html', user=user, msg='update is ok') else: return 'username is not register' @user_bp.route('/login', methods=['get', 'post']) def user_login(): return 'user_login' @user_bp.route('/logout', methods=['get', 'post']) def user_logout(): return 'user_logout'
apps/user/model.py
class User:
def __init__(self, username, password, phone=None):
self.username = username
self.password = password
self.phone = phone
#此例用对象实现,没有使用数据库
templates/base.html
父模板
<!--页面不变的地方写上,变的地方挖坑--> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>{% block title %}user center{% endblock %}</title> <style> #head{ background-color: cadetblue; width: 100%; height: 50px; border-color: aquamarine; } #head ul{ list-style: none; height: 50px; } #head ul li{ width:20%; float: left; text-align: center; font-size: medium; line-height: 50px; } #middle{ height: 500px; } {% block mycss %} {% endblock %} </style> </head> <body> <div id="head"> <ul> <li>user center<li> <li>shopping</li> <li>browser</li> <li>going</li> <li>order</li> </ul> </div> <div id="middle"> {% block middle %} {% endblock %} </div> <div id="foot"> <ul> <li>aaa<li> </ul> </div> {% block myjs %} {% endblock %} </body> </html>
templates/user/register.html
{% extends 'base.html' %} {% block title %} user register {% endblock %} {% block mycss %} #head{ background-color: red; width: 100%; height: 50px; border-color: aquamarine; } {% endblock %} {{ msg }} {% block middle %} {# 快捷写法from*1>p*5>input*1 #} <form action="/register" method="post" > <!--<form action="{{ url_for('user.user_register') }}" method="post" > 推荐使用--> <p><input type="text" name="username" placeholder="username"></p> <p><input type="password" name="password" placeholder="password"></p> <p><input type="password" name="repassword" placeholder="re again"></p> <p><input type="number" name="phone" placeholder="phone"></p> <p><input type="submit" value="submit"> </p> </form> {% endblock %} {% block myjs %} <script> btn=document.getElementById('submit') btn.onclick=function () { alert('next very good') } </script> {% endblock %}
templates/user/show.html
{% extends 'base.html' %} {% block title %} show {% endblock %} <h1>用户信息</h1> <span> 当前用户人数{{ users |length }} </span> {% block middle %} <table border="1" cellspacing="0"> {% for user in users %} <tr> <td>{{ loop.index }}</td> <td>{{ user.username }}</td> <td>{{ user.password }}</td> <td>{{ user.phone }}</td> <td><a href="">change</a> <a href="javascript:;" onclick="del('{{ user.username }}')">delete</a></td> {# a 标签默认点击走 href ,使用JavaScript:;停用 del('要删除的内容') #} </tr> {% endfor %} </table> {% endblock %} {% block myjs %} <script> function del(username){ location.href='/del?username='+username #相当于浏览器地址栏ip地址加端口拼接上字符串并跳转 } </script> {% endblock %}
templates/user/update.html
{% extends 'base.html' %} {% block title %} user_update {% endblock %} {% block middle %} <h1>{{ msg }}</h1> <form action="{{ url_for('user.update') }}" method="post"> {# p*5>input #} <p><input type="hidden" name="realname" value="{{ user.username }}"></p> {# 直接更改 username 就没法坐后边的查寻了 #} <p><input type="text" name="username" placeholder="username" value="{{ user.username }}"></p> {# placeholder相当于提示是鼠标单击输入框就消失了,value相当于是默认值是可以在此基础上更改 #} <p><input type="password" name="password" value="{{ user.password }}"></p> <p><input type="number" name="phone" value="{{ user.phone }}"></p> <p><input type="submit"></p> </form> {% endblock %}
使用endpoint 蓝图名.endpoint
使用 蓝图名.视图函数名 作为 url_for() 内容
view.py创建蓝图
user_bp = Blueprint('user', __name__)
# 创建蓝图对象 user_bp, user为蓝图名
使用 url_for(‘蓝图名.视图函数名’)
@user_bp.route('/')
def user_center():
print(url_for('user.user_register'))
#url_for('蓝图名.视图函数名')
@user_bp.route('/register', methods=['GET', 'POST'])
def user_register():
return 'ok'
输出:/register
让命令行支持自定义命令的工具,它为 Flask 程序添加一个命令行解释器,可以让我们的程序从命令行直接执行相应命令
安装:
pip install flask-script
引入:
manager 实例
from flask_script import Manager
manager = Manager(app = app)
manager.run()
#完整app.py
from flask_script import Manager
from apps import create_app
app = create_app()
manager = Manager(app=app)
if __name__ == '__main__':
manager.run()
启动
终端:python app.py runserver -p 端口 -h 主机
自定义命令
@manager.command()
def init():
print('aaaa')
#终端 python app.py init
关系型
关系型数据库:指采用了关系模型来组织数据的数据库。
关系模型指的就是二维表格模型,而一个关系型数据库就是由二维表及其之间的联系所组成的一个数据组织。
非关系型
非关系型数据库:指非关系型的,分布式的,且一般不保证遵循ACID
原则的数据存储系统。
非关系型数据库结构:
非关系型数据库以键值对存储,且结构不固定,每一个元组可以有不一样的字段,每个元组可以根据需要增加一些自己的键值对,不局限于固定的结构,可以减少一些时间和空间的开销。
https://www.jianshu.com/p/fd7b422d5f93
数据持久化使用关系型数据库
ORM 将数据库中的表与面向对象语言中的类建立了一种对应关系,这样,操作数据库,数据库中的表或者表中的一条记录就可以直接通过操作类或者类实例来完成
SQLAlchemy 是 python 社区最知名的 ORM 工具之一,为高效和高性能的数据库访问设计,实现了完整的企业级持久模型
flask-sqlalchemy 是基于SQLAIchemy,做了提升,更方便使用
安装pymysql 建工路
pip install pymysql
安装flask-sqlalchemy 实现ORM映射
pip install flask-sqlalchemy -i https://pypi.tuna.tsinghua.edu.cn/simple
pip install flask-migrate 发布命令工具
SQLAlchemy作者开发数据迁移工具
1.设置数据库配置文件,连接sqlalchemy
SQLALCHEMY_DATABASE_URI=‘mysql+pymysql://root:root@127.0.0.1:3306/flask’
格式:数据库+驱动://user:password@hostip:port/database_name?charset=utf-8
提前设置数据库 create database flask charset=utf-8
其他配置:
配置选项 | 说明 |
---|---|
* SQLALCHEMY_DATABASE_URI | 连接数据库。示例:mysql://username:password@host/post/db?charset=utf-8 |
SQLALCHEMY_BINDS | 一个将会绑定多种数据库的字典。 更多详细信息请看官文 绑定多种数据库. |
* SQLALCHEMY_ECHO | 调试设置为true |
SQLALCHEMY_POOL_SIZE | 数据库池的大小,默认值为5。 |
SQLALCHEMY_POOL_TIMEOUT | 连接超时时间 |
SQLALCHEMY_POOL_RECYCLE | 自动回收连接的秒数。 |
SQLALCHEMY_MAX_OVERFLOW | 控制在连接池达到最大值后可以创建的连接数。当这些额外的 连接回收到连接池后将会被断开和抛弃。 |
* SQLALCHEMY_TRACK_MODIFICATIONS | 如果设置成 True (默认情况),Flask-SQLAlchemy 将会追踪对象的修改并且发送信号。这需要额外的内存, 如果不必要的可以禁用它。 |
一般设置标星三项就可以
# settings.py 文件 class Config: SQLALCHEMY_DATABASE_URI = 'mysql+pymysql://root:root@127.0.0.1:3306/flask' SQLALCHEMY_TRACK_MODIFICATIONS= False SQLALCHEMY_ECHO = True class DevelopmentConfig(Config): #继承 Config 类 #定义开发环境配置 ENC = 'development' DEBUG = True class ProductionConfig(Config): #单独定义生产环境配置 #这样在user/__init__.py下使用 app.config.from_object(settings.DevelopmentConfig) ENC = 'production' DEBUG = False
第二种方法:
创建包 ext
__init__.py
中添加:
db = SQLAlchemy() 必须跟app联系
#ext/__init__.py
#创建一个映射对象
from flask_sqlalchemy import SQLAlchemy
db = SQLAlchemy()
apps/__init__.py
def create_app():
......
db.init_app(app)
......
app.py
from flask_migrate import Migrate, MigrateCommand from flask_script import Manager from apps import create_app, db app = create_app() manager = Manager(app=app) #命令工具 migrate = Migrate(app=app, db=db) manager.add_command('db', MigrateCommand) if __name__ == '__main__': manager.run()
(flask) C:\Users\q2723\PycharmProjects\flaskProject1>python app.py Map([<Rule '/register' (OPTIONS, POST, GET, HEAD) -> user.user_register>, <Rule '/update' (OPTIONS, POST, GET, HEAD) -> user.update>, <Rule '/logout' (OPTIONS, POST, GET, HEAD) -> user.user_logout>, <Rule '/login' (OPTIONS, POST, GET, HEAD) -> user.user_login>, <Rule '/del' (OPTIONS, GET, HEAD) -> user.delete>, <Rule '/' (OPTIONS, GET, HEAD) -> user.user_center>, <Rule '/templates/<filename>' (OPTIONS, GET, HEAD) -> static>]) usage: app.py [-?] {db,shell,runserver} ... positional arguments: {db,shell,runserver} db Perform database migrations shell Runs a Python shell inside Flask application context. runserver Runs the Flask development server i.e. app.run() optional arguments: -?, --help show this help message and exit (flask) C:\Users\q2723\PycharmProjects\flaskProject1>python app.py db --help
models.py
模型就是类
from datetime import datetime from apps import db #如果导入库的这一行在 pycharm 中为灰色说明没有用到 class User(db.Model): id = db.Column(db.Integer,primary_key=True,autoincrement=True) #设为主键,自动补充 username=db.Column(db.String(15),nullable=False) #不能为空 username=db.Column(db.String(15),nullable=False) #不能为空 phone=db.Column(db.String(12),unique=True) #值不能重复 phone=db.Column(db.DateTime,default=datetime.now) #default 为默认值 datetime.now 没有()
***** 在 app.py 中导入模型,必须导入
from apps.user.models import User
终端中使用命令:db
1.python app.py db init
会产生一个文件夹 migrations,一个项目只需要执行一次
2.python app.py db migrate
每执行一次自动产生了一个版本文件,方便降级(downgrade)
3.python app.py db upgrade 同步到数据库
若文件有修改则只需执行2、3两步
界面右侧 database -> 加号 -> DateSource -> 选择数据库
填写数据,test,如果有提示,则点击下方 set time zone 再进行连接
app.py
from flask import Flask
from flask_migrate import Migrate, MigrateCommand
from apps.user.model import User
from flask_script import Manager
from apps import create_app
from ext import db
app = create_app()
manager = Manager(app=app)
migrate = Migrate(app=app, db=db)
manager.add_command('db', MigrateCommand)
if __name__ == '__main__':
manager.run()
setting.py
class Config: SQLALCHEMY_DATABASE_URI = 'mysql+pymysql://root:root@127.0.0.1:3306/flask' SQLALCHEMY_TRACK_MODIFICATIONS = False SQLALCHEMY_ECHO = True class DevelopmentConfig(Config): # 继承 Config 类 # 定义开发环境配置 ENC = 'development' DEBUG = True class ProductionConfig(Config): # 单独定义生产环境配置 # 这样在user/__init__.py下使用 app.config.from_object(settings.DevelopmentConfig) ENC = 'production' DEBUG = False
apps/__init__.py
from flask import Flask
import settings
from apps.user.view import user_bp
from ext import db
def create_app():
app=Flask(__name__, template_folder='../templates', static_folder='../static')
app.config.from_object(settings.DevelopmentConfig)
#初始化配置db
db.init_app(app=app)
app.register_blueprint(user_bp)
return app
apps/user/model.py
from datetime import datetime
from ext import db
class User(db.Model):
id =db.Column(db.Integer,primary_key=True, autoincrement=True)
username = db.Column(db.String(15),nullable=False)
password = db.Column(db.String(15), nullable=False)
phone = db.Column(db.String(15), nullable=False,unique=True)
rdatatime = db.Column(db.DateTime, default=datetime.now())
def __str__(self):
return self.username
apps/user/view.py
from flask import Blueprint, request, render_template, redirect, url_for from apps.user.model import User from ext import db user_bp = Blueprint('user', __name__) @user_bp.route('/') def index(): return 'index' @user_bp.route('/register', methods=['GET', 'POST'],endpoint='register') def register(): if request.method == 'POST': username = request.form.get('username') password = request.form.get('password') repassword = request.form.get('repassword') phone = request.form.get('phone') if password == repassword: user = User() # 与模型相结合 # 1.找到模型类并创建对象 user.username = username user.password = password user.phone = phone # 2.给对象的属性赋值 db.session.add(user) # 添加 # 3.将user对象添加到session中(类似于缓存) db.session.commit() # 4.提交数据 return 'ok' else: return render_template('user/register.html')
ext/__init__.py
from flask_sqlalchemy import SQLAlchemy
db = SQLAlchemy()
templastes和之前写的一样
md5 sha1 sha256 sha512
import hashlib str = 'helloworld' md5 = hashlib.md5(str.encode('utf-8')).hexdigest() print("md5 {} len:{}".format(md5, len(md5))) sha1 = hashlib.sha1(str.encode('utf-8')).hexdigest() print("sha1 {} len:{}".format(sha1, len(sha1))) sha256 = hashlib.sha256(str.encode('utf-8')).hexdigest() print("sha256 {} len:{}".format(sha256, len(sha256))) sha512 = hashlib.sha512(str.encode('utf-8')).hexdigest() print("sha512 {} len:{}".format(sha512, len(sha512))) #结果 md5 fc5e038d38a57032085441e7fe7010b0 len:32 sha1 6adfb183a4a2c94a2f92dab5ade762a47889a5a1 len:40 sha256 936a185caaa266bb9cbe981e9e05cb78cd732b0b3280eb944412bb6f8f8f07af len:64 sha512 1594244d52f2d8c12b142bb61f47bc2eaf503d6d9ca8480cae9fcf112f66e4967dc5e8fa98285e36db8af1b8ffa8b84cb15e0fbcf836c3deb803c13f37659a60 len:128 #要加密成什么存入数据库时要注意长度
from datetime import datetime
from ext import db
class User(db.Model):
isdelete = db.Column(db.Boolean,default=False)
def __str__(self):
return self.username
@user_bp.route('/', methods=['GET', 'POST'],endpoint='index')
def index():
users = User.query.all()
# 查询数据库中的数据,返回一个对象列表
# 相当于 select * from user
return render_template('user/index.html',users=users)
查询所有:模型类.query.all()
有条件查询:
模型类.query.filter_by(字段名=字段值)
users = User.query.filter_by(username=username)
相当于 select * from user where username = username
如果查询结果是多个,则返回一个对象列表
users = User.query.filter_by(username=username).first()
取出第一个,注意:没有 last() 用法
根据主键查询
模型类.query.get( 键值 )
get() 返回指定主键对应的行,如不存在,返回None
重点
模型类.query.filter() 里面是一个布尔的条件
模型类.query.filter().all()
如果要检索的数据是字符串类型 ```bash 模型类.query.filter( 模型名.字段名 == 值 ) 模型类.query.filter( 模型类.字段.startwith( '值' ) ).all() 以。。开始的数据 #select * from user where username like 'a%' 模型类.query.filter( 模型类.字段.endwith( '值' ) ).all() 以。。结尾的数据 #select * from user where username like '%a' 模型类.query.filter( 模型类.字段.contains( '值' ) ).all() 包含。。。的数据 #select * from user where username like '%a%' 模型类.query.filter( in_(['','']))).all() 包列表值的数据 #select * from user where username not like '%a%' 模型类.query.filter( not_(模型类.字段.contains( '值' ))).all() 不包含。。。的数据 #select * from user where username not like '%a%' 模型类.query.filter( 模型类.字段.like( 'a%' ) ).all() 以。。开头的数据 #like()里边的写法和 sql 语句一致 #select * from user where username like 'a%' 模型类.query.filter(or_(模型类.字段.like( 'a%' ), 模型类.字段.contains( '值' ))).all() 以。。开头或者包含。。的数据 #select * from user where username like 'a%' or username like %a%
如果要检索的数据是整型或日期类型
模型类.query.filter(and_(模型类.字段.like( 'a%' ), 模型类.字段.__gt__( '值' ))).all() 以。。开头且字段大于某个值的数据
#select * from user where username like 'a%' and rdatetime > %a%
#补充 __gt__,__lt__,__ge__ (gt equal),__le__ (le equal) 通常应用在整形
#也可以直接使用 > , < , >= , <= , !=
#使用需要导入对应包
between
多个条件
and_ or_ not_
#需要导入包
from sqlalchemy import or_
排序 order_by
order_by
模型类.query.order_by(模型类.字段名)
1.直接是字符串:'字段名' 但是不能倒序
2.填字段名:模型.字段 order_by(-模型.字段) 可以倒序
如果是这个报错说明返回值不是列表解决:查询语句后加.all()
限制 limit
user_list = 模型类.query.limit(2).all()
#默认获取前两条
user_list = 模型类.query.offset(2).limit(2).all()
#跳过前两条在获取两条数据
_template(‘user/index.html’,users=users)
- 查询所有:模型类.query.all() - 有条件查询: 模型类.query.filter_by(字段名=字段值) users = User.query.filter_by(username=username) 相当于 select * from user where username = username 如果查询结果是多个,则返回一个对象列表 users = User.query.filter_by(username=username).first() 取出第一个,注意:没有 last() 用法 [外链图片转存中...(img-ZX4OdjQ9-1615810321534)] - 根据主键查询 模型类.query.get( 键值 ) get() 返回指定主键对应的行,如不存在,返回None - **重点** ```bash 模型类.query.filter() 里面是一个布尔的条件 模型类.query.filter().all()
如果要检索的数据是字符串类型
模型类.query.filter( 模型名.字段名 == 值 ) 模型类.query.filter( 模型类.字段.startwith( '值' ) ).all() 以。。开始的数据 #select * from user where username like 'a%' 模型类.query.filter( 模型类.字段.endwith( '值' ) ).all() 以。。结尾的数据 #select * from user where username like '%a' 模型类.query.filter( 模型类.字段.contains( '值' ) ).all() 包含。。。的数据 #select * from user where username like '%a%' 模型类.query.filter( in_(['','']))).all() 包列表值的数据 #select * from user where username not like '%a%' 模型类.query.filter( not_(模型类.字段.contains( '值' ))).all() 不包含。。。的数据 #select * from user where username not like '%a%' 模型类.query.filter( 模型类.字段.like( 'a%' ) ).all() 以。。开头的数据 #like()里边的写法和 sql 语句一致 #select * from user where username like 'a%' 模型类.query.filter(or_(模型类.字段.like( 'a%' ), 模型类.字段.contains( '值' ))).all() 以。。开头或者包含。。的数据 #select * from user where username like 'a%' or username like %a%
如果要检索的数据是整型或日期类型
模型类.query.filter(and_(模型类.字段.like( 'a%' ), 模型类.字段.__gt__( '值' ))).all() 以。。开头且字段大于某个值的数据
#select * from user where username like 'a%' and rdatetime > %a%
#补充 __gt__,__lt__,__ge__ (gt equal),__le__ (le equal) 通常应用在整形
#也可以直接使用 > , < , >= , <= , !=
#使用需要导入对应包
between
多个条件
and_ or_ not_
#需要导入包
from sqlalchemy import or_
排序 order_by
order_by
模型类.query.order_by(模型类.字段名)
1.直接是字符串:'字段名' 但是不能倒序
2.填字段名:模型.字段 order_by(-模型.字段) 可以倒序
如果是这个报错说明返回值不是列表解决:查询语句后加.all()[外链图片转存中…(img-8RYfUwV0-1615810321535)]
限制 limit
user_list = 模型类.query.limit(2).all()
#默认获取前两条
user_list = 模型类.query.offset(2).limit(2).all()
#跳过前两条在获取两条数据
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。