时间:2023-05-29 01:36:01 | 来源:网站运营
时间:2023-05-29 01:36:01 来源:网站运营
Python Web 开发框架Flask快速入门:pip install flask
helloFlask.py
,编写代码如下:from flask import Flaskapp = Flask(__name__)@app.route('/')def hello_world(): return 'Hello World!'if __name__ == '__main__': app.run()
python helloFlask.py
app.run(host='0.0.0.0')
@app.route('/')def index(): return 'Index Page'@app.route('/hello')def hello(): return 'Hello World'
return
返回,这样定义就太麻烦了吧,因为定义字符串是不会出任何效果和错误的,如果有一个专门定义前端页面的地方就好了。templates
文件夹里寻找模板。所以,如果你的应用是个模块,这个文件夹应该与模块同级;如果它是一个包,那么这个文件夹作为包的子目录:template
文件夹下创建模板index.html
render_template()
方法来渲染模板。你需要做的一切就是将模板名和你想作为关键字的参数传入模板的变量。这里有一个展示如何渲染模板的简例:from flask import render_template@app.route('/index/')def hello(name=None): name = "张三" return render_template('index.html', name=name)
index.html
中添加如下代码:<!doctype html><title>Hello from Flask</title>{% if name %} <h1>Hello {{ name }}!</h1>{% else %} <h1>Hello World!</h1>{% endif %}
127.0.0.1:5000/index
即可看到如下结果:{{ 变量名 }}
key
和 value
:render_template('index.html', name="张三")
{% if name %}{% else %}{% endif %}
{% for i in range(1,10) %} {% for j in range(1,i+1) %} {{ j }} x {{ i }} = {{ i*j }} {% endfor %} <br>{% endfor %}
sql
语句,那么能不能不写sql
语句就可以操作数据库呢? 答案是可以的。mysql
数据库,需要安装一个flask-sqlalchemy
的扩展。pip install flask-sqlalchemy
flask-mysqldb
pip install flask-mysqldb
test3
数据库,假设用户名为root
,密码为mysql
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql://root:mysql@127.0.0.1:3306/test3'
from flask import Flaskfrom flask_sqlalchemy import SQLAlchemyapp = Flask(__name__)#设置连接数据库的URLapp.config['SQLALCHEMY_DATABASE_URI'] = 'mysql://root:mysql@127.0.0.1:3306/Flask_test'#设置每次请求结束后会自动提交数据库中的改动app.config['SQLALCHEMY_COMMIT_ON_TEARDOWN'] = Trueapp.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True#查询时会显示原始SQL语句app.config['SQLALCHEMY_ECHO'] = Truedb = SQLAlchemy(app)class Role(db.Model): # 定义表名 __tablename__ = 'roles' # 定义列对象 id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(64), unique=True) us = db.relationship('User', backref='role')class User(db.Model): __tablename__ = 'users' id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(64), unique=True, index=True) email = db.Column(db.String(64),unique=True) pswd = db.Column(db.String(64)) role_id = db.Column(db.Integer, db.ForeignKey('roles.id'))if __name__ == '__main__': db.drop_all() db.create_all() ro1 = Role(name='admin') ro2 = Role(name='user') db.session.add_all([ro1,ro2]) db.session.commit() us1 = User(name='wang',email='wang@163.com',pswd='123456',role_id=ro1.id) us2 = User(name='zhang',email='zhang@189.com',pswd='201512',role_id=ro2.id) us3 = User(name='chen',email='chen@126.com',pswd='987654',role_id=ro2.id) us4 = User(name='zhou',email='zhou@163.com',pswd='456789',role_id=ro1.id) db.session.add_all([us1,us2,us3,us4]) db.session.commit() app.run(debug=True)
db.create_all()
db.drop_all()
ro1 = Role(name='admin')db.session.add(ro1)db.session.commit()#再次插入一条数据ro2 = Role(name='user')db.session.add(ro2)db.session.commit()
us1 = User(name='wang',email='wang@163.com',pswd='123456',role_id=ro1.id)us2 = User(name='zhang',email='zhang@189.com',pswd='201512',role_id=ro2.id)us3 = User(name='chen',email='chen@126.com',pswd='987654',role_id=ro2.id)us4 = User(name='zhou',email='zhou@163.com',pswd='456789',role_id=ro1.id)db.session.add_all([us1,us2,us3,us4])db.session.commit()
User.query.filter_by(name='wang').all()
User.query.first()
User.query.all()
User.query.filter(User.name.endswith('g')).all()
User.query.get()
User.query.filter(User.name!='wang').all()
from sqlalchemy import and_User.query.filter(and_(User.name!='wang',User.email.endswith('163.com'))).all()
from sqlalchemy import or_User.query.filter(or_(User.name!='wang',User.email.endswith('163.com'))).all()
user = User.query.first()db.session.delete(user)db.session.commit()User.query.all()
user = User.query.first()user.name = 'dong'db.session.commit()User.query.first()
User.query.filter_by(name='zhang').update({'name':'li'})
#查询roles表id为1的角色ro1 = Role.query.get(1)#查询该角色的所有用户ro1.us
#查询users表id为3的用户us1 = User.query.get(3)#查询用户属于什么角色us1.role
from flask import Flask,render_template,request,redirectfrom flask_sqlalchemy import SQLAlchemyapp = Flask(__name__)db = SQLAlchemy(app)#设置数据库连接app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql://root:asd8283676@127.0.0.1:3306/web'#定义模型class City(db.Model): #表模型 id = db.Column(db.Integer,primary_key=True,autoincrement=True) provincename = db.Column(db.String(255)) cityname = db.Column(db.String(255)) usernumber = db.Column(db.Integer)#查询所有数据@app.route("/select")def selectAll(): cityList = City.query.order_by(City.id.desc()).all() return render_template("index.html",city_list = cityList)@app.route('/')def index(): return selectAll()#添加数据@app.route('/insert',methods=['GET','POST'])def insert(): #进行添加操作 province = request.form['province'] cityname = request.form['city'] number = request.form['number'] city = City(provincename=province,cityname=cityname,usernumber=number) db.session.add(city) db.session.commit() #添加完成重定向至主页 return redirect('/')@app.route("/insert_page")def insert_page(): #跳转至添加信息页面 return render_template("insert.html")#删除数据@app.route("/delete",methods=['GET'])def delete(): #操作数据库得到目标数据,before_number表示删除之前的数量,after_name表示删除之后的数量 id = request.args.get("id") city = City.query.filter_by(id=id).first() db.session.delete(city) db.session.commit() return redirect('/')#修改操作@app.route("/alter",methods=['GET','POST'])def alter(): # 可以通过请求方式来改变处理该请求的具体操作 # 比如用户访问/alter页面 如果通过GET请求则返回修改页面 如果通过POST请求则使用修改操作 if request.method == 'GET': id = request.args.get("id") province = request.args.get("provincename") cityname = request.args.get("cityname") usernumber = request.args.get("usernumber") city = City(id = id,provincename=province,cityname=cityname,usernumber = usernumber) return render_template("alter.html",city = city) else: #接收参数,修改数据 id = request.form["id"] province = request.form['province'] cityname = request.form['city'] number = request.form['number'] city = City.query.filter_by(id = id).first() city.provincename = province city.cityname = cityname city.usernumber = number db.session.commit() return redirect('/')if __name__ == "__main__": app.run(debug = True,host='0.0.0.0',port=8080)
index.html
<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <title>首页</title></head><body> <div align="center"> <br> <a href="insert_page">添加城市</a> <br> <br> <table width="600" cellpadding="5" align="center" border="1" cellspacing="0"> <th align="center" colspan="4">城市信息</th> <tr> <td>province</td> <td>cityname</td> <td>usernumber</td> <td>操作</td> </tr> {% for item in city_list %} <tr> <td>{{item.provincename}}</td> <td>{{item.cityname}}</td> <td>{{item.usernumber}}</td> <td><a href='/alter?id={{item.id}}&provincename={{ item.provincename }}&cityname={{ item.cityname }}&usernumber={{item.usernumber}}'>编辑</a> <a href="/delete?id={{ item.id }}">删除</a> </td> </tr> {% endfor %} </table> </div></body></html>
alter.html
<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <title>修改</title></head><body><div class="layui-main"> <div class="site-content"> <br><br> <h1 class="site-h1">修改信息</h1> <br><br> <form class="layui-form" action="alter" method="post"> <input type="hidden" name = 'id' value="{{city.id}}"> <div class="layui-form-item"> <label class="layui-form-label">省份</label> <div class="layui-input-block"> <input type="text" name="province" required lay-verify="required" placeholder="请输入省份" autocomplete="off" class="layui-input" value="{{city.provincename}}"> </div> </div> <div class="layui-form-item"> <label class="layui-form-label">城市</label> <div class="layui-input-block"> <input type="text" name="city" required lay-verify="required" placeholder="请输入城市名称" autocomplete="off" class="layui-input" value="{{city.cityname}}"> </div> </div> <div class="layui-form-item"> <label class="layui-form-label">人数</label> <div class="layui-input-block"> <input type="number" name="number" required lay-verify="required" placeholder="请输入人数" autocomplete="off" class="layui-input" value="{{city.usernumber}}"> </div> </div> <div class="layui-form-item"> <div class="layui-input-block"> <button class="layui-btn" lay-submit lay-filter="formDemo">立即提交</button> <button type="reset" class="layui-btn layui-btn-primary">重置</button> </div> </div> </form> </div></div></body></html>
insert.html
<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <title>增加</title></head><body><div class="layui-main"> <div class="site-content"> <br><br> <h1 class="site-h1">添加信息</h1><br><br> <form class="layui-form" action="insert" method="post"> <div class="layui-form-item"> <label class="layui-form-label">省份</label> <div class="layui-input-block"> <input type="text" name="province" required lay-verify="required" placeholder="请输入省份" autocomplete="off" class="layui-input"> </div> </div> <div class="layui-form-item"> <label class="layui-form-label">城市</label> <div class="layui-input-block"> <input type="text" name="city" required lay-verify="required" placeholder="请输入城市" autocomplete="off" class="layui-input"> </div> </div> <div class="layui-form-item"> <label class="layui-form-label">用户数</label> <div class="layui-input-block"> <input type="number" name="number" required lay-verify="required" placeholder="请输入用户数量" autocomplete="off" class="layui-input"> </div> </div> <div class="layui-form-item"> <div class="layui-input-block"> <button class="layui-btn" lay-submit lay-filter="formDemo">立即提交</button> <button type="reset" class="layui-btn layui-btn-primary">重置</button> </div> </div> </form> </div></div></body></html>
static
目录下(static目录用于存放静态文件如css
,js
文件可以让网站看起来更加美观)。index.html:
<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <title>首页</title> <link rel="stylesheet" href="/static/layui/css/layui.css"></head><body> <div align="center"> <br> <a href="insert_page">添加城市</a> <br> <br> <table id = 'tabledemo'lay-filter="test"> <thead> <tr> <th lay-data="{field:'id', width:100}">编号</th> <th lay-data="{field:'provincename', width:100}">省份</th> <th lay-data="{field:'cityname', width:80, sort:true}">城市名称</th> <th lay-data="{field:'usernumber'}">用户数量</th> <th lay-data="{fixed: 'right', width: 165, align:'center', toolbar: '#barDemo'}"></th> </tr> </thead> <tbody> {% for item in city_list %} <tr> <td>{{item.id}}</td> <td>{{item.provincename}}</td> <td>{{item.cityname}}</td> <td>{{item.usernumber}}</td> </tr> {% endfor %} </tbody> </table> </div><script type="text/html" id="barDemo"> <a class="layui-btn layui-btn-xs" lay-event="edit">编辑</a> <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a></script><script src="/static/layui/layui.js"></script><script> layui.use('table', function () { var table = layui.table;//转换静态表格 table.init('test', { height: 1000, width: 600//设置高度 ,limit:100 }); table.on('tool(test)', function(obj){ //注:tool 是工具条事件名,test 是 table 原始容器的属性 lay-filter="对应的值" var data = obj.data //获得当前行数据 ,layEvent = obj.event; //获得 lay-event 对应的值 if(layEvent === 'detail'){ layer.msg('查看操作'); } else if(layEvent === 'del'){ layer.confirm('真的删除行么', function(index){ location.href='/delete?id='+data.id; }); } else if(layEvent === 'edit'){ location.href='/alter?id=' + data.id + "&provincename=" +data.provincename + "&cityname=" + data.cityname + "&usernumber=" + data.usernumber; } }); });</script></body></html>
alter.html:
<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <title>修改</title> <link rel="stylesheet" href="/static/layui/css/layui.css"></head><body><div class="layui-main"> <div class="site-content"> <br><br> <h1 class="site-h1">修改信息</h1> <br><br> <form class="layui-form" action="alter" method="post"> <input type="hidden" name = 'id' value="{{city.id}}"> <div class="layui-form-item"> <label class="layui-form-label">省份</label> <div class="layui-input-block"> <input type="text" name="province" required lay-verify="required" placeholder="请输入省份" autocomplete="off" class="layui-input" value="{{city.provincename}}"> </div> </div> <div class="layui-form-item"> <label class="layui-form-label">城市</label> <div class="layui-input-block"> <input type="text" name="city" required lay-verify="required" placeholder="请输入城市名称" autocomplete="off" class="layui-input" value="{{city.cityname}}"> </div> </div> <div class="layui-form-item"> <label class="layui-form-label">人数</label> <div class="layui-input-block"> <input type="number" name="number" required lay-verify="required" placeholder="请输入人数" autocomplete="off" class="layui-input" value="{{city.usernumber}}"> </div> </div> <div class="layui-form-item"> <div class="layui-input-block"> <button class="layui-btn" lay-submit lay-filter="formDemo">立即提交</button> <button type="reset" class="layui-btn layui-btn-primary">重置</button> </div> </div> </form> </div></div><script src="/static/layui/layui.js"></script><script> //Demo layui.use('form', function () { var form = layui.form; });</script></body></html>
insert.html:
<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <title>增加</title> <link rel="stylesheet" href="/static/layui/css/layui.css"></head><body><div class="layui-main"> <div class="site-content"> <br><br> <h1 class="site-h1">添加信息</h1><br><br> <form class="layui-form" action="insert" method="post"> <div class="layui-form-item"> <label class="layui-form-label">省份</label> <div class="layui-input-block"> <input type="text" name="province" required lay-verify="required" placeholder="请输入省份" autocomplete="off" class="layui-input"> </div> </div> <div class="layui-form-item"> <label class="layui-form-label">城市</label> <div class="layui-input-block"> <input type="text" name="city" required lay-verify="required" placeholder="请输入城市" autocomplete="off" class="layui-input"> </div> </div> <div class="layui-form-item"> <label class="layui-form-label">用户数</label> <div class="layui-input-block"> <input type="number" name="number" required lay-verify="required" placeholder="请输入用户数量" autocomplete="off" class="layui-input"> </div> </div> <div class="layui-form-item"> <div class="layui-input-block"> <button class="layui-btn" lay-submit lay-filter="formDemo">立即提交</button> <button type="reset" class="layui-btn layui-btn-primary">重置</button> </div> </div> </form> </div></div><script src="/static/layui/layui.js"></script><script> layui.use('form', function () { var form = layui.form; });</script></body></html>
nohup python app.py &
exit
命令退出 linux 的连接8848
端口。server {listen 80;autoindex on;server_name flask.codejiaonang.com;access_log /usr/local/nginx/logs/access.log combined;location / { proxy_pass http://127.0.0.1:8848/; }}
关键词:入门