python flask笔记

官方文档https://flask.net.cn/index.html

安装

windows

  • pip install flask

linux

pip install Flask -i http://pypi.douban.com/simple/
  • ModuleNotFoundError: No module named ‘distutils.cmd’
sudo apt-get install python3-distutils

直接运行helloworld

from flask import Flask
app = Flask(__name__)

@app.route('/')
def hello_world():
    return 'Hello, World!'
app.run() # 访问 http://127.0.0.1:5000/ 即可

路由

简单路由

  • 不传参数
from flask import Flask
app = Flask(__name__)

@app.route('/hello')
def hello():
    return 'Hello, World'
app.run() # 访问 http://127.0.0.1:5000/hello 即可
  • 传参数
from flask import Flask
app = Flask(__name__)

@app.route('/hello/<id>')
def hello(id):
    return 'Hello, World'+id
app.run() # 访问 http://127.0.0.1:5000/hello/1 即可,如果调试失败,先关闭后台的python程序

只回应get或post的请求的路由

from flask import request

@app.route('/login', methods=['GET', 'POST'])
def login():
    if request.method == 'POST':
        return do_the_login()
    else:
        return show_the_login_form()

重定向

from flask import abort, redirect, url_for, Flask,render_template
@app.route('/hello', methods=['POST', 'GET'])
def hello():
    return render_template('hello.html', error=error)# hello.html为简单的前端界面
    
@app.route('/')
def index():
    return redirect(url_for('hello'))# redirect('https://www.baidu.com')

渲染前端

from flask import Flask,render_template
@app.route('/hello', methods=['POST', 'GET'])
def hello():
    return render_template('hello.html', error=error)# hello.html为简单的前端界面
  • Flask应用一般在templates文件夹中查找HTML文件,且templates文件夹要与运行py文件在同一层级。
  • 或者在app初始化时指定html的文件路径app = Flask(name, template_folder=‘templates’, static_folder=““,static_url_path=””)

向前端返回json数据

from flask import abort, redirect, url_for, Flask,render_template,make_response,json
app = Flask(__name__)
@app.route("/me")
def me_api():
    user = {
        "username": user.username,
        "theme": user.theme,
        "image": url_for("user_image", filename=user.image),
    }
    return make_response(json.dumps(data))
app.run()    
  • 直接return也行
@app.route("/me")
def me_api():
    user = get_current_user()
    return {
        "username": user.username,
        "theme": user.theme,
        "image": url_for("user_image", filename=user.image),
    }

解析前端post数据

form post

    <form action="http://127.0.0.1:5000/upload" enctype='multipart/form-data' method='POST'>
        <input type="submit" value="上传" class="button-new" style="margin-top:15px;"/>
        <p>提交:<input type="text" name="username" ></p>
        <p>密码:<input type="password" name="password" ></p>
    </form>
@app.route('/upload', methods=['POST', 'GET'])
def upload():
    if request.method == 'POST':
        user_info = request.form.to_dict()
        if user_info.get("username") == "admin" and user_info.get("password") == '123456':
            return render_template('upload.html')

解析前端post的json数据

  • params = request.form or request.json
  • params.get
@app.route('/upload', methods=['POST', 'GET'])
def upload():
    if request.method == 'POST':
        content_type = request.headers.get('Content-Type')
        if content_type and 'application/json' in content_type:
            # 处理json数据
            user_info = request.get_json(force=True)
            print(user_info)
        else:
            user_info = request.form.to_dict()
            print(user_info)

提交測試

multiprocessing post
import os
from multiprocessing import Process
import random
import time
def foo():
    start = time.time()
    os.system('test.bat')
    end = time.time()
    print(end-start)

if __name__ == '__main__':
    for num in range(10):
        Process(target=foo, args=()).start()

文件处理

前端向flask传递图片

@app.route('/upload', methods=['POST', 'GET'])
def upload():
    if request.method == 'POST':
        # 通过file标签获取文件
        f = request.files['file']
        if not (f and allowed_file(f.filename)):
            return jsonify({"error": 1001, "msg": "图片类型:png、PNG、jpg、JPG、bmp"})
		# 一定要先创建该文件夹,不然会提示没有该路径
        basepath = os.path.dirname(__file__)
        upload_path = os.path.join(basepath, 'static/images', secure_filename(f.filename))
        f.save(upload_path)# 保存文件
        return render_template('upload_ok.html')# 返回上传成功界面
    
    return render_template('upload.html')# 否则返回上传界面
  • 前端代码
<body>
    <form action="http://10.1.12.47:5000/upload" enctype='multipart/form-data' method='POST'>
        <input type="file" name="file" style="margin-top:20px;"/>
        <input type="submit" value="上传" class="button-new" style="margin-top:15px;"/>
    </form>
</body>

CG

相关开源项目

Simple flask example for quick prototypes and small applications
🐍 📊 📈 Build complex dashboards without any front-end code. Use your own endpoints. JSON config only. Ready to go.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值