简体   繁体   English

Flask 从函数 python 中提取变量

[英]Flask extract variables from a function python

I created a form with flask using python and html.我使用 python 和 html 创建了一个带有烧瓶的表单。

I want to fill up a form and then save the values by clicking a Submit button in order to use them for another project.我想填写一个表单,然后通过单击提交按钮保存这些值,以便将它们用于另一个项目。 But I also want to create another button which when I click on it fill automatically the form with default values (in my case, I want 0 everywhere).但我也想创建另一个按钮,当我点击它时,它会自动用默认值填充表单(在我的情况下,我希望到处都是0 )。

Here is my HTML code form.html :这是我的 HTML 代码form.html

<!DOCTYPE HTML>
<html>
<head>
    <title>Sample page to test fill_web_form.py</title>
</head>
<body>
<p1><strong>SAMPLE PAGE TO TEST FILL_WEB_FORM.PY</strong></p1>

<!--test form-->
<form method="post" action="/">
    Test the motor:<br>
    <table> 
        <tr> 
            <td> Function number: </td> 
            <td> <input type="text" name="functionnumber"> </td> 
        </tr> 
        <tr> 
            <td> Angle: </td> 
            <td> <input type="text" name="angle"> </td> 
        </tr> 
        <tr> 
            <td> Speed: </td> 
            <td> <input type="text" name="speed"> </td> 
        </tr> 
        <tr> 
            <td> <input type="submit" name="btn" Value="Submit"> </td> 
        </tr> 
        <tr> 
            <td> <input type="submit" name="btn" Value="TURNON"> </td> 
        </tr>
    </table>
</form>

And my python code hello.py :而我的 python 代码hello.py

# sends data from html form to database
from flask import Flask 
from flask import request 
from flask import render_template

app = Flask(__name__)
@app.route('/')
def form():
    return render_template('form.html') 

@app.route('/', methods=['POST'])
def get_parameters():
    if request.form["btn"] == "Submit":
        form_params = []
        form_params.append(request.form['functionnumber'])
        form_params.append(request.form['angle'])
        form_params.append(request.form['speed'])       
    else:
        form_params = []
        form_params.append('0')
        form_params.append('0')
        form_params.append('0')
    return render_template('form.html'), str(form_params)

get_parameters()
print(get_parameters.form_params[0])

The two last lines are when I am trying to extract the variables from the function because I need to use them (I haven't implemented yet the code about why I need these variables).最后两行是当我试图从函数中提取变量时,因为我需要使用它们(我还没有实现关于为什么我需要这些变量的代码)。 I am printing the value of functionnumber --> print(get_parameters.form_params[0]) in order to see of it's working well.我正在打印functionnumber --> print(get_parameters.form_params[0]) ,以查看它是否运行良好。

Unfortunately I got the following error:不幸的是,我收到以下错误:

Traceback (most recent call last):
  File "C:\Users\Camille\AppData\Local\Programs\Python\Python39\lib\runpy.py", line 197, in _run_module_as_main
    return _run_code(code, main_globals, None,
  File "C:\Users\Camille\AppData\Local\Programs\Python\Python39\lib\runpy.py", line 87, in _run_code
    exec(code, run_globals)
  File "C:\Users\Camille\Documents\myproject\venv\Scripts\flask.exe\__main__.py", line 7, in <module>
  File "c:\users\camille\documents\myproject\venv\lib\site-packages\flask\cli.py", line 990, in main
    cli.main(args=sys.argv[1:])
  File "c:\users\camille\documents\myproject\venv\lib\site-packages\flask\cli.py", line 596, in main
    return super().main(*args, **kwargs)
  File "c:\users\camille\documents\myproject\venv\lib\site-packages\click\core.py", line 1062, in main
    rv = self.invoke(ctx)
  File "c:\users\camille\documents\myproject\venv\lib\site-packages\click\core.py", line 1668, in invoke
    return _process_result(sub_ctx.command.invoke(sub_ctx))
  File "c:\users\camille\documents\myproject\venv\lib\site-packages\click\core.py", line 1404, in invoke
    return ctx.invoke(self.callback, **ctx.params)
  File "c:\users\camille\documents\myproject\venv\lib\site-packages\click\core.py", line 763, in invoke
    return __callback(*args, **kwargs)
  File "c:\users\camille\documents\myproject\venv\lib\site-packages\click\decorators.py", line 84, in new_func
    return ctx.invoke(f, obj, *args, **kwargs)
  File "c:\users\camille\documents\myproject\venv\lib\site-packages\click\core.py", line 763, in invoke
    return __callback(*args, **kwargs)
  File "c:\users\camille\documents\myproject\venv\lib\site-packages\flask\cli.py", line 845, in run_command
    app = DispatchingApp(info.load_app, use_eager_loading=eager_loading)
  File "c:\users\camille\documents\myproject\venv\lib\site-packages\flask\cli.py", line 321, in __init__
    self._load_unlocked()
  File "c:\users\camille\documents\myproject\venv\lib\site-packages\flask\cli.py", line 346, in _load_unlocked
    self._app = rv = self.loader()
  File "c:\users\camille\documents\myproject\venv\lib\site-packages\flask\cli.py", line 402, in load_app
    app = locate_app(self, import_name, name)
  File "c:\users\camille\documents\myproject\venv\lib\site-packages\flask\cli.py", line 256, in locate_app
    __import__(module_name)
  File "C:\Users\Camille\Documents\myproject\hello.py", line 25, in <module>
    get_parameters()
  File "C:\Users\Camille\Documents\myproject\hello.py", line 13, in get_parameters
    if request.form["btn"] == "Submit":
  File "c:\users\camille\documents\myproject\venv\lib\site-packages\werkzeug\local.py", line 422, in __get__
    obj = instance._get_current_object()
  File "c:\users\camille\documents\myproject\venv\lib\site-packages\werkzeug\local.py", line 544, in _get_current_object
    return self.__local()  # type: ignore
  File "c:\users\camille\documents\myproject\venv\lib\site-packages\flask\globals.py", line 33, in _lookup_req_object
    raise RuntimeError(_request_ctx_err_msg)
RuntimeError: Working outside of request context.

This typically means that you attempted to use functionality that needed
an active HTTP request.  Consult the documentation on testing for
information about how to avoid this problem.
     

When I don't add the two last line, it's working but it's still an issue because I can't use and extract the variables.当我不添加最后两行时,它可以工作,但仍然是一个问题,因为我无法使用和提取变量。 I want to access the variables form_params[0] , form_params[1] , form_params[2] outside the function.我想访问函数外的变量form_params[0]form_params[1]form_params[2]

Your question has 2 parts:你的问题有两部分:

  1. How to add default values to HTML input fields: You can either give default value by default rather than on a button click, this way:如何向 HTML 输入字段添加默认值:您可以默认提供默认值而不是单击按钮,如下所示:
<input type="text" name="speed" value="0">

I'm not sure why you want it to appear on a button click.我不确定您为什么希望它出现在单击按钮时。 But if you really want it that way you need to add some JavaScript and do it, something like this:但是如果你真的想要那样,你需要添加一些 JavaScript 并执行它,如下所示:

HTML HTML

<form id="form">
<input type="text" name="speed">
<input type="text" name="angle">
<form>
<button id="btn"> Add default values </button>

JS (with jQuery) JS (使用 jQuery)

$("#btn").click(function () {
  $("#form")
    .find("input")
    .each(function (i) {
      $(this).attr("value", "0");
    });
});
  1. Run your flask server and just use the Browser or Postman to call your route and see what it returns.运行您的 Flask 服务器,只需使用浏览器或邮递员调用您的路线并查看它返回的内容。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM