• flask入门(四)前后端数据传输


    1、flask后端接收来自前端的数据

    1)如果前端提交的方法为POST

    后端接收时的代码:

    xx=request.form.get('xx');
    xx=request.form['xx']
    
    • 1
    • 2

    2)如果前段提交的方法是GET

    xx=request.args.get(xx)
    
    • 1

    2、flask后端向前端传数据

    传送单个数据

    return render_template('html文件',xx='xx')
    
    • 1

    传送多个数据:先把数据写进字典,字典整体进行传输

    return render_template('html文件',xx='字典变量')
    
    • 1

    3、案例

    目录结构:
    在这里插入图片描述
    index.py文件:

    # --*-- coding:utf-8 --*--
    # @Author : 一只楚楚猫
    # @File : index.py
    # @Software : PyCharm
    
    from flask import *
    from sentence_transformers import SentenceTransformer
    import torch.nn as nn
    import torch
    import torch.nn.functional as F
    
    model = SentenceTransformer(r'E:\楚楚猫\code\python\01design\01creativity\01distance\all-MiniLM-L6-v2')
    
    app = Flask(__name__)
    
    result = dict()
    result["results"] = ""
    
    
    @app.route('/', methods=('GET', 'POST'))
    def index():
        global result
        if request.method == 'POST':
            step1 = request.form.get("step1")
            step2 = request.form.get("step2")
            step3 = request.form.get("step3")
            step4 = request.form.get("step4")
    
            # 用户输入的内容
            sentences = [step1, step2, step3, step4]
    
            results = list()
    
            # 384维
            embeddings = torch.FloatTensor(model.encode(sentences))
    
            # p=2就是计算欧氏距离,p=1就是曼哈顿距离
            euclidean_distance = nn.PairwiseDistance(p=2)
    
            for i in range(0, embeddings.size()[0]):
                for j in range(i + 1, embeddings.size()[0]):
                    cosine_similarity = round(F.cosine_similarity(embeddings[i], embeddings[j], dim=0).item(), 4)
                    distance = round(euclidean_distance(embeddings[i], embeddings[j]).item(), 4)
    
                    results.append(
                        f"step{i + 1} & step{j + 1}的相关性:{cosine_similarity}       step{i + 1} & step{j + 1}的距离:{distance}")
    
                    print(
                        f"step{i + 1} & step{j + 1}之间的相关性:{cosine_similarity}step{i + 1} & step{j + 1}之间的距离:{distance}")
    
            result["results"] = results
    
            return render_template('hello.html', result=result)
    
        return render_template('hello.html', result=result)
    
    
    if __name__ == '__main__':
        app.run(port=11252)
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60

    hello.html文件:

    DOCTYPE html>
    <html lang="en">
    <meta charset="utf-8">
    <head>
        <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no"/>
        <meta http-equiv="content-type" content="text/html;charset=utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
        <title>欢迎来到我的世界title>
    
        <link href="../static/css/style.css" rel="stylesheet" type="text/css">
    head>
    
    <div id="container">
        <div id="output">
            <div class="containerT">
                <h1>Yimoh1>
                <form class="form" id="entry_form" method="post">
                    <h2><input type="text" name="step1" style="height:30px">h2><br>
                    <h2><input type="text" name="step2" style="height:30px">h2><br>
                    <h2><input type="text" name="step3" style="height:30px">h2><br>
                    <h2><input type="text" name="step4" style="height:30px">h2><br>
                    <center>
                        <button><h3>Click me!(๑•̀ㅂ•́)و✧h3>button>
                    center>
    
                    {{result.results}}
                form>
            div>
        div>
    div>
    
    
    body>
    html>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34

    上面涉及到的sentence_transformers模块来自论文:《Sentence-BERT: Sentence Embeddings using Siamese BERT-Networks》,使用孪生网络(Siamse Network)将两个文本映射到特征空间得到特征向量(384维)

    参考文献

    1、flask 前端(html)与后端(python)相互传数据:https://www.cnblogs.com/zzai/p/html_dataStream.html
    2、如何从Python发布数据并进入Flask前端:https://www.cnpython.com/qa/1513860

  • 相关阅读:
    深入浅出 JavaScript 模块化
    Pandas分组聚合_Python数据分析与可视化
    不是单例的单例——巧用ClassLoader
    pytest文档81 - 如何管理Captured logging日志
    力扣数组2(C++)
    kubelet如何避免节点频繁切换“资源不足”和“资源充足”状态?
    猿创征文|分布式事务常见解决方案
    每日三题 8.12
    关于AtomSeg程序移植问题(持续更新)
    源码分析:如何开发规则链
  • 原文地址:https://blog.csdn.net/julac/article/details/133965741