环境
centos7 python3.6
环境部署
yum install python3 pip3 install flask
项目创建
mkdir newproj cd newproj
# cat > Hello_development.py <<EOF ###开发模式 from flask import Flask app = Flask(__name__) app.debug = True ##开启是可以实时查看 @app.route('/') def hello_world(): return 'Hello World' if __name__ == '__main__': app.run('0.0.0.0',5000) EOF
# cat > Hello_production.py <<EOF ###生产模式 from flask import Flask from wsgiref.simple_server import make_server app = Flask(__name__) @app.route('/') def hello_world(): return "hello" @app.route('/web') def hello_world2(): return "hello web" if __name__ == '__main__': server = make_server('0.0.0.0', 5000, app) server.serve_forever() EOF
# python3 Hello_production.py 浏览器访问http://ip:5000
Flask 路由
@app.route('/hello') def hello_world(): return 'hello world' http://localhost5000/hello
Flask 变量规则
from flask import Flask app = Flask(__name__) @app.route('/hello/<name>') ##字符串变量 def hello_name(name): return 'Hello %s!' % name @app.route('/blog/<int:postID>') ##int型变量 def show_blog(postID): return 'Blog Number %d' % postID @app.route('/rev/<float:revNo>') ##浮点型变量 def revision(revNo): return 'Revision Number %f' % revNo if __name__ == '__main__': app.run(debug = True)
打开浏览器并输入URL http://localhost:5000/hello/feko 如果输入http://localhost:5000/hello/feko/ 就会报404
规范URL
Flask的URL规则基于Werkzeug的路由模块。这确保形成的URL是唯一的,并且基于Apache规定的先例。
from flask import Flask app = Flask(__name__) @app.route('/hello/<name>/') ##字符串变量 def hello_name(name): return 'Hello %s!' % name @app.route('/blog/<int:postID>/') ##int型变量 def show_blog(postID): return 'Blog Number %d' % postID @app.route('/rev/<float:revNo>/') ##浮点型变量 def revision(revNo): return 'Revision Number %f' % revNo if __name__ == '__main__': app.run(debug = True)
打开浏览器并输入URL http://localhost:5000/hello/feko 或 http://localhost:5000/hello/feko/ 都不会报错
Flask URL构建
URL重定向 from flask import Flask, redirect, url_for app = Flask(__name__) @app.route('/admin/') def hello_admin(): return 'Hello Admin' @app.route('/guest/<guest>/') def hello_guest(guest): return 'Hello %s as Guest' % guest @app.route('/user/<name>/') def hello_user(name): if name =='admin': return redirect(url_for('hello_admin')) else: return redirect(url_for('hello_guest',guest = name)) if __name__ == '__main__': app.run(debug = True)
打开浏览器并输入URL - http://localhost:5000/user/admin 浏览器中的应用程序响应是: Hello Admin 在浏览器中输入以下URL - http://localhost:5000/user/feko 应用程序响应现在更改为: Hello feko as Guest
HTTP方法
GET - 从指定的资源请求数据。以未加密的形式将数据发送到服务器。最常见的方法。 POST - 向指定的资源提交要被处理的数据,用于将HTML表单数据发送到服务器。 login.html
<html> <body> <form action = "http://192.168.209.211:5000/login/" method = "post"> <p>Enter Name:</p> <p><input type = "text" name = "nm" /></p> <p><input type = "submit" value = "submit" /></p> </form> </body> </html>
Hello_development.py
from flask import Flask, redirect, url_for, request app = Flask(__name__) @app.route('/success/<name>/') def success(name): return 'welcome %s' % name @app.route('/login/',methods = ['POST', 'GET']) ##action 地址要对应,有'/'也有'/' def login(): if request.method == 'POST': user = request.form['nm'] return redirect(url_for('success',name = user)) else: user = request.args.get('nm') return redirect(url_for('success',name = user)) if __name__ == '__main__': app.run(debug = True)
Flask 模板使用
render_template 函数用于渲染模板 模板必须放在templates目录下 Hello_development.py
from flask import Flask, render_template app = Flask(__name__) @app.route('/') def index(): my_int = 1 my_str = 'fafa' my_list = [1,2,3,4,5,6] my_dict = { 'name': 'feko', 'age': 26 } # render_template方法:渲染模板 # 参数1: 模板名称 参数n: 传到模板里的数据 return render_template('hello.html', my_int=my_int, my_str=my_str, my_list=my_list, my_dict=my_dict ) if __name__ == '__main__': app.run(debug=True)
cat templates/hello.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <h3>我是模板</h3> {{ my_int }} <br> {{ my_str }} <br> {{ my_list }} <br> {{ my_dict }} <hr> <h3>两种方法:模板的list数据获取</h3> <hr> {{ my_list[0] }} <br> {{ my_list.1 }} <hr> <h3>两种方法:字典数据获取</h3> <hr> {{ my_dict['name'] }} <br> {{ my_dict.age }} <hr> <h3>两种方法:算术运算</h3> <br> {{ my_list.0 + 10 }} <br> {{ my_list[0] + my_list.1 }} </body> </html>
Flask 静态文件 静态文件主要包括js/css文件,并存在static目录下 python程序去渲染html模板,模板再去调用js里面的函数 Hello_development.py
from flask import Flask, render_template app = Flask(__name__) @app.route("/") def index(): return render_template("index.html") if __name__ == '__main__': app.run(debug = True)
templates/index.html
<html> <head> <script type = "text/javascript" src = "{{ url_for('static', filename = 'hello.js') }}" ></script> </head> <body> <input type = "button" onclick = "sayHello()" value = "Say Hello" /> </body> </html>
static/hello.js
function sayHello() { alert("Hello World") }
#Flask Request对象 来自客户端网页的数据作为全局请求对象发送到服务器。为了处理请求数据,应该从Flask模块导入。 Request对象的重要属性如下所列: Form - 它是一个字典对象,包含表单参数及其值的键和值对。 args - 解析查询字符串的内容,它是问号(?)之后的URL的一部分。 Cookies - 保存Cookie名称和值的字典对象。 files - 与上传文件有关的数据。 method - 当前请求方法。
Flask 将表单数据发送到模板
cat Hello_development.py ##主程序
from flask import Flask, render_template, request app = Flask(__name__) @app.route('/') def student(): return render_template('student.html') @app.route('/result',methods = ['POST','GET']) def result(): if request.method == 'POST': result = request.form return render_template('result.html',result = result) if __name__ == '__main__': app.run('0.0.0.0',5000,debug = True)
cat templates/student.html ##脚本
<form action="http://192.168.209.211:5000/result" method="POST"> <p>Name <input type = "text" name = "Name"/></p> <p>Physics <input type = "text" name = "Physics"/></p> <p>Maths <input type = "text" name = "Maths"/></p> <p><input type = "submit" value="submit"/></p> </form>
cat templates/result.html ##模板
<!doctype html> <table border = 1> {% for key, value in result.items() %} <tr> <th>{{key}}</th> <th>{{value}}</th> </tr> {% endfor %} </table>
Flask Cookies
Cookie以文本文件的形式存储在客户端的计算机上。其目的是记住和跟踪与客户使用相关的数据,以获得更好的访问者体验和网站统计信息。 Hello_development.py
from flask import Flask, make_response, request app = Flask(__name__) @app.route('/set_cookies') def set_cookies(): resp = make_response("success") resp.set_cookie("cookie_id_1","009911", max_age=3600) return resp @app.route('/get_cookies') def get_cookies(): cookies_get = request.cookies.get('cookie_id_1') return cookies_get @app.route('/delete_cookies') def delete_cookies(): resp = make_response('del success') resp.delete_cookie('cookie_id_1') return resp if __name__ == '__main__': app.run('0.0.0.0',5000,debug=True)
Flask Sessions(会话)
Session(会话)数据存储在服务器上。会话是客户端登录到服务器并注销服务器的时间间隔。 会话变量使用 cat Hello_development.py
#!/usr/bin/env ptyoh # ~*~ coding: utf-8 ~*~ from flask import Flask, session, redirect, url_for, escape, request app = Flask(__name__) app.secret_key = '9988aabbkkllii' @app.route('/') def index(): if 'username' in session: return "登录用户是:" + session["username"] + "<br><a href='/logout'>点击这里注销登录</a>" return ''' 你暂时没有登录 <br> <a href='/login'>点击这里登录</a> ''' @app.route('/login',methods = ['POST','GET']) def login(): if request.method == 'POST': session["username"] = request.form["username"] ##可以直接当作dict使用 return redirect(url_for('index')) return ''' <form action = '' method = 'POST'> <p>username:<input type='text' name = 'username' <br></p> <p><input type='submit' value = 'submit'</p> </form> ''' @app.route('/logout') def logout(): session.pop('username',None) return redirect(url_for('index')) if __name__ == '__main__': app.run('0.0.0.0',5000,debug = True)
Flask 重定向和错误
重定向 Flask.redirect(location, statuscode, response) 在上述函数中: location参数是应该重定向响应的URL。 statuscode发送到浏览器标头,默认为302。 response参数用于实例化响应。 错误 Flask类具有带有错误代码的abort()函数。
Flask.abort(code) code参数采用以下值之一: 400 - 用于错误请求 401 - 用于未身份验证的 403 - Forbidden 404 - 未找到 406 - 表示不接受 415 - 用于不支持的媒体类型 429 - 请求过多
Hello_development.py
#!/usr/bin/env ptyoh # ~*~ coding: utf-8 ~*~ from flask import Flask, session, redirect, url_for, escape, request,render_template,abort app = Flask(__name__) @app.route('/') def index(): return render_template('log_in.html') @app.route('/login',methods = ['POST','GET']) def login(): if request.method == 'POST': if request.form["username"] == "admin": return redirect(url_for('success'),301) else: abort(401) else: return redirect(url_for('index')) @app.route('/success') def success(): return "login is success" if __name__ == '__main__': app.run('0.0.0.0',5000,debug = True)
templates/log_in.html
<form action="/login" method="post" > <p>username:<input type="text" name="username"/></p> <p><input type="submit" value="submit"/></p> </form>
Flask 消息闪现
一个好的基于 GUI 的应用程序会向用户提供有关交互的反馈。 简单使用: 后端定义flash("login successful!!") 模板获取get_flashed_messages()
Hello_development.py
#!/usr/bin/env ptyoh # ~*~ coding: utf-8 ~*~ from flask import Flask, session, redirect, url_for, escape, request,render_template,abort,flash import os app = Flask(__name__) app.secret_key=os.urandom(32) @app.route('/') def index(): return render_template('index.html') @app.route('/login',methods = ['POST','GET']) def login(): error = None if request.method == 'POST': if request.form['username'] != "admin" or request.form['password'] != "admin": error = "Invalid username or passworld!!!" else: flash("login is successful!!!") return redirect(url_for('index')) return render_template('login.html',error = error) if __name__ == '__main__': app.run('0.0.0.0',5000,debug = True)
templates/index.html
<html> <head> <meta charset="UTF-8"> <title>Index</title> </head> <body> {% with messages = get_flashed_messages() %} {% if messages %} {% for i in messages %} {{i}} {% endfor %} {% endif %} {% endwith %} <p>Do you want to <a href="{{ url_for('login') }}">log in?</a></p> </body> </html>
templates/login.html
<html> <head> <meta charset="UTF-8"> <title>Login</title> </head> <body> <form action="/login" method="post"> <p>username:<input type="text" name="username"/></p> <p>password:<input type="text" name="password"/></p> <p><input type="submit" value="submit"/></p> </form> {% if error %} <p>ERROR:{{error}}</p> {% endif %} </body> </html>
Flask 文件上传
在 Flask 中处理文件上传非常简单。它需要一个 HTML 表单,其 enctype 属性设置为“multipart / form-data”,将文件发布到 URL。URL 处理程序从 request.files[] 对象中提取文件,并将其保存到所需的位置。
Hello_development.py
#!/usr/bin/env ptyoh # ~*~ coding: utf-8 ~*~ from flask import Flask, request,render_template from werkzeug.utils import secure_filename import os app = Flask(__name__) app.config['UPLOAD_FOLDER'] = 'upload/' @app.route('/upload') def upload(): return render_template('upload.html') @app.route('/upload_file',methods = ['POST','GET']) def upload_file(): if request.method == 'POST': f = request.files["file"] f.save(os.path.join(app.config['UPLOAD_FOLDER'],secure_filename(f.filename))) return "upload file is successful!!!" if __name__ == '__main__': app.run('0.0.0.0',5000,debug = True)
templates/upload.html
<html> <head> <meta charset="UTF-8"> <title>file upload</title> </head> <form action="/upload_file" method="post" enctype="multipart/form-data"> <p><input type="file" name="file" accept=".jpg,.png,.zip,.tar.gz"/> <input type="submit" value="submit"/></p> <p>注意:上传的文件名默认不支持中文命名</p> </form> </html>
Flask扩展
Flask通常被称为微框架,因为核心功能包括基于Werkzeug的WSGI和路由以及基于Jinja2的模板引擎。此外,Flask框架还支持cookie和会话,以及JSON,静态文件等Web帮助程序。这不足以开发完整的Web应用程序。Flask扩展为Flask框架提供了可扩展性。 Flask扩展是一个Python模块 重要的Flask扩展: Flask Mail - 为Flask应用程序提供SMTP接口 Flask WTF - 添加WTForms的渲染和验证 Flask SQLAlchemy - 为Flask应用程序添加SQLAlchemy支持 Flask Sijax - Sijax的接口 - Python/jQuery库,使AJAX易于在Web应用程序中使用
Flask扩展之邮件
Flask-Mail扩展使得与任何电子邮件服务器建立简单的接口变得非常容易,属于python模块,可以用pip安装。使用Mail类来配置邮箱和发送邮件,Message类来封装邮件. 测试账号 jkfeko94@163.com br/>使用Mail类来配置邮箱和发送邮件,Message类来封装邮件. 测试账号 jkfeko94@163.com WGPJPPBTONSIQKCE #
Hello_development.py
from flask import Flask from flask_mail import Mail,Message app= Flask(__name__) ##定义邮件配置 app.config['MAIL_SERVER'] = 'smtp.163.com' app.config['MAIL_PORT'] = 465 app.config['MAIL_USERNAME'] = 'jkfeko94@163.com' app.config['MAIL_PASSWORD'] = 'WGPJPPBTONSIQKCE' app.config['MAIL_USE_TLS'] = False app.config['MAIL_USE_SSL'] = True ##创建实例 mail = Mail(app) @app.route('/') def index(): msg = Message('Flask Mail',sender=app.config['MAIL_USERNAME'],recipients=['1025158107@qq.com']) msg.body = "This is a flask mail send test.." mail.send(msg) return 'sent' if __name__ == '__main__': app.run('0.0.0.0',5000,debug=True)
Flask扩展之WTF
WTForms表单:Web应用程序的一个重要方面是为用户提供用户界面的扩展。 如果通过html创建表单:表单元素必须定义两次 - 一次在HTML中,另一次在服务器端脚本中。 用WTF就只创建一次即可。 WTF两大部分 wtforms标准表单字段:如 TextField 表示<input type ='text'> ##HTML表单元素 validators验证器:如validators.DataRequired("不能为空") ##不输入会返回error="不能为空"
forms.py
from flask_wtf import FlaskForm from wtforms import RadioField,TextAreaField,SelectField,IntegerField,SubmitField,StringField from wtforms import validators, ValidationError import email_validator ##创建联系人的类,包括名字,性别,地址,邮箱,年龄,技能语言 ##用到WTF 必须继承FlaskForm类 class ContactForm(FlaskForm): name = StringField('姓名',[validators.DataRequired('姓名不能为空,请输入正常的名字!!!')]) gender = RadioField('性别',choices=[('M','男'),('F','女')]) address = TextAreaField("住址") email = StringField('邮箱',[validators.DataRequired('邮箱不能为空!!'),validators.Email("邮箱格式错误,请输入正确格式")]) age = IntegerField('年龄') language = SelectField('编程语言',choices=[('cpp','C++'),('py','python')]) submit = SubmitField('提交')
Hello_development.py
from flask import Flask,render_template,request,flash from forms import ContactForm import os app = Flask(__name__) app.secret_key = os.urandom(32) @app.route('/contact',methods=['POST','GET']) def contact(): form = ContactForm() #实例化联系人表单 if request.method == 'POST': if form.validate() == False: ##检查表单输入是否有误 flash("输入内容有误") return render_template('contact.html', form=form) else: name = form.name.data ##获取表单值 gender = form.gender.data email = form.email.data age = form.age.data language = form.language.data return str(name) + "<br>" + \ str(gender) + "<br>" +\ str(email) + "<br>" +\ str(age) + "<br>" +\ str(language) + "<br>" +\ "<br> post contact is successful!!!" return render_template('contact.html',form = form) if __name__ == "__main__": app.run('0.0.0.0',5000,debug=True)
templates/contact.html
<html> <head> <meta charset="UTF-8"/> <title>联系人表单填写</title> </head> <body> <h1>联系人表单填写 </h1> {% with msg = get_flashed_messages() %} {% if msg %} {% for i in msg %} {{ i }} {% endfor %} {% endif %} {% endwith %} {% for msg in form.name.errors %} <div>{{ msg }}</div> {% endfor %} {% for msg in form.email.errors %} <div>{{ msg }}</div> {% endfor %} {% for msg in form.age.errors %} <div>{{ msg }}</div> {% endfor %} <form action="/contact" method="post"> <fieldset> <legend>联系人表单填写内容</legend> <!-- 渲染所有隐藏字段,包括跨站请求伪造保护 --> {{ form.hidden_tag() }} <div style=" font-size:20px;font-weight:bold; margin-left: 600px;"> {{ form.name.label }} <br> {{ form.name }} <br> {{ form.gender.label }} {{ form.gender }} <br> {{ form.address.label }} <br> {{ form.address }} <br> {{ form.email.label }} <br> {{ form.email }} <br> {{ form.age.label }} <br> {{ form.age }} <br> {{ form.language.label }} <br> {{ form.language }} <br> {{ form.submit }} </div> </fieldset> </form> </body> </html>
Flask扩展之SQLite3
创建sqlite数据库和表 Create_Sqlite.py
import sqlite3 con = sqlite3.connect('database.db') cur = con.cursor() cur.execute('create table contact (name TEXT, gender TEXT, email TEXT, age TEXT, language TEXT)') con.commit() con.close()
Hello_development.py
from flask import Flask,render_template,request,flash from forms import ContactForm import sqlite3 import os app = Flask(__name__) app.secret_key = os.urandom(32) @app.route('/') def home(): return render_template('home.html') @app.route('/contact',methods=['POST','GET']) def contact(): form = ContactForm() #实例化联系人表单 if request.method == 'POST': if form.validate() == False: ##检查表单输入是否有误 flash("输入内容有误") return render_template('contact.html', form=form) else: try: name = form.name.data gender = form.gender.data email = form.email.data age = form.age.data language = form.language.data with sqlite3.connect("database.db") as con: ##要先手动创建sqlite数据库和表 cur = con.cursor() cont = [(name,gender,email,age,language)] cur.executemany('INSERT INTO contact(name,gender,email,age,language) VALUES (?,?,?,?,?)', cont) con.commit() msg = "Record successfully added." except: con.rollback() #msg = "error record is fail." finally: con.close() return render_template('result.html',msg = msg) return render_template('contact.html',form = form) @app.route('/show') def show(): with sqlite3.connect("database.db") as con: ##要先手动创建sqlite数据库和表 con.row_factory = sqlite3.Row #将设置row_factory为callable sqlite3.Row,将普通元组转换为更有用的对象。 cur = con.cursor() cur.execute('select * from contact') rows = cur.fetchall() return render_template('show.html',rows = rows) if __name__ == "__main__": app.run('0.0.0.0',5000,debug=True)
templates/home.html
<html> <head> <meta charset="UTF-8"> <title>SQLITE3数据库的读写</title> </head> <h1>SQLITE3数据库的读写</h1> <p> <a href="/contact">点击进入联系人信息录入界面</a> </p> <br> <p> <a href="/show">点击进入联系人信息查看界面</a> </p> <body> </body>
templates/contact.html
<html> <head> <meta charset="UTF-8"/> <title>联系人表单填写</title> </head> <body> <h1>联系人表单填写 </h1> {% with msg = get_flashed_messages() %} {% if msg %} {% for i in msg %} {{ i }} {% endfor %} {% endif %} {% endwith %} {% for msg in form.name.errors %} <div>{{ msg }}</div> {% endfor %} {% for msg in form.email.errors %} <div>{{ msg }}</div> {% endfor %} {% for msg in form.age.errors %} <div>{{ msg }}</div> {% endfor %} <form action="/contact" method="post"> <fieldset> <legend>联系人表单填写内容</legend> <!-- 渲染所有隐藏字段,包括跨站请求伪造保护 --> {{ form.hidden_tag() }} <div style=" font-size:20px;font-weight:bold; margin-left: 600px;"> {{ form.name.label }} <br> {{ form.name }} <br> {{ form.gender.label }} {{ form.gender }} <br> {{ form.address.label }} <br> {{ form.address }} <br> {{ form.email.label }} <br> {{ form.email }} <br> {{ form.age.label }} <br> {{ form.age }} <br> {{ form.language.label }} <br> {{ form.language }} <br> {{ form.submit }} <br> <p> <a href="/">点击返回首页</a> </p> </div> </fieldset> </form> </body> </html>
templates/show.html
<html> <head> <meta charset="UTF-8"> <title>联系人信息查看界面</title> </head> <body> <h1>联系人信息查看界面</h1> <table border = 1> <thead> <td>Name</td> <td>gender</td> <td>gender</td> <td>age</td> <td>language</td> </thead> {% for i in rows %} <tr> <td>{{i["name"]}}</td> <td>{{i["gender"]}}</td> <td> {{ i["email"]}}</td> <td>{{i['age']}}</td> <td>{{i['language']}}</td> </tr> {% endfor %} </table> <p><a href="/">Go to home!!</a></p> </body> </html>
templates/result.html
<html> <head> <meta charset="UTF-8"> <title>SQLITE3数据库读写返回状态</title> </head> <h1>SQLITE3数据库读写返回状态</h1> {{ msg }} <br> <p><a href="/">Go to home!!</a></p> <body> </body> </html>
Flask SQLAlchemy
SQLAlchemy,Python工具包是一个强大的ORM,将内容存储在对象的方式 模块安装 SQLAlchemy 1.3版本 Flask-SQLAlchemy 2.4.4版本
templates/home.html
<html> <head> <meta charset="UTF-8"> <title>SQLAlchemy SQL工具包及对象关系映射(ORM)工具</title> </head> <body> <h1>SQLAlchemy SQL工具包及对象关系映射(ORM)工具</h1> <p> <a href="/newstu">点击进入学生信息录入界面</a> </p> <br> <p> <a href="/showstu">点击进入学生信息查看界面</a> </p> </body> </html>
templates/newstu.html
<html> <head> <meta charset="UTF-8"> <title>学生信息录入-Flask SQLAlchemy 使用</title> </head> <h1>学生信息录入-Flask SQLAlchemy 使用</h1> {% for msg in get_flashed_messages() %} {{ msg }} {% endfor %} <form action="{{ url_for('stu') }}" method="post"> <p>姓名:<input type="text" name="name"></p> <p>城市:<input type="text" name="city"></p> <p>地址:<textarea name="addr"></textarea></p> <p>手机号码:<input type="text" name="phone"></p> <p><input type="submit" value="submit"></p> </form> <a href="/">返回主页</a> </html>
templates/showstu.html
<html> <head> <meta charset="UTF-8"> <title>学生信息查询结果</title> </head> <h1>学生信息查询结果</h1> <table border = 1> <thead> <tr> <th>姓名</th> <th>城市</th> <th>地址</th> <th>手机号码</th> </tr> </thead> <tbody> {% for stu in students %} <tr> <td>{{stu.name}}</td> <td>{{stu.city}}</td> <td>{{stu.addr}}</td> <td>{{stu.phone}}</td> </tr> {% endfor %} </tbody> </table> <a href="/">返回主页</a> </html>
Hello_development.py
from flask import Flask,render_template,request,flash import os,pymysql from flask_sqlalchemy import SQLAlchemy app = Flask(__name__) app.secret_key = os.urandom(32) # 设置连接sqlite3数据库的URL # app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///stu.db' # app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False # 设置连接mysql数据库的URL app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+pymysql://root:123456@192.168.5.157:3306/test' # 设置每次请求结束后会自动提交数据库的改动 app.config['SQLALCHEMY_COMMIT_ON_TEARDOWN'] = True app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True # 查询时显示原始SQL语句 #app.config['SQLALCHEMY_ECHO'] = True db = SQLAlchemy(app) ##实例化 class Students(db.Model): ##继承父类Model __tablename__ = 'students' id = db.Column('student_id', db.Integer, primary_key = True) name = db.Column(db.String(100)) city = db.Column(db.String(200)) addr = db.Column(db.String(100)) phone = db.Column(db.String(200)) def __init__(self, name, city, addr, phone): self.name = name self.city = city self.addr = addr self.phone = phone @app.route('/') def home(): #db.create_all() ##可以用这个来创建表结构一般创建完就注释的 return render_template('home.html') @app.route('/newstu') def newstu(): return render_template('newstu.html') @app.route('/showstu') def showstu(): return render_template('showstu.html',students = Students.query.all()) @app.route('/stu',methods=['POST']) def stu(): if request.method == 'POST': if not request.form['name'] or not request.form['city'] or not request.form['addr'] or not request.form['phone']: flash('Input cannot be empty') else: student = Students(request.form['name'],request.form['city'],request.form['addr'],request.form['phone']) db.session.add(student) db.session.commit() flash("Record was successfully added") return render_template('newstu.html') if __name__ == "__main__": app.run('0.0.0.0',5000,debug=True)
Flask AJAX
AJAX不是JavaScript的规范,它只是一个哥们“发明”的缩写:Asynchronous JavaScript and XML,意思就是用JavaScript执行异步网络请求。 如果仔细观察一个Form的提交,你就会发现,一旦用户点击“Submit”按钮,表单开始提交,浏览器就会刷新页面,然后在新页面里告诉你操作是成功了还是失败了。如果不幸由于网络太慢或者其他原因,就会得到一个404页面。这就是Web的运作原理:一次HTTP请求对应一个页面。 如果要让用户留在当前页面中,同时发出新的HTTP请求,就必须用JavaScript发送这个新请求,接收到数据后,再用JavaScript更新页面,这样一来,用户就感觉自己仍然停留在当前页面,但是数据却可以不断地更新。 最早大规模使用AJAX的就是Gmail,Gmail的页面在首次加载后,剩下的所有数据都依赖于AJAX来更新。 用JavaScript写一个完整的AJAX代码并不复杂,但是需要注意:AJAX请求是异步执行的,也就是说,要通过回调函数获得响应
templates/ajax.html
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>ajax</title> <script src="https://cdn.staticfile.org/jquery/1.10.2/jquery.min.js"></script> <body> <form id="my_form"> name: <input name="name" type="text"/><br> age: <input name="age" type="text"/><br> <input id="my_button" type="button" value="button"/> </form> <script> $("#my_button").click(function () { $.ajax({ url:"/test_post", type:"POST", dataType:"json", async:true, data:$("#my_form").serialize(), success:function (result) { // 回调函数,处理app.py返回的结果 alert(result['ok']) }, error:function (XMLHttpRequest,textStatus,errorThrown) { alert(XMLHttpRequest.status) alert(XMLHttpRequest.readyState) alert(textStatus) } }); }) </script> </body> </html>
Hello_development.py
import os,json from flask import Flask,render_template,jsonify,request,redirect,url_for app = Flask(__name__) @app.route('/') def home(): return render_template('ajax.html') @app.route('/test_post',methods=['POST','GET']) def test_post(): if request.method == 'POST': name=request.form.get('name') age=request.form.get('age') print(name,age) return jsonify({'ok': True}) return redirect(url_for('home')) if __name__ == "__main__": app.run('0.0.0.0',5000,debug=True)
以上全部代码均实操通过,时间20210322
查看更多关于Flask框架基础全面教程(2021实战版)的详细内容...