falsk 是基于Browser/Serve端开发, S端是服务器,B端是就是浏览器的前端。flask 做的很多工作就是服务器端。
flask web 后端:
第一:最简单的demo1.py
from flask import Flask
app = Flask(__name__)
@app.route('/')
def hello_world():
return 'Hello World!'
if __name__ == '__main__':
app.run(debug=True, # 可以在程序运行时,对程序进行调试
port=7000, # 改变端口号,而不是默认的5000
host='0.0.0.0',)
app.route('/'):代表路由,也就是通常我们说的网址。app 是Flask 对象的一个实例。
def hello_world():
app.run() 代表程序正式运行。
第二:request 和respond
用户在浏览器输入网址,就是发送请求的过程,就是request ,而服务器反馈客户请求的过程,就是response.
2.1 request:
上下文(context):
一直看到这个东西,却不知道这是个什么玩意,难以理解。简单说一下什么是请求上下文:我们客户端发送了请求给服务器,那么这个request对象就发送过去了。服务器那边就接收到了这个request,那么就可以使用一系列方法读取这个request对象中的内容(比如使用request.method 显示它用GET还是POST方式提交的,使用request.path 查看它请求的路径是什么)。而我们如果浏览器没有发送请求,那么在服务器端,你去使用request.method这些方法就会报错,因为这些方法需要客户端发送过来请求才能执行,也就是说,某些方法的执行需要一系列操作作为基础,需要前因后果这种关系(说的比较抽象),而这种前因后果就可以通俗理解为上下文。
req1.py
# -*- coding: utf-8 -*-
#!/usr/bin/python
# coding: utf-8
from flask import Flask,jsonify,render_template,request
import json
app = Flask(__name__)#实例化app对象
@app.route('/req/')
def req():
#information = request.method #方法:查询使用的方法
print("method:",request.method) #获取访问方式 GET
print("url:",request.url) #获取url http://127.0.0.1:5000/req?id=1&name=wl
print("cookies:",request.cookies) #获取cookies {}
print("path:",request.path) # 获取访问路径 /req
print("args:",request.args) #获取url传过来的值 ImmutableMultiDict([('id', '1'), ('name', 'wl')])
print("id:",request.args.get("id")) #get获取id 1
print("name:",request.args["name"]) # 索引获取name wl
print(request.args.to_dict()) # 获取到一个字典 {'id': '1', 'name': 'wl'}
information= request.args.get("name","未找到") # 传递参数
return information
if __name__ == '__main__':
app.run(debug=True)
当我们输入三个不同网址时,效果是不同的:原因就是?代表的是传入参数。
http://127.0.0.1:5000/req/?name=ki||ji
http://127.0.0.1:5000/req/?name=ki&ji
http://127.0.0.1:5000/req/name=ki
通过上面的例子我们知道了request 的意义。但是更重要的我们需要实践,利用request来传递浏览器端数据,然后在服务器端响应需求。
request 传递前端你的数据:两种形式,一是通过form表单,二是传输文件。
第一种情况传递表单:
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>主页面</title>
</head>
<body>
<h2>主页面</h2>
<hr />
<h4>Donot aim for your success if you really want it. Just stick to do what you love and believe in.</h4>
</body>
</html>
login.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>登录页面</title>
</head>
<body>
<h2>登录页面</h2>
<hr />
<div>
<form action="/login/" method="post"> #前端的数据传输是post
<div>
<label for="email">邮箱:</label><input type="text" id="email" name="email" />
</div>
<div>
<label for="password">密码:</label><input type="password" id="password" name="password" />
</div>
<div>
<button type="submit">登录</button>
</div>
</form>
</div>
</body>
</html>
主程序:
# -*- coding: utf-8 -*-
#!/usr/bin/python
# coding: utf-8
from flask import Flask
from flask import request
from flask import render_template
from werkzeug.datastructures import ImmutableMultiDict
app = Flask(__name__)
@app.route('/')
def index():
return render_template('index.html')
@app.route('/login/', methods=['GET', 'POST'])
def login():
print(request.method) # 输出是get
if request.method == 'POST':
print('POST请求')
formData = request.form
print(type(formData))
print(formData)
email = formData.get('email', 'null')
password = formData['password']
print("email:",email,"password:",password,type(email),type(password))
return render_template('index.html')
if request.method == 'GET':
print('GET请求')
return render_template('login.html')
print(app.url_map)
if __name__ == '__main__':
app.run(debug=True)
有一个有趣的现象:
login.html 传输数据是post ,app.py传输数据是get.
第二种:request 传递文件
hello.py
# -*- coding: utf-8 -*-
#!/usr/bin/python
# coding: utf-8
from flask import Flask, render_template, request
from werkzeug.utils import secure_filename
app = Flask(__name__)
@app.route('/')
def index():
return render_template('upload.html')
@app.route('/upload', methods=['GET', 'POST'])
def upload():
if request.method == 'POST':
f = request.files['myfile']
f.save(secure_filename(f.filename))
return '上传文件成功。'
if __name__ == '__main__':
app.run(debug=True)
upoad.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>上传文件</title>
</head>
<body>
<form action="/upload" method="POST"
enctype="multipart/form-data">
<input type="file" name="myfile"><br><br>
<input type="submit" name="开始上传">
</form>
</body>
</html>
secret_key设置成os.urandom(24)这样的写法再项目中不合适,因为没次启动服务器这个值都会改变,所以所有保存的session都失效。现在只是学习阶段,所以就可以随机产生。
参考:
Flask中session的用法
从零开始学Python Flask Web(四)--Flask Request请求
Flask10 登录模块、表单框架、表单渲染、表单验证、bookie、请求之前钩子、g对象、编写装饰器