Python和Flask,从服务器发送和接收数据。

huangapple go评论67阅读模式
英文:

Python & Flask, send and receive data from server

问题

I am trying to do a practice, which consists of sending some data from an html form, receive it, execute a function and return it to the html.

From the index.html file, I have declared a form with the <form> label.
With the action attribute, I pass to the URL /products/mouse the name of a product, which is defined in a dictionary inside a file with the name products.py.

This value is collected by the index() function, calls the getProduct() function and passes it the variable product_nombre which contains the value mouse sent from index.html.

getProduct, goes through the products dictionary looking for a product that matches the name of the product sent by html, in this case, mouse.

The question is that in the index.html, it indicates to me:

Producto no encontrado - Product not found when the product exists

Why does this happen?

this is the content of my main app.py file:

from flask import Flask, jsonify, request, render_template, redirect, url_for
from products import products

app = Flask(__name__)

@app.route('/')
def index():
    product_nombre = request.args.get('product_nombre', 'punto control')
    data = getProduct(product_nombre)
    return render_template('index.html', data=data)

@app.route('/products/<string:product_nombre>', methods=['GET'])
def getProduct(product_nombre):
    for product in products:
        if product['nombre'] == product_nombre:
            return product
    return "Producto no encontrado"

if __name__ == "__main__":
    app.run(debug=True)

this is the contents of my index.html file:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <form action="/products/mouse" method="get">
        <h2 id>Hola mundo</h2>
        <h4> {{ data }}</h4>
    </form>
</body>
</html>

this is the content of the file products.py

products = [ 
    {"nombre": "laptop",
    "precio": 800,
    "cantidad": 4},
    {"nombre": "mouse",
    "precio": 40,
    "cantidad": 10},
    {"nombre": "monitor",
    "precio": 250,
    "cantidad": 3}
    ]
英文:

I am trying to do a practice, which consists of sending some data from an html form, receive it, execute a function and return it to the html.

From the index.html file, I have declared a form with the &lt;form&gt; label.
With the action attribute, I pass to the URL /products/mouse the name of a product, which is defined in a dictionary inside a file with the name products.py.

This value is collected by the index() function, calls the getProduct() function and passes it the variable product_nombre which contains the value mouse sent from index.html.

getProduct, goes through the products dictionary looking for a product that matches the name of the product sent by html, in this case, mouse.

The question is that in the index.html, it indicates to me:

>Producto no encontrado - Product not found when the product exists

Why does this happen?

this is the content of my main app.py file:

from flask import Flask, jsonify, request, render_template, redirect, url_for
from products import products

app = Flask(__name__)

@app.route(&#39;/&#39;)
def index():
    product_nombre = request.args.get(&#39;product_nombre&#39;, &#39;punto control&#39;)
    data = getProduct(product_nombre)
    return render_template(&#39;index.html&#39;, data=data)

@app.route(&#39;/products/&lt;string:product_nombre&gt;&#39;, methods=[&#39;GET&#39;])
def getProduct(product_nombre):
    for product in products:
        if product[&#39;nombre&#39;] == product_nombre:
            return product
    return &quot;Producto no encontrado&quot;

if __name__ == &quot;__main__&quot;:
    app.run(debug=True)

this is the contents of my index.html file:

&lt;!DOCTYPE html&gt;
&lt;html lang=&quot;en&quot;&gt;
&lt;head&gt;
    &lt;meta charset=&quot;UTF-8&quot;&gt;
    &lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1.0&quot;&gt;
    &lt;title&gt;Document&lt;/title&gt;
&lt;/head&gt;
&lt;body&gt;
    &lt;form action=&quot;/products/mouse&quot; method=&quot;get&quot;&gt;
        &lt;h2 id=&gt;Hola mundo&lt;/h2&gt;
        &lt;h4&gt; {{ data }}&lt;/h4&gt;
    &lt;/form&gt;
&lt;/body&gt;
&lt;/html&gt;

this is the content of the file products.py

products = [ 
    {&quot;nombre&quot;: &quot;laptop&quot;,
    &quot;precio&quot;: 800,
    &quot;cantidad&quot;: 4},
    {&quot;nombre&quot;: &quot;mouse&quot;,
    &quot;precio&quot;: 40,
    &quot;cantidad&quot;: 10},
    {&quot;nombre&quot;: &quot;monitor&quot;,
    &quot;precio&quot;: 250,
    &quot;cantidad&quot;: 3}
    ]

答案1

得分: 0

在index.html中,它对我表示:

Producto no encontrado

我理解这是发生在 @app.route('/'),对吗?那么,在那里的流程是什么?

product_nombre = request.args.get('product_nombre', 'punto control')

这获取了一个 请求参数,即URL查询参数。如果只是访问 localhost:5000/(或其他什么),那么就没有参数。所以 product_nombre 将获取默认值 'punto control'。嗯,然后 getProduct(product_nombre) 当然不会匹配任何东西,因为没有产品叫做 "punto control",所以你会得到默认的返回值 "Producto no encontrado"。

英文:

> in the index.html, it indicates to me:
>
> > Producto no encontrado

I take this to mean that it happens in @app.route(&#39;/&#39;), right? Well, then what's the flow there?

> product_nombre = request.args.get('product_nombre', 'punto control')

This gets a request argument, i.e. URL query parameters. If you just visit localhost:5000/ (or whatever), then there are no arguments. So product_nombre will get the default value of &#39;punto control&#39;. Well, then getProduct(product_nombre) of course doesn't match anything, because there's no product "punto control", so you get the default return &quot;Producto no encontrado&quot;.

huangapple
  • 本文由 发表于 2023年7月13日 19:15:54
  • 转载请务必保留本文链接:https://go.coder-hub.com/76678746.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定