Hướng dẫn passing value from html to python flask without form - chuyển giá trị từ html sang bình python mà không có biểu mẫu

Bạn cần sửa đổi

$(document).ready(function(){
  $('.qtemp').on('click',function(){
    var layout = $(this).data('rep');
    $.ajax({
      url: "/update_layout",
      type: "get",
      data: {layout: layout},
      success: function(response) {
        window.location.replace('/workstation');
      },
    });     
  });
});
6 của mình để đảm bảo rằng bạn đang nhận được kết quả
$(document).ready(function(){
  $('.qtemp').on('click',function(){
    var layout = $(this).data('rep');
    $.ajax({
      url: "/update_layout",
      type: "get",
      data: {layout: layout},
      success: function(response) {
        window.location.replace('/workstation');
      },
    });     
  });
});
7ified từ tuyến Python. Ngoài ra, để lưu trữ dữ liệu được trả về từ cuộc gọi AJAX, bạn phải truy cập các giá trị bằng tên khóa bằng cách sử dụng
$(document).ready(function(){
  $('.qtemp').on('click',function(){
    var layout = $(this).data('rep');
    $.ajax({
      url: "/update_layout",
      type: "get",
      data: {layout: layout},
      success: function(response) {
        window.location.replace('/workstation');
      },
    });     
  });
});
8:

Trong

$(document).ready(function(){
  $('.qtemp').on('click',function(){
    var layout = $(this).data('rep');
    $.ajax({
      url: "/update_layout",
      type: "get",
      data: {layout: layout},
      success: function(response) {
        window.location.replace('/workstation');
      },
    });     
  });
});
9:

$(document).ready(function(){
   $('.qtemp').on('click',function(){
    var layout = $(this).data('rep');
     $.ajax({
      url: "/workstation",
      type: "get",
      data: {layout: layout},
      success: function(response) {
        var new_html = response.html;
      },
     });     
  });
});

Trong

import string, random

app.secret_key = ''.join(random.choice(string.printable) for _ in range(20))
#secret_key needed for session implementation

@app.route("/update_layout")
def update_layout():
  flask.session['layout'] = flask.request.args.get('layout')
  return flask.jsonify({'success':'True'})

@app.route('/workstation', methods=['GET'])
def workstation():
  return flask.render_template('station.html',target = flask.session['layout'])
0:

@app.route('/workstation')
def workstation():
  layout = flask.request.args.get('layout')
  return flask.jsonify({'html':flask.render_template('station.html',target=layout)})

Chỉnh sửa: Bạn có thể lưu trữ giá trị được thu thập từ yêu cầu

$(document).ready(function(){
  $('.qtemp').on('click',function(){
    var layout = $(this).data('rep');
    $.ajax({
      url: "/update_layout",
      type: "get",
      data: {layout: layout},
      success: function(response) {
        window.location.replace('/workstation');
      },
    });     
  });
});
6 trong
import string, random

app.secret_key = ''.join(random.choice(string.printable) for _ in range(20))
#secret_key needed for session implementation

@app.route("/update_layout")
def update_layout():
  flask.session['layout'] = flask.request.args.get('layout')
  return flask.jsonify({'success':'True'})

@app.route('/workstation', methods=['GET'])
def workstation():
  return flask.render_template('station.html',target = flask.session['layout'])
2 và chuyển hướng đến trang mong muốn. Để làm như vậy, hãy tạo một tuyến đường bổ sung để tiết kiệm giá trị và sau đó sử dụng
import string, random

app.secret_key = ''.join(random.choice(string.printable) for _ in range(20))
#secret_key needed for session implementation

@app.route("/update_layout")
def update_layout():
  flask.session['layout'] = flask.request.args.get('layout')
  return flask.jsonify({'success':'True'})

@app.route('/workstation', methods=['GET'])
def workstation():
  return flask.render_template('station.html',target = flask.session['layout'])
3 trong phần thân của hàm
$(document).ready(function(){
  $('.qtemp').on('click',function(){
    var layout = $(this).data('rep');
    $.ajax({
      url: "/update_layout",
      type: "get",
      data: {layout: layout},
      success: function(response) {
        window.location.replace('/workstation');
      },
    });     
  });
});
6
import string, random

app.secret_key = ''.join(random.choice(string.printable) for _ in range(20))
#secret_key needed for session implementation

@app.route("/update_layout")
def update_layout():
  flask.session['layout'] = flask.request.args.get('layout')
  return flask.jsonify({'success':'True'})

@app.route('/workstation', methods=['GET'])
def workstation():
  return flask.render_template('station.html',target = flask.session['layout'])
5:

Trong

$(document).ready(function(){
  $('.qtemp').on('click',function(){
    var layout = $(this).data('rep');
    $.ajax({
      url: "/update_layout",
      type: "get",
      data: {layout: layout},
      success: function(response) {
        window.location.replace('/workstation');
      },
    });     
  });
});
9:

$(document).ready(function(){
  $('.qtemp').on('click',function(){
    var layout = $(this).data('rep');
    $.ajax({
      url: "/update_layout",
      type: "get",
      data: {layout: layout},
      success: function(response) {
        window.location.replace('/workstation');
      },
    });     
  });
});

Trong

import string, random

app.secret_key = ''.join(random.choice(string.printable) for _ in range(20))
#secret_key needed for session implementation

@app.route("/update_layout")
def update_layout():
  flask.session['layout'] = flask.request.args.get('layout')
  return flask.jsonify({'success':'True'})

@app.route('/workstation', methods=['GET'])
def workstation():
  return flask.render_template('station.html',target = flask.session['layout'])
0:

import string, random

app.secret_key = ''.join(random.choice(string.printable) for _ in range(20))
#secret_key needed for session implementation

@app.route("/update_layout")
def update_layout():
  flask.session['layout'] = flask.request.args.get('layout')
  return flask.jsonify({'success':'True'})

@app.route('/workstation', methods=['GET'])
def workstation():
  return flask.render_template('station.html',target = flask.session['layout'])

  1. Nhà
  2. Phát triển các ứng dụng web với Python và bình
  3. Phần 1
  4. Các hình thức

Phần 1, Chương 6

Chương này xem xét cách tạo các biểu mẫu để có được dữ liệu đầu vào của người dùng.

Điều kiện tiên quyết

Chương này xem xét cách các biểu mẫu được thực hiện và xác nhận trong HTML. Nếu bạn chưa bao giờ làm việc với HTML hoặc các biểu mẫu trước đây, có một số tài nguyên tuyệt vời có sẵn từ Mạng lưới Nhà phát triển Mozilla (MDN):

  • Giới thiệu về HTML
  • Giới thiệu về các biểu mẫu web
  • Hình thức xác nhận

Các hình thức

Phần 1, Chương 6

Chương này xem xét cách tạo các biểu mẫu để có được dữ liệu đầu vào của người dùng.

  • Điều kiện tiên quyết
  • Chương này xem xét cách các biểu mẫu được thực hiện và xác nhận trong HTML. Nếu bạn chưa bao giờ làm việc với HTML hoặc các biểu mẫu trước đây, có một số tài nguyên tuyệt vời có sẵn từ Mạng lưới Nhà phát triển Mozilla (MDN):
  • Giới thiệu về HTML

Giới thiệu về các biểu mẫu web

  • Hình thức xác nhận
  • Các biểu mẫu (còn được gọi là 'biểu mẫu web' hoặc 'biểu mẫu HTML') cung cấp một cách để người dùng tương tác với một ứng dụng web. Thông thường, các biểu mẫu cho phép người dùng nhập dữ liệu, được gửi đến máy chủ được xử lý.
  • Một số ví dụ về biểu mẫu:

Đăng ký người dùng

Tiếp xúc

  1. Nhận xét
  2. Trong chương này, chúng tôi sẽ triển khai một biểu mẫu để gửi dữ liệu sau đây cho một cổ phiếu:

Biểu tượng cổ phần

Số lượng cổ phiếu đã mua

giá mua

Biểu mẫu cho dữ liệu chứng khoán

Để tạo biểu mẫu, chúng tôi sẽ thêm:

  • Mã HTML (trong một mẫu) để hiển thị biểu mẫu
  • Một hàm xem (tính bằng python) để phục vụ và xử lý việc gửi biểu mẫu

Mẫu (HTML)

Hãy bắt đầu bằng cách tạo mã HTML cho biểu mẫu bằng cách tạo một tệp mới có tên Mẫu/add_Stock.html:

{% extends "base.html" %}

{% block content %}
<h2>Add a Stock</h2>
<form method="post">
  <label for="stockSymbol">Stock Symbol:</label>
  <input type="text" id="stockSymbol" name="stock_symbol" />
  <br>
  <label for="numberOfShares">Number of Shares:</label>
  <input type="text" id="numberOfShares" name="number_of_shares" />
  <br>
  <label for="purchasePrice">Purchase Price ($):</label>
  <input type="text" id="purchasePrice" name="purchase_price" />
  <br>
  <input type="submit">
</form>
{% endblock %}

<label for="stockSymbol">Stock Symbol:</label>
<input type="text" id="stockSymbol" name="stock_symbol" />

Yếu tố hình thức

Phần tử

import string, random

app.secret_key = ''.join(random.choice(string.printable) for _ in range(20))
#secret_key needed for session implementation

@app.route("/update_layout")
def update_layout():
  flask.session['layout'] = flask.request.args.get('layout')
  return flask.jsonify({'success':'True'})

@app.route('/workstation', methods=['GET'])
def workstation():
  return flask.render_template('station.html',target = flask.session['layout'])
8 được sử dụng để xác định một biểu mẫu, có thể chứa bất kỳ số lượng đầu vào nào mà người dùng có thể cung cấp. Có hai thuộc tính chính thường được sử dụng với phần tử
import string, random

app.secret_key = ''.join(random.choice(string.printable) for _ in range(20))
#secret_key needed for session implementation

@app.route("/update_layout")
def update_layout():
  flask.session['layout'] = flask.request.args.get('layout')
  return flask.jsonify({'success':'True'})

@app.route('/workstation', methods=['GET'])
def workstation():
  return flask.render_template('station.html',target = flask.session['layout'])
8:

{% extends "base.html" %}

{% block content %}
<h2>Add a Stock</h2>
<form method="post">
  <label for="stockSymbol">Stock Symbol:</label>
  <input type="text" id="stockSymbol" name="stock_symbol" />
  <br>
  <label for="numberOfShares">Number of Shares:</label>
  <input type="text" id="numberOfShares" name="number_of_shares" />
  <br>
  <label for="purchasePrice">Purchase Price ($):</label>
  <input type="text" id="purchasePrice" name="purchase_price" />
  <br>
  <input type="submit">
</form>
{% endblock %}
0 Xác định vị trí (URL) trong đó biểu mẫu sẽ được gửi đến khi được gửi

  • {% extends "base.html" %}
    
    {% block content %}
    <h2>Add a Stock</h2>
    <form method="post">
      <label for="stockSymbol">Stock Symbol:</label>
      <input type="text" id="stockSymbol" name="stock_symbol" />
      <br>
      <label for="numberOfShares">Number of Shares:</label>
      <input type="text" id="numberOfShares" name="number_of_shares" />
      <br>
      <label for="purchasePrice">Purchase Price ($):</label>
      <input type="text" id="purchasePrice" name="purchase_price" />
      <br>
      <input type="submit">
    </form>
    {% endblock %}
    
    1 định nghĩa phương thức HTTP nào (thông thường, đăng) để gửi dữ liệu với
  • Trong ví dụ trên, chúng tôi đặt phương thức để đăng và vì chúng tôi đã bỏ thuộc tính
    {% extends "base.html" %}
    
    {% block content %}
    <h2>Add a Stock</h2>
    <form method="post">
      <label for="stockSymbol">Stock Symbol:</label>
      <input type="text" id="stockSymbol" name="stock_symbol" />
      <br>
      <label for="numberOfShares">Number of Shares:</label>
      <input type="text" id="numberOfShares" name="number_of_shares" />
      <br>
      <label for="purchasePrice">Purchase Price ($):</label>
      <input type="text" id="purchasePrice" name="purchase_price" />
      <br>
      <input type="submit">
    </form>
    {% endblock %}
    
    0, việc gửi biểu mẫu sẽ được gửi đến cùng một URL được sử dụng để phục vụ biểu mẫu trong trình duyệt.
  • Các yếu tố đầu vào
  • Trong HTML, cách tiếp cận điển hình để xác định đầu vào là tạo một phần tử
    {% extends "base.html" %}
    
    {% block content %}
    <h2>Add a Stock</h2>
    <form method="post">
      <label for="stockSymbol">Stock Symbol:</label>
      <input type="text" id="stockSymbol" name="stock_symbol" />
      <br>
      <label for="numberOfShares">Number of Shares:</label>
      <input type="text" id="numberOfShares" name="number_of_shares" />
      <br>
      <label for="purchasePrice">Purchase Price ($):</label>
      <input type="text" id="purchasePrice" name="purchase_price" />
      <br>
      <input type="submit">
    </form>
    {% endblock %}
    
    3 để xác định mô tả về những gì sẽ nhập và sau đó có một phần tử
    {% extends "base.html" %}
    
    {% block content %}
    <h2>Add a Stock</h2>
    <form method="post">
      <label for="stockSymbol">Stock Symbol:</label>
      <input type="text" id="stockSymbol" name="stock_symbol" />
      <br>
      <label for="numberOfShares">Number of Shares:</label>
      <input type="text" id="numberOfShares" name="number_of_shares" />
      <br>
      <label for="purchasePrice">Purchase Price ($):</label>
      <input type="text" id="purchasePrice" name="purchase_price" />
      <br>
      <input type="submit">
    </form>
    {% endblock %}
    
    4 riêng biệt để thu thập đầu vào:
  • Hai yếu tố này được liên kết với nhau thông qua định danh
    {% extends "base.html" %}
    
    {% block content %}
    <h2>Add a Stock</h2>
    <form method="post">
      <label for="stockSymbol">Stock Symbol:</label>
      <input type="text" id="stockSymbol" name="stock_symbol" />
      <br>
      <label for="numberOfShares">Number of Shares:</label>
      <input type="text" id="numberOfShares" name="number_of_shares" />
      <br>
      <label for="purchasePrice">Purchase Price ($):</label>
      <input type="text" id="purchasePrice" name="purchase_price" />
      <br>
      <input type="submit">
    </form>
    {% endblock %}
    
    5. Phần tử
    {% extends "base.html" %}
    
    {% block content %}
    <h2>Add a Stock</h2>
    <form method="post">
      <label for="stockSymbol">Stock Symbol:</label>
      <input type="text" id="stockSymbol" name="stock_symbol" />
      <br>
      <label for="numberOfShares">Number of Shares:</label>
      <input type="text" id="numberOfShares" name="number_of_shares" />
      <br>
      <label for="purchasePrice">Purchase Price ($):</label>
      <input type="text" id="purchasePrice" name="purchase_price" />
      <br>
      <input type="submit">
    </form>
    {% endblock %}
    
    3 cung cấp mô tả
    {% extends "base.html" %}
    
    {% block content %}
    <h2>Add a Stock</h2>
    <form method="post">
      <label for="stockSymbol">Stock Symbol:</label>
      <input type="text" id="stockSymbol" name="stock_symbol" />
      <br>
      <label for="numberOfShares">Number of Shares:</label>
      <input type="text" id="numberOfShares" name="number_of_shares" />
      <br>
      <label for="purchasePrice">Purchase Price ($):</label>
      <input type="text" id="purchasePrice" name="purchase_price" />
      <br>
      <input type="submit">
    </form>
    {% endblock %}
    
    7 Phần tử
    {% extends "base.html" %}
    
    {% block content %}
    <h2>Add a Stock</h2>
    <form method="post">
      <label for="stockSymbol">Stock Symbol:</label>
      <input type="text" id="stockSymbol" name="stock_symbol" />
      <br>
      <label for="numberOfShares">Number of Shares:</label>
      <input type="text" id="numberOfShares" name="number_of_shares" />
      <br>
      <label for="purchasePrice">Purchase Price ($):</label>
      <input type="text" id="purchasePrice" name="purchase_price" />
      <br>
      <input type="submit">
    </form>
    {% endblock %}
    
    4 với
    {% extends "base.html" %}
    
    {% block content %}
    <h2>Add a Stock</h2>
    <form method="post">
      <label for="stockSymbol">Stock Symbol:</label>
      <input type="text" id="stockSymbol" name="stock_symbol" />
      <br>
      <label for="numberOfShares">Number of Shares:</label>
      <input type="text" id="numberOfShares" name="number_of_shares" />
      <br>
      <label for="purchasePrice">Purchase Price ($):</label>
      <input type="text" id="purchasePrice" name="purchase_price" />
      <br>
      <input type="submit">
    </form>
    {% endblock %}
    
    9 phù hợp của
    {% extends "base.html" %}
    
    {% block content %}
    <h2>Add a Stock</h2>
    <form method="post">
      <label for="stockSymbol">Stock Symbol:</label>
      <input type="text" id="stockSymbol" name="stock_symbol" />
      <br>
      <label for="numberOfShares">Number of Shares:</label>
      <input type="text" id="numberOfShares" name="number_of_shares" />
      <br>
      <label for="purchasePrice">Purchase Price ($):</label>
      <input type="text" id="purchasePrice" name="purchase_price" />
      <br>
      <input type="submit">
    </form>
    {% endblock %}
    
    5.
  • Đảm bảo bao gồm thuộc tính
    <label for="stockSymbol">Stock Symbol:</label>
    <input type="text" id="stockSymbol" name="stock_symbol" />
    
    1 trong mỗi phần tử
    {% extends "base.html" %}
    
    {% block content %}
    <h2>Add a Stock</h2>
    <form method="post">
      <label for="stockSymbol">Stock Symbol:</label>
      <input type="text" id="stockSymbol" name="stock_symbol" />
      <br>
      <label for="numberOfShares">Number of Shares:</label>
      <input type="text" id="numberOfShares" name="number_of_shares" />
      <br>
      <label for="purchasePrice">Purchase Price ($):</label>
      <input type="text" id="purchasePrice" name="purchase_price" />
      <br>
      <input type="submit">
    </form>
    {% endblock %}
    
    4, vì điều này được sử dụng bởi bình để phân tích dữ liệu đầu vào từ đối tượng
    <label for="stockSymbol">Stock Symbol:</label>
    <input type="text" id="stockSymbol" name="stock_symbol" />
    
    3. Chúng tôi sẽ xem xét chi tiết này một cách chi tiết.
  • <label for="stockSymbol">Stock Symbol:</label>
    <input type="text" id="stockSymbol" name="stock_symbol" />
    
    4 của phần tử đầu vào xác định loại dữ liệu dự kiến:
  • cái nút
  • Hộp kiểm
  • ngày
  • e-mail

tập tin

con số

mật khẩu mở khóa

Đài

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

Gửi đi

Hướng dẫn passing value from html to python flask without form - chuyển giá trị từ html sang bình python mà không có biểu mẫu

văn bản (mặc định)

<h2>Method Not Allowed</h2>
<p>The method is not allowed for the requested URL.</p>

URL

Trong hình thức này, chúng tôi đã xác định ba yếu tố

{% extends "base.html" %}

{% block content %}
<h2>Add a Stock</h2>
<form method="post">
  <label for="stockSymbol">Stock Symbol:</label>
  <input type="text" id="stockSymbol" name="stock_symbol" />
  <br>
  <label for="numberOfShares">Number of Shares:</label>
  <input type="text" id="numberOfShares" name="number_of_shares" />
  <br>
  <label for="purchasePrice">Purchase Price ($):</label>
  <input type="text" id="purchasePrice" name="purchase_price" />
  <br>
  <input type="submit">
</form>
{% endblock %}
4 với
<label for="stockSymbol">Stock Symbol:</label>
<input type="text" id="stockSymbol" name="stock_symbol" />
6.

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

Phần tử

{% extends "base.html" %}

{% block content %}
<h2>Add a Stock</h2>
<form method="post">
  <label for="stockSymbol">Stock Symbol:</label>
  <input type="text" id="stockSymbol" name="stock_symbol" />
  <br>
  <label for="numberOfShares">Number of Shares:</label>
  <input type="text" id="numberOfShares" name="number_of_shares" />
  <br>
  <label for="purchasePrice">Purchase Price ($):</label>
  <input type="text" id="purchasePrice" name="purchase_price" />
  <br>
  <input type="submit">
</form>
{% endblock %}
4 cuối cùng, từ ví dụ, có một loại
<label for="stockSymbol">Stock Symbol:</label>
<input type="text" id="stockSymbol" name="stock_symbol" />
8, sẽ được hiển thị dưới dạng nút HTML. Khi được nhấp, dữ liệu biểu mẫu sẽ được gửi đến phía máy chủ thông qua yêu cầu POST.

@app.route('/add_stock', methods=['GET', 'POST'])
def add_stock():
    return render_template('add_stock.html')

Tuyến đường

@app.route('/workstation')
def workstation():
  layout = flask.request.args.get('layout')
  return flask.jsonify({'html':flask.render_template('station.html',target=layout)})
0

Để phục vụ biểu mẫu này, hãy thêm chức năng tuyến mới và xem chức năng vào App.py:

Hướng dẫn passing value from html to python flask without form - chuyển giá trị từ html sang bình python mà không có biểu mẫu

Bây giờ, khi URL '/add_stock' được truy cập, mẫu/add_stock.html sẽ được hiển thị cho người dùng để xem:

Mặc dù chúng tôi có thể xem biểu mẫu, chúng tôi chưa thiết lập một tuyến đường để xử lý việc gửi biểu mẫu. Trên thực tế, nếu bạn nhấp vào nút 'Gửi', bạn sẽ nhận được lỗi 404 (phương thức không được phép):

@app.route('/workstation')
def workstation():
  layout = flask.request.args.get('layout')
  return flask.jsonify({'html':flask.render_template('station.html',target=layout)})
1

Xử lý dữ liệu mẫu

  • Hiện tại, chức năng
    <label for="stockSymbol">Stock Symbol:</label>
    <input type="text" id="stockSymbol" name="stock_symbol" />
    
    9 chỉ xử lý các yêu cầu nhận được:
  • Bạn có nhớ làm thế nào để cho phép các phương thức HTTP bổ sung không?
  • Tiếp theo, để thực hiện một thao tác khác khi phương thức HTTP là một bài đăng, hãy thực hiện các thay đổi sau:

Biểu đồ này cung cấp một minh họa về những gì xảy ra khi biểu mẫu được gửi:

@app.route('/workstation')
def workstation():
  layout = flask.request.args.get('layout')
  return flask.jsonify({'html':flask.render_template('station.html',target=layout)})
2

Lời yêu cầu

@app.route('/workstation')
def workstation():
  layout = flask.request.args.get('layout')
  return flask.jsonify({'html':flask.render_template('station.html',target=layout)})
3

Hình thức xác nhận

Các biểu mẫu (còn được gọi là 'biểu mẫu web' hoặc 'biểu mẫu HTML') cung cấp một cách để người dùng tương tác với một ứng dụng web. Thông thường, các biểu mẫu cho phép người dùng nhập dữ liệu, được gửi đến máy chủ được xử lý.

Một số ví dụ về biểu mẫu:

  • Đăng ký người dùng
  • Tiếp xúc
  • Nhận xét

Trong chương này, chúng tôi sẽ triển khai một biểu mẫu để gửi dữ liệu sau đây cho một cổ phiếu:

Client-Side

Xác thực biểu mẫu phía khách hàng là một lựa chọn tuyệt vời vì những lý do này:

  1. Không cần phải lãng phí thời gian gửi dữ liệu đến máy chủ nếu nó không hợp lệ để bắt đầu
  2. Xác thực hình thức HTML đã được cải thiện đáng kể trong vài năm qua

Xác thực phía máy khách là tuyệt vời để cung cấp phản hồi tức thời (gần) cho người dùng khi họ nhập dữ liệu không hợp lệ hoặc bất ngờ; Cách tiếp cận này cung cấp một trải nghiệm người dùng tốt đẹp.

Dưới đây là một số kiểm tra xác thực chính có thể được xác định trong mã HTML cho một biểu mẫu:

  • @app.route('/add_stock')
    def add_stock():
        return render_template('add_stock.html')
    
    4 Chỉ định rằng trường cần được điền vào
  • @app.route('/add_stock')
    def add_stock():
        return render_template('add_stock.html')
    
    5 và
    @app.route('/add_stock')
    def add_stock():
        return render_template('add_stock.html')
    
    6 Chỉ định độ dài tối thiểu và tối đa của đầu vào văn bản (chuỗi)
  • @app.route('/add_stock')
    def add_stock():
        return render_template('add_stock.html')
    
    7 sử dụng biểu thức chính quy để xác định một mẫu mà dữ liệu cần tuân thủ

Ngoài ra, các thuộc tính

<label for="stockSymbol">Stock Symbol:</label>
<input type="text" id="stockSymbol" name="stock_symbol" />
4 khác nhau có xác thực dữ liệu tích hợp, riêng của chúng.

Vì vậy, khi biểu mẫu được gửi, trình duyệt web kiểm tra xem dữ liệu ở định dạng chính xác dựa trên các ràng buộc được chỉ định. Nếu dữ liệu truyền kiểm tra xác thực, nó sẽ được gửi đến máy chủ để xử lý.

Đầu vào dữ liệu không hợp lệ

Để minh họa cách xác thực biểu mẫu có giá trị, hãy cố gắng gửi một số dữ liệu không hợp lệ. Điều hướng đến biểu mẫu trong trình duyệt của bạn và nhập dữ liệu sau:

Đồng ruộngGiá trịSự mô tả
Biểu tượng cổ phần15 Biểu tượng chứng khoán không hợp lệ!
Số lượng cổ phiếu Cánh đồng trống!
Giá mua ($)302.17 Có giá trị

Vì không có kiểm tra xác thực trên các trường đầu vào, dữ liệu này được truyền trực tiếp đến chức năng xem của chúng tôi và đầu ra sau được đăng nhập vào bảng điều khiển:

@app.route('/workstation')
def workstation():
  layout = flask.request.args.get('layout')
  return flask.jsonify({'html':flask.render_template('station.html',target=layout)})
4

May mắn thay, đây là một sửa chữa khá dễ dàng.

Biểu mẫu cập nhật

Mặc dù chúng tôi sẽ sử dụng một số trình xác nhận biểu mẫu khác nhau trong khóa học này, hãy bắt đầu bằng cách sử dụng trình xác nhận

@app.route('/add_stock')
def add_stock():
    return render_template('add_stock.html')
4 và
@app.route('/add_stock')
def add_stock():
    return render_template('add_stock.html')
7 trong các mẫu/add_stock.html:

@app.route('/workstation')
def workstation():
  layout = flask.request.args.get('layout')
  return flask.jsonify({'html':flask.render_template('station.html',target=layout)})
5

Biểu mẫu không còn cho phép trường

{% extends "base.html" %}

{% block content %}
<h2>Add a Stock</h2>
<form method="post">
  <label for="stockSymbol">Stock Symbol:</label>
  <input type="text" id="stockSymbol" name="stock_symbol" />
  <br>
  <label for="numberOfShares">Number of Shares:</label>
  <input type="text" id="numberOfShares" name="number_of_shares" />
  <br>
  <label for="purchasePrice">Purchase Price ($):</label>
  <input type="text" id="purchasePrice" name="purchase_price" />
  <br>
  <input type="submit">
</form>
{% endblock %}
4 trống do thuộc tính
@app.route('/add_stock')
def add_stock():
    return render_template('add_stock.html')
4. Ngoài ra, có một mẫu regex được sử dụng để kiểm tra định dạng của ký hiệu chứng khoán. Mẫu Regex được định nghĩa là
<h2>Method Not Allowed</h2>
<p>The method is not allowed for the requested URL.</p>
3, có nghĩa là cần phải có từ 1 đến 5 (
<h2>Method Not Allowed</h2>
<p>The method is not allowed for the requested URL.</p>
4) chữ cái viết hoa (
<h2>Method Not Allowed</h2>
<p>The method is not allowed for the requested URL.</p>
5).

Vài ví dụ:

  • AAPL - hợp lệ
  • Appl - không hợp lệ
  • Patrick - Không hợp lệ
  • T123 - Không hợp lệ
  • T - hợp lệ

Vì mỗi đầu vào là bắt buộc, chúng tôi nên thông báo cho người dùng về điều này để chúng không bị mất cảnh giác bởi một thông báo lỗi khi họ gửi biểu mẫu:

@app.route('/workstation')
def workstation():
  layout = flask.request.args.get('layout')
  return flask.jsonify({'html':flask.render_template('station.html',target=layout)})
6

Hãy thử gửi biểu mẫu mà không cần điền vào trường biểu tượng chứng khoán:

Hướng dẫn passing value from html to python flask without form - chuyển giá trị từ html sang bình python mà không có biểu mẫu

Trình duyệt web thực hiện xác thực biểu mẫu mỗi khi nhấp vào nút 'gửi'. Vì trường ký hiệu chứng khoán không được điền vào, trình duyệt web báo cáo lỗi lại cho chúng tôi và yêu cầu bài đăng HTTP cho máy chủ không được gửi vì biểu mẫu không hợp lệ.

Nếu bạn không thấy các thay đổi được thực hiện cho các tệp HTML (hoặc CSS) của mình khi chạy máy chủ phát triển Flask, hãy thử khởi động lại bằng cách thoát khỏi Máy chủ phát triển Flask (Control-C) và chạy lại

<h2>Method Not Allowed</h2>
<p>The method is not allowed for the requested URL.</p>
6.

Tiếp theo, hãy thử gửi biểu mẫu với một mục nhập không hợp lệ trong trường biểu tượng chứng khoán:

Hướng dẫn passing value from html to python flask without form - chuyển giá trị từ html sang bình python mà không có biểu mẫu

Vì ký hiệu chứng khoán của '12' không khớp với mẫu regex cho biểu tượng chứng khoán, trình duyệt web báo cáo lỗi lại cho chúng tôi.

Mặc dù có rất nhiều tùy chọn có sẵn để xác thực biểu mẫu trong HTML, bạn có thể mở rộng điều này hơn nữa bằng cách sử dụng JavaScript để mở rộng trình xác nhận tích hợp của trình duyệt để tạo trải nghiệm thanh lịch hơn cho người dùng cuối. Tham khảo Hướng dẫn xác thực biểu mẫu từ Mạng lưới Nhà phát triển Mozilla để biết thêm chi tiết.

Server-Side

Mặc dù xác thực phía máy khách giúp giữ trải nghiệm người dùng tốt đẹp, xác thực phía máy chủ vẫn là một cách tốt nhất (ngay cả với xác thực phía máy khách). Xác thực phía máy khách có thể được bỏ qua và dữ liệu độc hại/độc hại có thể được gửi đến máy chủ của bạn. Kiểm tra hướng dẫn của Tmozilla Developer Network về xác thực phía máy khách để biết thêm chi tiết.

Để có được ý tưởng về các hạn chế của xác thực phía máy khách, hãy thử gửi biểu mẫu với dữ liệu sau:

Đồng ruộngGiá trịSự mô tả
Biểu tượng cổ phầnBiểu tượng chứng khoán không hợp lệ!Có giá trị
Số lượng cổ phiếu100 Có giá trị
Giá mua ($)34,56 Có giá trị

Vì không có kiểm tra xác thực trên các trường đầu vào, dữ liệu này được truyền trực tiếp đến chức năng xem của chúng tôi và đầu ra sau được đăng nhập vào bảng điều khiển:

@app.route('/workstation')
def workstation():
  layout = flask.request.args.get('layout')
  return flask.jsonify({'html':flask.render_template('station.html',target=layout)})
7

May mắn thay, đây là một sửa chữa khá dễ dàng.

Biểu mẫu cập nhật

@app.route('/workstation')
def workstation():
  layout = flask.request.args.get('layout')
  return flask.jsonify({'html':flask.render_template('station.html',target=layout)})
8

Mặc dù chúng tôi sẽ sử dụng một số trình xác nhận biểu mẫu khác nhau trong khóa học này, hãy bắt đầu bằng cách sử dụng trình xác nhận

@app.route('/add_stock')
def add_stock():
    return render_template('add_stock.html')
4 và
@app.route('/add_stock')
def add_stock():
    return render_template('add_stock.html')
7 trong các mẫu/add_stock.html:

@app.route('/workstation')
def workstation():
  layout = flask.request.args.get('layout')
  return flask.jsonify({'html':flask.render_template('station.html',target=layout)})
9

Biểu mẫu không còn cho phép trường

{% extends "base.html" %}

{% block content %}
<h2>Add a Stock</h2>
<form method="post">
  <label for="stockSymbol">Stock Symbol:</label>
  <input type="text" id="stockSymbol" name="stock_symbol" />
  <br>
  <label for="numberOfShares">Number of Shares:</label>
  <input type="text" id="numberOfShares" name="number_of_shares" />
  <br>
  <label for="purchasePrice">Purchase Price ($):</label>
  <input type="text" id="purchasePrice" name="purchase_price" />
  <br>
  <input type="submit">
</form>
{% endblock %}
4 trống do thuộc tính
@app.route('/add_stock')
def add_stock():
    return render_template('add_stock.html')
4. Ngoài ra, có một mẫu regex được sử dụng để kiểm tra định dạng của ký hiệu chứng khoán. Mẫu Regex được định nghĩa là
<h2>Method Not Allowed</h2>
<p>The method is not allowed for the requested URL.</p>
3, có nghĩa là cần phải có từ 1 đến 5 (
<h2>Method Not Allowed</h2>
<p>The method is not allowed for the requested URL.</p>
4) chữ cái viết hoa (
<h2>Method Not Allowed</h2>
<p>The method is not allowed for the requested URL.</p>
5).

$(document).ready(function(){
  $('.qtemp').on('click',function(){
    var layout = $(this).data('rep');
    $.ajax({
      url: "/update_layout",
      type: "get",
      data: {layout: layout},
      success: function(response) {
        window.location.replace('/workstation');
      },
    });     
  });
});
0

Vài ví dụ:

  1. @app.route('/add_stock')
    def add_stock():
        return render_template('add_stock.html')
    
    0 - ​​Chuỗi (
    @app.route('/add_stock')
    def add_stock():
        return render_template('add_stock.html')
    
    1)
  2. @app.route('/add_stock')
    def add_stock():
        return render_template('add_stock.html')
    
    2 - Số nguyên (
    @app.route('/add_stock')
    def add_stock():
        return render_template('add_stock.html')
    
    3)
  3. @app.route('/add_stock')
    def add_stock():
        return render_template('add_stock.html')
    
    4 - Điểm nổi (
    @app.route('/add_stock')
    def add_stock():
        return render_template('add_stock.html')
    
    5)

Khi một thể hiện mới của

<h2>Method Not Allowed</h2>
<p>The method is not allowed for the requested URL.</p>
8 được tạo bằng cách truyền trong cả ba phần tử dữ liệu, một nỗ lực sẽ được thực hiện để chuyển đổi từng trường thành loại dữ liệu hiện hành. Ngoài ra, có trình xác thực tùy chỉnh cho trường
@app.route('/add_stock')
def add_stock():
    return render_template('add_stock.html')
0 để đảm bảo giá trị nằm trong khoảng từ 1 đến 5 ký tự.

Dưới đây là một ví dụ về việc tạo đối tượng

<h2>Method Not Allowed</h2>
<p>The method is not allowed for the requested URL.</p>
8 với dữ liệu hợp lệ:

$(document).ready(function(){
  $('.qtemp').on('click',function(){
    var layout = $(this).data('rep');
    $.ajax({
      url: "/update_layout",
      type: "get",
      data: {layout: layout},
      success: function(response) {
        window.location.replace('/workstation');
      },
    });     
  });
});
1

Vỏ bình sẽ được giới thiệu trong một chương sắp tới!

Tuy nhiên, nếu dữ liệu không hợp lệ được truyền vào khi tạo đối tượng

<h2>Method Not Allowed</h2>
<p>The method is not allowed for the requested URL.</p>
8, thì
@app.route('/add_stock', methods=['GET', 'POST'])
def add_stock():
    return render_template('add_stock.html')
0 sẽ được nêu ra:

$(document).ready(function(){
  $('.qtemp').on('click',function(){
    var layout = $(this).data('rep');
    $.ajax({
      url: "/update_layout",
      type: "get",
      data: {layout: layout},
      success: function(response) {
        window.location.replace('/workstation');
      },
    });     
  });
});
2

Hãy sử dụng lớp trợ giúp này (

<h2>Method Not Allowed</h2>
<p>The method is not allowed for the requested URL.</p>
8) trong hàm xem
<label for="stockSymbol">Stock Symbol:</label>
<input type="text" id="stockSymbol" name="stock_symbol" />
9:

$(document).ready(function(){
  $('.qtemp').on('click',function(){
    var layout = $(this).data('rep');
    $.ajax({
      url: "/update_layout",
      type: "get",
      data: {layout: layout},
      success: function(response) {
        window.location.replace('/workstation');
      },
    });     
  });
});
3

Vì vậy, khi biểu mẫu 'thêm cổ phiếu' được gửi (thông qua cuộc gọi bài đăng), các phần tử dữ liệu từ biểu mẫu sẽ được xác thực khi đối tượng

<h2>Method Not Allowed</h2>
<p>The method is not allowed for the requested URL.</p>
8 được tạo:

  1. Nếu dữ liệu ở định dạng chính xác, thì dữ liệu chứng khoán sẽ được in vào bảng điều khiển.
  2. Nếu dữ liệu không ở định dạng chính xác, thông báo lỗi được in vào bảng điều khiển cho biết kiểm tra xác thực nào không thành công.

Hãy thử thêm cùng một dữ liệu không hợp lệ từ trước đó (với

<h2>Method Not Allowed</h2>
<p>The method is not allowed for the requested URL.</p>
7 như giá mua):invalid data from earlier (with
<h2>Method Not Allowed</h2>
<p>The method is not allowed for the requested URL.</p>
7 as the purchase price):

$(document).ready(function(){
  $('.qtemp').on('click',function(){
    var layout = $(this).data('rep');
    $.ajax({
      url: "/update_layout",
      type: "get",
      data: {layout: layout},
      success: function(response) {
        window.location.replace('/workstation');
      },
    });     
  });
});
4

Thử thêm dữ liệu hợp lệ trong biểu mẫu:valid data in the form:

$(document).ready(function(){
  $('.qtemp').on('click',function(){
    var layout = $(this).data('rep');
    $.ajax({
      url: "/update_layout",
      type: "get",
      data: {layout: layout},
      success: function(response) {
        window.location.replace('/workstation');
      },
    });     
  });
});
5

Sự kết luận

Trong chương này, chúng tôi đã xem xét cách tạo và xử lý các hình thức. Bây giờ bạn sẽ có thể:

  1. Giải thích cách xử lý các biểu mẫu trên ứng dụng web
  2. Xác định một biểu mẫu trong mẫu HTML
  3. Thay đổi các phương thức http cho phép cho chức năng xem bình
  4. Phân tích dữ liệu biểu mẫu trong hàm xem bằng đối tượng
    <label for="stockSymbol">Stock Symbol:</label>
    <input type="text" id="stockSymbol" name="stock_symbol" />
    
    3
  5. Thực hiện xác thực biểu mẫu cơ bản trong HTML (phía máy khách)
  6. Thực hiện xác thực dữ liệu trong Python với Pydantic (phía máy chủ)

Xin lưu ý rằng chương này không thảo luận về một cuộc tấn công phổ biến được gọi là giả mạo yêu cầu chéo (CSRF). Chúng tôi sẽ đề cập đến cách ngăn chặn cuộc tấn công này trong một chương sắp tới bằng cách sử dụng mô-đun Flask-WTForms.


Mark as Completed

Làm cách nào để gửi dữ liệu HTML đến bình mà không có biểu mẫu?

Trong index.js, thay thế dữ liệu: Bố cục bằng dữ liệu: json.Stringify (bố cục) sau đó trong .main.py, thay thế bố cục = dữ liệu bằng bố cục = yêu cầu. js , replace data: layout with data: JSON. stringify(layout) then in . main.py , replace layout = data with layout = request.

Làm cách nào để chuyển dữ liệu từ HTML sang bình Python?

Làm thế nào để bạn chuyển một giá trị từ HTML sang bình Python ?..
từ yêu cầu nhập khẩu bình ..
@ứng dụng. tuyến đường ('/py', phương thức = ['get', 'post']).
DEF Server ():.
Nếu yêu cầu. Phương thức == 'Bài đăng':.
# Sau đó lấy dữ liệu từ biểu mẫu ..
Tag = Yêu cầu. biểu mẫu ['tag'].

Làm cách nào để liên kết một tệp HTML với bình?

Kết xuất tệp HTML trong bình..
Đầu tiên, tạo một thư mục mới trong thư mục dự án có tên là Mẫu.Tạo một tệp mới trong thư mục mẫu đặt tên nhà.HTML.Trình phát video đang tải.Phát video.....
Bây giờ hãy mở App.py và thêm mã sau.Từ bình Nhập bình, Render_Template.Ứng dụng = Flask (__ name__) @App.tuyến đường('/').

Làm cách nào để chuyển hình ảnh từ HTML sang Python?

Thêm một tham chiếu thư viện (nhập thư viện) vào dự án Python của bạn. Hãy mở tệp hình ảnh nguồn trong python.call phương thức 'lưu ()', chuyển tên tệp đầu ra với phần mở rộng HTML.Nhận kết quả chuyển đổi hình ảnh là HTML. Open the source image file in Python. Call the 'save()' method, passing an output filename with HTML extension. Get the result of image conversion as HTML.