python web框架 flask基础入门教程
今天我们写一个flask基础入门教程,当然也会覆盖很多重要的知识点,在这篇博客中,我们主要会讲解如下内容:
1、通过flask框架向web传输和接收参数
2、实现静态图片插入和图书上传
3、实现搭建的网站局域网共享
4、实现html模板继承
5、实现javascript 、css渲染
6、连接数据库,创建模型,实现自动建表
7、实现对数据库表的增删改查
8、实现按钮与函数交互
9、实现链接跳转
那么先开始我们的第一条内容:
项目文件结构如下:
然后导入相关库:
from flask import Flask, request, render_templatefrom datetime import datetime
from flask import render_template
from FlaskWebLearning import app
from flask_sqlalchemy import SQLAlchemyimport pymysql
1、通过flask框架向web传毒和接收参数
先让我们来看一下最简单的路由程序:
@app.route('/')
@app.route('/home')
def home():return"hello world "
通过上面方法程序,我们就可以实现这样的结果
对于这部份内容,我们先看第一种传输数据的方式:
@app.route('/test2/<your_word>')
def test3(your_word):return '你想说的话:'+your_word
运行我们的app之后,输入如下网址,我们可以得到这样的结果:
第二中我们则也可以通过后端进行数据传输进行数据传输,并将数据传输给模板:
@app.route('/cs/<title>')
def cs(title):return render_template("about.html",title=title,message="测试程序")
输入链接:http://127.0.0.1:5555/cs/dfafd、得到如下界面
注:做到这一步其实就用到了模板,下面我们把本次用到的所有的模板列出来:
about.html
{% extends "layout.html" %}{% block content %}<h2>{{ title }}.</h2>
<h3>{{ message }}</h3><img src="{{url_for('static',filename='image/6.png')}}">
<p>Use this area to provide additional information.</p><address>One Microsoft Way<br />Redmond, WA 98052-6399<br /><abbr title="Phone">P:</abbr>425.555.0100
</address><address><strong>Support:</strong> <a href="mailto:Support@example.com">Support@example.com</a><br /><strong>Marketing:</strong> <a href="mailto:Marketing@example.com">Marketing@example.com</a>
</address>{% endblock %}
form.html
{% extends "layout.html" %}{% block content %}<form action="{{ url_for('form') }}" method="post"><label for="username">Username</label><br><input type="text" name="username" placeholder="Héctor Rivera"><br><label for="password">Password</label><br><input type="password" name="password" placeholder="19001130"><br><input type="submit" name="submit" value="Log in">
</form><a href="https://bilibili.com">网址直接跳转</a>
<a href="/link">链接跳转</a><!--<a href="images/1.webp">相对路径跳转</a>网址直接跳转</a>--><address>One Microsoft Way<br />Redmond, WA 98052-6399<br /><abbr title="Phone">P:</abbr>425.555.0100</address><address><strong>Support:</strong> <a href="mailto:Support@example.com">Support@example.com</a><br /><strong>Marketing:</strong> <a href="mailto:Marketing@example.com">Marketing@example.com</a></address>{% endblock %}
index.html
{% extends "layout.html" %}{% block content %}<div class="jumbotron"><h1>Flask</h1><p class="lead">Flask is a free web framework for building great Web sites and Web applications using HTML, CSS and JavaScript.</p><p><a href="http://flask.pocoo.org/" class="btn btn-primary btn-large">Learn more »</a></p>
</div>
<div><form method="post" action="/up_photo" enctype="multipart/form-data"><input type="file" size="30" name="photo" /><br><input type="text" class="txt_input" name="name" style="margin-top:15px;" /><input type="submit" value="提交信息" class="button-new" style="margin-top:15px;" /></form>
</div>
<div class="row"><div class="col-md-4"><h2>Getting started</h2><p>Flask gives you a powerful, patterns-based way to build dynamic websites thatenables a clean separation of concerns and gives you full control over markupfor enjoyable, agile development.</p><p><a class="btn btn-default" href="http://flask.pocoo.org/docs/">Learn more »</a></p></div><div class="col-md-4"><h2>Get more libraries</h2><p>The Python Package Index is a repository of software for the Python programming language.</p><p><a class="btn btn-default" href="https://pypi.python.org/pypi">Learn more »</a></p></div><div class="col-md-4"><h2>Microsoft Azure</h2><p>You can easily publish to Microsoft Azure using Visual Studio. Find out how you can host your application using a free trial today.</p><p><a class="btn btn-default" href="http://azure.microsoft.com">Learn more »</a></p></div>
</div>{% endblock %}
layout.html
<!DOCTYPE html>
<html>
<head><meta charset="utf-8" /><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>{{ title }} - My Flask Application</title><link rel="stylesheet" type="text/css" href="/static/content/bootstrap.min.css" /><link rel="stylesheet" type="text/css" href="/static/content/site.css" /><script src="/static/scripts/modernizr-2.6.2.js"></script>
</head><body><div class="navbar navbar-inverse navbar-fixed-top"><div class="container"><div class="navbar-header"><button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse"><span class="icon-bar"></span><span class="icon-bar"></span><span class="icon-bar"></span></button><a href="/" class="navbar-brand">Application name</a></div><div class="navbar-collapse collapse"><ul class="nav navbar-nav"></ul></div></div></div><div class="container body-content">{% block content %}{% endblock %}<hr /><footer><p>© {{ year }} - My Flask Application</p></footer></div><script src="/static/scripts/jquery-1.10.2.js"></script><script src="/static/scripts/bootstrap.js"></script><script src="/static/scripts/respond.js"></script>{% block scripts %}{% endblock %}</body>
</html>
test.html
<!DOCTYPE html>
<html>
<head><meta http-equiv="Content-Type" content="text/html; charset=GBK" /><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>{{ title }} - My Flask Application</title><link rel="stylesheet" type="text/css" href="/static/content/bootstrap.min.css" /><link rel="stylesheet" type="text/css" href="/static/content/site.css" /><script src="/static/scripts/modernizr-2.6.2.js"></script>
</head><body><h2>濮撳悕锛歿{person.name}}</h2><h2>骞撮緞锛歿{person.age}}</h2><div class="container body-content">{% block content %}{% endblock %}<hr /><footer><p>© {{ year }} - My Flask Application</p></footer></div><script src="/static/scripts/jquery-1.10.2.js"></script><script src="/static/scripts/bootstrap.js"></script><script src="/static/scripts/respond.js"></script>{% block scripts %}{% endblock %}</body>
</html>
test2.html
<!DOCTYPE html>
<html>
<head><meta http-equiv="Content-Type" content="text/html; charset=GBK" /><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>{{ title }} - My Flask Application</title><link rel="stylesheet" type="text/css" href="/static/content/bootstrap.min.css" /><link rel="stylesheet" type="text/css" href="/static/content/site.css" /><script src="/static/scripts/modernizr-2.6.2.js"></script>
</head><body><h2>{{strz|dformat}}</h2><div class="container body-content">{% block content %}{% endblock %}<hr /><footer><p>© {{ year }} - My Flask Application</p></footer></div><script src="/static/scripts/jquery-1.10.2.js"></script><script src="/static/scripts/bootstrap.js"></script><script src="/static/scripts/respond.js"></script>{% block scripts %}{% endblock %}</body>
</html>
test3.html
<!DOCTYPE html>
<html>
<head><meta http-equiv="Content-Type" content="text/html; charset=utf8" /><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>{{ title }} - My Flask Application</title><link rel="stylesheet" type="text/css" href="/static/content/bootstrap.min.css" /><link rel="stylesheet" type="text/css" href="/static/content/site.css" /><script src="/static/scripts/modernizr-2.6.2.js"></script>
</head><body>{%if age<18 %}<p>鏈弧18宀侊紝鍙互鍘荤綉鍚т簡</p>{% else %}<p>宸叉弧18宀侊紝涓嶅彲浠ュ幓缃戝惂</p>{% endif %}<div class="container body-content">{% block content %}{% endblock %}<hr /><footer><p>© {{ year }} - My Flask Application</p></footer></div><script src="/static/scripts/jquery-1.10.2.js"></script><script src="/static/scripts/bootstrap.js"></script><script src="/static/scripts/respond.js"></script>{% block scripts %}{% endblock %}</body>
</html>
同样,我们也可以传输我们的对象给前端:
@app.route('/person')
def person():p=Person("zhangsan",78)return render_template("test.html",person=p)
下面做一个小插曲,html过滤器的使用:
注意过滤器其实非常非常重要,他的作用性很大,可以帮助我们处理各种各样的字符,数字等转换
def filter1(value):return value[2:5]
app.add_template_filter(filter1,'dformat')@app.route('/filter/<s>')
def filter(s):return render_template("test2.html",strz=s)
2、实现静态图片插入和图书上传
(1)静态图片插入,这部分内容其实比较简单哈:
看一下代码:
<img src="{{url_for('static',filename='image/6.png')}}">
完整代码如下
{% extends "layout.html" %}{% block content %}<h2>{{ title }}.</h2>
<h3>{{ message }}</h3><img src="{{url_for('static',filename='image/6.png')}}">
<p>Use this area to provide additional information.</p><address>One Microsoft Way<br />Redmond, WA 98052-6399<br /><abbr title="Phone">P:</abbr>425.555.0100
</address><address><strong>Support:</strong> <a href="mailto:Support@example.com">Support@example.com</a><br /><strong>Marketing:</strong> <a href="mailto:Marketing@example.com">Marketing@example.com</a>
</address>{% endblock %}
通过这个代码我们就可以实现静态图片插入:
(2)图片上传
路由函数
@app.route('/index')
def index():return render_template("index.html")@app.route('/up_photo', methods=['post'])
def up_photo():img = request.files.get('photo')username = request.form.get("name")path =r"FlaskWebLearning/static/image/"file_path = path+img.filenameimg.save(file_path)print('上传头像成功,上传的用户是:'+username)return render_template('index.html')
注意,先进入/index路由,会显示图片上传界面:
3、实现搭建的网站局域网共享
这里比简单:
只需要在app.run()的时候传入host=‘0.0.0.0’,那么你搭建的网站,链接局域网的就都可以访问了。
"""
#coding=gbk
from os import environfrom FlaskWebLearning import appif __name__ == '__main__':HOST = '222.19.67.89'try:PORT = int(environ.get('SERVER_PORT', '5555'))except ValueError:PORT = 5555app.run(host='0.0.0.0',port=5555)
4、实现html模板继承
模板继承:
{% extends "layout.html" %}
{% extends "layout.html" %}{% block content %}<h2>{{ title }}.</h2>
<h3>{{ message }}</h3><img src="{{url_for('static',filename='image/6.png')}}">
<p>Use this area to provide additional information.</p><address>One Microsoft Way<br />Redmond, WA 98052-6399<br /><abbr title="Phone">P:</abbr>425.555.0100
</address><address><strong>Support:</strong> <a href="mailto:Support@example.com">Support@example.com</a><br /><strong>Marketing:</strong> <a href="mailto:Marketing@example.com">Marketing@example.com</a>
</address>{% endblock %}
这就是模板继承的代码,会把layout.html先加载,那么还有模板补充:
{% block content %} {% endblock %}之间的内容会被补充道layout.html网页里,补充的地方就在
对应的{% block content %} {% endblock %}之间
5、实现javascript 、css渲染
这个代码比较简单:
<head><meta charset="utf-8" /><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>{{ title }} - My Flask Application</title><link rel="stylesheet" type="text/css" href="/static/content/bootstrap.min.css" /><link rel="stylesheet" type="text/css" href="/static/content/site.css" /><script src="/static/scripts/modernizr-2.6.2.js"></script>
</head>
6、连接数据库,创建模型,实现自动建表
链接数据库:
pymysql.install_as_MySQLdb()# 设置数据库连接地址
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql://root:密码@127.0.0.1:3306/数据库名?charset=utf8'
# 是否追踪数据库修改(开启后会触发一些钩子函数) 一般不开启, 会影响性能
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
# 是否显示底层执行的SQL语句
app.config['SQLALCHEMY_ECHO'] = Truedb = SQLAlchemy(app)
创建模型:
#ORM对象关系映射class User(db.Model):__tablename__='user'id=db.Column(db.Integer,primary_key=True,autoincrement=True)username=db.Column(db.String(100))password=db.Column(db.String(100))# articles=db.relationship("Article",back_populates='author')class Article(db.Model):__tablename__='article'id=db.Column(db.Integer,primary_key=True,autoincrement=True)title=db.Column(db.String(200),nullable=False)content=db.Column(db.Text,nullable=False)author_id=db.Column(db.Integer,db.ForeignKey("user.id"))author=db.relationship('User',backref='articles')
实现自动建表:
#user=User(username="张三",password="123456")with app.app_context():db.create_all()
7、实现对数据库表的增删改查
数据库增加表数据:
@app.route('/user/add')
def add_user():user1=User(username="张三",password="123456")user2=User(username="李四",password="123456")user3=User(username="王五",password="123456")db.session.add(user1)db.session.add(user2)db.session.add(user3)db.session.commit()return "用户数据导入成功"
数据库删除表数据:
@app.route('/user/delete')
def delete_user():user1=db.query.get(1)#根据主键查找print(user1)db.session.delete(user1)db.session.commit()return "数据删除成功"
数据库修改表数据:
@app.route('/user/update')
def updatae_user():users=User.query.filter_by(username='李四')#根据主键查找for user in users:user.password='222222'# db.session.delete(user1)db.session.commit()return "数据更新成功"
数据库查询表数据:
@app.route('/user/query')
def query_user():user1=User.query.get(1)#根据主键查找print(user1)users=User.query.filter_by(username='李四')#根据主键查找print(users)users=User.query.all()#根据主键查找s=''for i in users:print(i.username,i.password)s=s+i.username+' '+i.password+'\n'db.session.commit()return s
8、实现按钮与函数交互
最后呢,我们做一个按钮和函数交互的操作,并实现,数据库的数据增加:
@app.route('/page', methods=['GET', 'POST'])
def page():return render_template("form.html")
@app.route('/form', methods=['GET', 'POST'])
def form():if request.method == 'POST':username1 = request.form['username']password1 = request.form['password']print(username1, password1)user1=User(username=username1,password=password1)db.session.add(user1)db.session.commit()return "数据导入成功"return "hello"
{% extends "layout.html" %}{% block content %}<form action="{{ url_for('form') }}" method="post"><label for="username">Username</label><br><input type="text" name="username" placeholder="Héctor Rivera"><br><label for="password">Password</label><br><input type="password" name="password" placeholder="19001130"><br><input type="submit" name="submit" value="Log in">
</form><a href="https://bilibili.com">网址直接跳转</a>
<a href="/link">链接跳转</a><!--<a href="images/1.webp">相对路径跳转</a>网址直接跳转</a>--><address>One Microsoft Way<br />Redmond, WA 98052-6399<br /><abbr title="Phone">P:</abbr>425.555.0100</address><address><strong>Support:</strong> <a href="mailto:Support@example.com">Support@example.com</a><br /><strong>Marketing:</strong> <a href="mailto:Marketing@example.com">Marketing@example.com</a></address>{% endblock %}
首先进入page路由:
然后输入数据:
点击log in:
刚才输入的数据就会被导入数据库。