Flask中的Request、Response

Flask 中的Response

  • 1、return "helloword"
from flask import Flask
# 实例化Flask对象 app
app = Flask(__name__)
@app.route('/index')
# 视图函数
def index():
	return 'helloword'
  • 2 render_template("html文件")
from flask import Flask
from flask import render_template

@app.route('/home')
def home():
	# 模板存放路径
    # 创建 templates文件夹;右键文件夹 ---》Mark Directory as --->templates ---jinja2
	return render_template('home.html')
# 启动服务
app.run()
  • 3、redirect("/home")

    • ResponseHeaders 中加入了一个 Location:http://url # 实现重定向
    • 302 http status
    • 4xx 错误 客户端
    • 5xx 错误 服务端
    from flask import Flask,render_template,redirect
    # 实例化Flask对象 app
    app = Flask(__name__)
    
    # app中的route装饰器  路由
    @app.route('/index')
    # 视图函数
    def index():
    	return 'helloword'
    @app.route('/home')
    def home():
    	# 模板存放路径
    	return render_template('home.html')
    @app.route("/re")
    def re():
        # 重定向
    	return redirect("/home")
    # 启动服务
    app.run()
    
    Flask 特殊返回值
  • 4、send_file('文件路径') 返回文件

    • 打开文件并返回文件内容;自动识别文件类型,并且在浏览器自动加上ResponseHeaders并且加入Content-Type:文件类型,是可以被客户端识别的文件类型;不能识别的文件类型 比如 .exe文件 会下载处理 - -浏览器会下载

      x-ms x:二进制 ; ms 微软

from flask import Flask, send_file
@app.route('/get_file')
def get_file():
    # 返回helloword.py里的内容  Content-Type: text/plain; charset=utf-8
	return send_file('helloword.py')
	# 返回图片  Content-Type: image/jpeg
	return send_file('1.jpg')
	# 返回MP4 或 MP3   Content-Type: voide/mp4
    return send_file('2.mp4')
	# 下载 这个exe文件  Content-Type: application/x-msdownload
	return send_file('3.exe')
# 启动服务
app.run()
  • 5、jsonify('字符串或数据类型') 返回标准格式的Json字符串

    • Content-Type:application/json

    • # 比如Flask更新了  1.1.1
      # return d  # 暂时不建议使用,兼容性
      # 直接返回dict时  本质上在执行jsonify(d)
      
    • API接口

    • 序列化json字符串

    • 编写ResponseHeaders 加入Conent-Type:application/json

from flask import Flask, jsonify

# 实例化Flask对象 app
app = Flask(__name__)
@app.route('/get_json')
def get_json():
	dic = {
		"name": "anwen"
	}
	# Content-Type:application/json
	return jsonify(d)
	# 比如Flask更新了  1.1.1
	# return dic  # 暂时不建议使用,兼容性;直接返回dic时  本质上在执行jsonify(d)
# 启动服务
app.run()

Flask 中的request

# -*- coding: utf-8 -*-
# @Time    : 2019/9/24 11:07
# @Author  : AnWen
import os

from flask import Flask, render_template, request, redirect

app = Flask(__name__)
app.debug = True


# 报错 405 Method Not Allowed
# methods=['GET', 'POST'] 添加路由的装饰器允许请求方式,覆盖
@app.route('/login', methods=['GET', 'POST'])
def login():
	# request.method 获取请求方式
	if request.method == 'GET':
		# 在Django request.GET 取出 URL 中的参数
		# 在Flask 获取URL 中的参数
		# print(request.url) # 请求地址 http://127.0.0.1:9999/login?id=wen
		# print(request.url_charset) # URL 编码方式 utf-8
		# print(request.url_root) # 请求地址 完整请求地址 host http://127.0.0.1:9999/
		# print(request.url_rule) # 请求路由地址  /login
		# print(request.values.to_dict())  # 接收所有(GET,POST)请求中的数据,包含了 URL 和 FormData 中的数据 {'id': 'wen'}
		# print(request.args.get("id"))  # 获取URL中的数据 字符串 wen
		return render_template('login.html')
	if request.method == 'POST':
		# request.form获取 FormData中的数据
		# print(request.form)  # ImmutableMultiDict([('username', '123')])
		# print(request.form.get('username'))  # 123
		# print(request.form.to_dict())  # {'username': '123'}

		# request.files 所有文件类型全部放在这里  包括二进制 音频视频
		# print(request.files.get("myfile"))  # 文件对象<FileStorage: 'Flask day01.md' ('application/octet-stream')>
		# my_file = request.files.get('myfile')
		# # my_file.save('bf.jpg')  # 当前目录下会保存一个bf.jpg
		# new_file = os.path.join('img',my_file.filename)
		# my_file.save(new_file)  # 保存原文件到文件夹中

		# 获取其他数据
		# request.headers
		# request.cookies
		# request.path == request.url_rule
		# request.host == "127.0.0.1:9527"
		# request.host_url == "http://127.0.0.1:9527/"

		# 特殊提交方式数据获取
		# Content-Type:application/json
		# request.json 获取Content-Type:application/json时提交的数据
		# Content-Type 无法被识别 或 不包含Form字眼
		# request.data 获取 原始请求体中的数据 b""

		return '200 ok'
	# return redirect('/')

@app.route('/')
def index():
	return render_template('index.html')

if __name__ == '__main__':
	app.run("0.0.0.0", 9999)
原文地址:https://www.cnblogs.com/an-wen/p/11582219.html