使用从多个表中选择的内容创建烧瓶表单

2023-12-02

我看过大量的教程,这些教程显示了使用 Flask 和 flash-wtf 的登录表单,但没有一个教程是从数据库表值填充多个选择框的。

这就是我正在尝试做的:

一个简单的注册表:

地址第一行

地址行 2

City

状态 Id(从 Id、状态的状态库查询中填充)

国家/地区 ID(根据国家/地区库查询填充,ID)

示例代码或演练链接将不胜感激。


我试图找到如何执行此操作的解释,但找不到。所以我要在这里写一篇。这就是我做事的方式,可能还有更好的方法。

源代码

您可以在我的 github 帐户上下载本教程的完整源代码。我几乎是从源代码中复制和粘贴的,但以防万一 github 有一天死了,我们就开始吧。

配置

需要配置我们的应用程序和数据库连接。在多数情况下 您可能想从配置文件加载所有这些。

在本教程中,我们将使用基本的 sqlalchemy 测试数据库。

app = Flask(__name__)
app.config['SECRET_KEY'] = 'Insert_random_string_here'

如果您想查看生成的所有 SQL,请将此配置设置为 True。

app.config['SQLALCHEMY_ECHO'] = False
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:////tmp/test.db'

WTForms 配置字符串

app.config['WTF_CSRF_ENABLED'] = True

CSRF 代币很重要。在这里阅读更多关于他们的信息,https://www.owasp.org/index.php/Cross-Site_Request_Forgery_(CSRF)_Prevention_Cheat_Sheet

app.config['WTF_CSRF_SECRET_KEY'] = 'Insert_random_string_here'
db = SQLAlchemy(app)

SQLALchemy 模型

接下来我们需要创建将在创建过程中使用的模型类 数据库的操作以及当我们想要操作数据库时。这应该 通常是它自己的单独文件。

我从这里导入,就好像这是它自己的单独文件一样。

通常你必须导入做类似的事情 从应用程序导入数据库

class RegisteredUser(db.Model):
    """
    loads and pushes registered user data after they have signed up.

    SQLalchemy ORM table object which is used to load, and push, data from the
    server memory scope to, and from, the database scope.
    """
    __tablename__ = "RegisteredUser"

    #all of the columns in the database.
    registered_id = db.Column(db.Integer, primary_key=True)
    first_name = db.Column(db.String(70))
    last_name = db.Column(db.String(70))
    address_line_one = db.Column(db.String(256))
    address_line_two = db.Column(db.String(256))
    city = db.Column(db.String(50))

    """
    Now we're going to create all of the foreign keys for the RegisteredUser
    table. The db.relationship section allows us to easily and automatically
    join the other tables with registeredUser. The Join will only take place
    if you attempt to access columns from the State or country table.

    For more on Foreign keys using SQLAlchemy go to
    """
    state_id = db.Column(
            db.Integer,
            db.ForeignKey('State.state_id'),
            nullable=False)
    #retrives the users name for display purposes.
    state_by = db.relationship(
            'State',
            foreign_keys=[state_id],
            backref=db.backref('State', lazy='dynamic'))
    country_id = db.Column(
            db.Integer,
            db.ForeignKey('Country.country_id'),
            nullable=False)
    #retrives the users name for display purposes.
    country_by = db.relationship(
            'Country',
            foreign_keys=[country_id],)

    #this is the method and function style I've chosen when lines are too long
    def __init__(
            self,
            first_name,
            last_name,
            address_line_one,
            address_line_two,
            city,
            state_id,
            country_id):
        """
        Used to create a RegisteredUser object in the python server scope

        We will be calling these init functions every time we use
        RegisteredUser() as a 'function' call. It will create a SQLalchemy ORM
        object for us.
        """
        self.first_name = first_name
        self.last_name = last_name
        self.address_line_one = address_line_one
        self.address_line_two = address_line_two
        self.city = city
        self.state_id = state_id
        self.country_id = country_id


class State(db.Model):  # pylint: disable-msg=R0903
    """
    Holds State names for the database to load during the registration page.

    SQLalchemy ORM table object which is used to load, and push, data from the
    server memory scope to, and from, the database scope.
    """
    __tablename__ = "State"

    state_id = db.Column(db.Integer, primary_key=True)
    state_name = db.Column(db.String(10), unique=True)

    def __init__(self, state_name):
        """
        Used to create a State object in the python server scope
        """
        self.state_name = state_name


class Country(db.Model):  # pylint: disable-msg=R0903
    """
    Holds Country names for the database to load during the registration page.

    SQLalchemy ORM table object which is used to load, and push, data from the
    server memory scope to, and from, the database scope.
    """
    __tablename__ = "Country"

    country_id = db.Column(db.Integer, primary_key=True)
    #longest country length is currently 163 letters
    country_name = db.Column(db.String(256), unique=True)

    def __init__(self, country_name):
        """
        Used to create a Country object in the python server scope
        """
        self.country_name = country_name


def create_example_data():
    """
    Generates all of the demo data to be used later in the tutorial. This is
    how we can use our ORM objects to push data to the database.

    NOTE: create_example_data is called at the very bottom of the file.
    """
    #Create a bunch of state models and add them to the current session.
    #Note, this does not add rows to the database. We'll commit them later.
    state_model = State(state_name="WA")
    db.session.add(state_model)
    state_model = State(state_name="AK")
    db.session.add(state_model)
    state_model = State(state_name="LA")
    db.session.add(state_model)
    #Normally I load this data from very large CVS or json files and run This
    #sort of thing through a for loop.

    country_model = Country("USA")
    db.session.add(country_model)
    country_model = Country("Some_Made_Up_Place")
    db.session.add(country_model)
    # Interesting Note: things will be commited in reverse order from when they
    # were added.
    try:
        db.session.commit()
    except IntegrityError as e:
        print("attempted to push data to database. Not first run. continuing\
                as normal")

WTForm

现在我们将创建您的 WTForms 对象。这些将获得数据 从放置在它们上的数据库中,然后我们将它们传递到我们的模板文件 我们将在哪里渲染它们。

我从这里导入,就好像这是它自己的单独文件一样。

import wtforms
import wtforms.validators as validators
from flask.ext.wtf import Form

class RegistrationForm(Form):
    """
    This Form class contains all of the fileds that make up our registration
    Form. 
    """
    #Get all of the text fields out of the way.
    first_name_field = wtforms.TextField(
            label="First Name",
            validators=[validators.Length(max=70), validators.Required()])
    last_name_field = wtforms.TextField(
            label="Last Name",
            validators=[validators.Length(max=70), validators.Required()])
    address_line_one_field = wtforms.TextField(
            label="Address",
            validators=[validators.Length(max=256), validators.Required()])
    address_line_two_field = wtforms.TextField(
            label="Second Address",
            validators=[validators.Length(max=256), ])
    city_field = wtforms.TextField(
            label="City",
            validators=[validators.Length(max=50), validators.Required()])
    # Now let's set all of our select fields.
    state_select_field = wtforms.SelectField(label="State", coerce=int)
    country_select_field = wtforms.SelectField(label="Country", coerce=int)

Views

进口烧瓶

def populate_form_choices(registration_form):
    """
    Pulls choices from the database to populate our select fields.
    """
    states = State.query.all()
    countries = Country.query.all()
    state_names = []
    for state in states:
        state_names.append(state.state_name)
    #choices need to come in the form of a list comprised of enumerated lists
    #example [('cpp', 'C++'), ('py', 'Python'), ('text', 'Plain Text')]
    state_choices = list(enumerate(state_names))
    country_names = []
    for country in countries:
        country_names.append(country.country_name)
    country_choices = list(enumerate(country_names))
    #now that we've built our choices, we need to set them.
    registration_form.state_select_field.choices = state_choices
    registration_form.country_select_field.choices = country_choices

@app.route('/', methods=['GET', 'POST'])
def demonstration():
    """
    This will render a template that displays all of the form objects if it's
    a Get request. If the use is attempting to Post then this view will push
    the data to the database.
    """
    #this parts a little hard to understand. flask-wtforms does an implicit
    #call each time you create a form object. It attempts to see if there's a
    #request.form object in this session and if there is it adds the data from
    #the request to the form object.
    registration_form = RegistrationForm()
    #Before we attempt to validate our form data we have to set our select
    #field choices. This is just something you need to do if you're going to 
    #use WTForms, even if it seems silly.
    populate_form_choices(registration_form)
    #This means that if we're not sending a post request then this if statement
    #will always fail. So then we just move on to render the template normally.
    if flask.request.method == 'POST' and registration_form.validate():
        #If we're making a post request and we passed all the validators then
        #create a registered user model and push that model to the database.
        registered_user = RegisteredUser(
            first_name=registration_form.data['first_name_field'],
            last_name=registration_form.data['last_name_field'],
            address_line_one=registration_form.data['address_line_one_field'],
            address_line_two=registration_form.data['address_line_two_field'],
            city=registration_form.data['city_field'],
            state_id=registration_form.data['state_select_field'],
            country_id=registration_form.data['country_select_field'],)
        db.session.add(registered_user)
        db.session.commit()
        return flask.render_template(
            template_name_or_list='success.html',
            registration_form=registration_form,)
    return flask.render_template(
            template_name_or_list='registration.html',
            registration_form=registration_form,)

运行服务器.py

最后,这仅用于开发目的。我通常把它放在一个 文件名为 RunServer.py。为了实际交付您的应用程序,您应该 运行在某种 Web 服务器(Apache、Nginix、Heroku)后面。

if __name__ == '__main__':
    db.create_all()
    create_example_data()
    app.run(debug=True)

模板

在宏.html 中

{% macro render_field(field) %}
  <dt>{{ field.label }}
  <dd>{{ field(**kwargs)|safe }}
  {% if field.errors %}
    <ul class=errors>
    {% for error in field.errors %}
      <li>{{ error }}</li>
    {% endfor %}
    </ul>
  {% endif %}
  </dd>
{% endmacro %}

{% macro render_data(field) %}
  <dt>{{ field.label }}
  <dd>{{ field.data|safe }}
  {% if field.errors %}
    <ul class=errors>
    {% for error in field.errors %}
      <li>{{ error }}</li>
    {% endfor %}
    </ul>
  {% endif %}
  </dd>
{% endmacro %}

在注册.html中

{% from "macros.html" import render_field %}
<form method=post action="/">
    {{registration_form.hidden_tag()}}
  <dl>
    {{ render_field(registration_form.first_name_field) }}
    {{ render_field(registration_form.last_name_field) }}
    {{ render_field(registration_form.address_line_one_field) }}
    {{ render_field(registration_form.address_line_two_field) }}
    {{ render_field(registration_form.city_field) }}
    {{ render_field(registration_form.state_select_field) }}
    {{ render_field(registration_form.country_select_field) }}
  </dl>
  <p><input type=submit value=Register>
</form>

最后在success.html中

{% from "macros.html" import render_data %}
<h1> This data was saved to the database! </h1>
<form method=post action="/">
    {{registration_form.hidden_tag()}}
  <dl>
    {{ render_data(registration_form.first_name_field) }}
    {{ render_data(registration_form.last_name_field) }}
    {{ render_data(registration_form.address_line_one_field) }}
    {{ render_data(registration_form.address_line_two_field) }}
    {{ render_data(registration_form.city_field) }}
    {{ render_data(registration_form.state_select_field) }}
    {{ render_data(registration_form.country_select_field) }}
  </dl>
  <p><input type=submit value=Register>
</form>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

使用从多个表中选择的内容创建烧瓶表单 的相关文章

  • Python中矩阵元素的双重求和

    基于下面的简化示例 我想在我的代码中 from sympy import import numpy as np init printing x y symbols x y mat Matrix x 1 1 y X 1 2 3 Y 10 20
  • Python 线程在 main 中调用一次时运行两次[重复]

    这个问题在这里已经有答案了 if name main t threading Thread target authtarget t daemon True t start print running thread app run debug
  • 操作错误:尝试在 ubuntu 服务器中写入只读数据库

    我正在使用 FlaskApp 运行mod wsgi and apache2在 Ubuntu 服务器上 我尝试运行烧瓶应用程序localhost成功 然后部署到ubuntu服务器上 但是当我尝试更新数据库时 出现错误 Failed to up
  • 使用 Python 和 Google App Engine 的 Cookie

    我正在 Google App Engine 上开发一个应用程序 但遇到了问题 我想向每个用户会话添加一个 cookie 以便我能够区分当前用户 我希望他们都是匿名的 因此我不需要登录 因此 我为 cookie 实现了以下代码 def cle
  • 使用一次递归调用实现递归

    给定一个函数如下 f n f n 1 f n 3 f n 4 f 0 1 f 1 2 f 2 3 f 3 4 我知道使用递归来实现它 并在一个函数内进行三个递归调用 但我想在函数内仅使用一次递归调用来完成此操作 怎样才能做到呢 要实现使用
  • 如何让 Angular-Flask 应用加载 html 部分?

    我试图让我的 Angular Flask 应用程序在基本 html 文件中渲染部分 HTML 文件 应用程序加载基本 html 窗口标题和页脚加载 但 ng view 没有加载任何内容 也许我到局部的角度路由不正确 文件结构 gt flas
  • 使用 SERVER_NAME 时出现 Flask 404

    在我的 Flask 配置中 我将 SERVER NAME 设置为 app example com 之类的域 我这样做是因为我需要使用url for with external网址 如果未设置 SERVER NAME Flask 会认为服务器
  • 清理 .txt 并计算最常见的单词

    我需要 1 从停用词列表中清除 txt 我将其放在单独的 txt中 2 之后我需要统计最常见的 25 个单词 这是我为第一部分想到的 usr bin python coding iso 8859 15 import re from coll
  • Python守护进程:保持日志记录

    我有一个将一些数据记录到磁盘的脚本 logging basicConfig filename davis debug log level logging DEBUG logging basicConfig filename davis er
  • 在 docker 中根据更改重新启动 Flask 应用程序

    我正在使用 Flask script 来运行我的应用程序 if name main manager run 在 docker 中我有以下内容 CMD python manage py runserver h 0 0 0 0 p 5000 现
  • Wtforms:如何使用具有动态选择值的选择字段生成空白值

    我在用着Flask http flask pocoo org 与 WTForms doc http wtforms simplecodes com docs 0 6 fields html 在 Google App Engine 上 为选择
  • Matplotlib 与多处理冻结计算机

    我对 matplotlib 和多重处理有疑问 我启动第一个进程 在其中显示图像并选择一个区域 然后关闭图形 然后我启动另一个进程 在其中调用定期更新的图形函数 至此 一切正常 然后 当我尝试使用相同的图形功能启动另一个进程时 它冻结了我的整
  • 我可以在我的机器上同时安装 python 2.7 和 3.5 的tensorflow吗?

    目前我通过 Anaconda 在我的机器 MAC OX 上安装了 Python 2 7 Python 3 5 Tensorflow for Python 3 5 我也想在我的机器上安装 Tensorflow for Python 2 7 当
  • 张量流服务错误:参数无效:JSON 对象:没有命名输入

    我正在尝试使用 Amazon Sagemaker 训练模型 并且希望使用 Tensorflow 服务来为其提供服务 为了实现这一目标 我将模型下载到 Tensorflow 服务 docker 并尝试从那里提供服务 Sagemaker 的训练
  • 如何使用python在一个文件中写入多行

    如果我知道要写多少行 我就知道如何将多行写入一个文件 但是 当我想写多行时 问题就出现了 但是 我不知道它们会是多少 我正在开发一个应用程序 它从网站上抓取并将结果的链接存储在文本文件中 但是 我们不知道它会回复多少行 我的代码现在如下 r
  • 如何使用原始 SQL 查询实现搜索功能

    我正在创建一个由 CS50 的网络系列指导的应用程序 这要求我仅使用原始 SQL 查询而不是 ORM 我正在尝试创建一个搜索功能 用户可以在其中查找存储在数据库中的书籍列表 我希望他们能够查询 书籍 表中的 ISBN 标题 作者列 目前 它
  • 如何在flask中重新加载python模块?

    我有一个名为mapping py有一本字典methodMapping 在我的 Web 应用程序中 一个键值对被添加到 methodMapping 字典中 我将其附加到之后mapping py reload mapping 被调用 并且文件重
  • 在python中使用sftp从远程路径获取文件到本地目录

    我正在尝试将文件从远程路径获取到本地目录 当我执行代码时 我收到错误 如下所述 import paramiko import SSHLibrary from stat import S ISDIR server username passw
  • 如何检查字符串是否严格包含字母和数字

    如何检查一个字符串是否是strictly同时包含字母和数字 关注还不够 def containsLettersAndNumber input if input isalnum return True else return False is
  • 在 Pandas 中使用正则表达式的多种模式

    我是Python编程的初学者 我正在探索正则表达式 我正在尝试从 描述 列中提取一个单词 数据库名称 我无法给出多个正则表达式模式 请参阅下面的描述和代码 描述 Summary AD1 Low free DATA space in data

随机推荐

  • 获取星期一和星期日等..作为 Unix 中任何日期的一周参数

    如何获取某个日期一周中的星期一和星期日的日期 这给出了 最后 星期一的日期 date dlast monday Y m d 我想传递一个日期作为参数查找该周的星期一和星期日 基本上 我想要一周的周日和周一 任何日期 不仅仅是上周一 尝试这个
  • 如何将字符串从 HTML 传递到 Python 并返回到 HTML

    背景 我创建了一个非常简单的前端 用户可以在其中输入字符串 输入并单击 检查 按钮后 我想将此字符串作为 JSON 传递到 python 字符串 在其中执行 SQL 查找 根据 SQL 的外观 python 脚本应该传递一个布尔值 该值应该
  • 获取编译时已知的特定长度的切片

    在此代码中 fn unpack u32 data u8 gt u32 assert eq data len 4 let res data 0 as u32 data 1 as u32 lt lt 8 data 2 as u32 lt lt
  • 带有 C# ImageFormat 类的 WebP 图像

    我正在从网络下载图像以将其保存在本地 它适用于任何其他图像格式 但当我尝试读取 WebP 图像时 下面的方法会失败并出现参数异常 private static Image GetImage string url try HttpWebReq
  • 包容性和排除性的区别?

    我觉得这是一个简单的概念 但我在包容性和排他性方面遇到了麻烦 特别是关于随机数生成器 例如 如果我想要一个值 2 8 包括 2 和 8 那么这将是包容性的 对吗 该代码看起来怎么样 像这样的事情 nextInt 8 2 2 例如 如果我想要
  • 从一元数据创建二元(关系)数据

    我的冲突数据看起来像这样 conflict ID country code SideA 1 1 1 1 2 1 1 3 0 2 4 1 2 5 0 现在我想将其变成如下所示的二元冲突数据 SideA 1 应该是country code 1
  • 如何使用 PHP 创建随机字符串?

    我知道 PHP 中的 rand 函数生成随机整数 但是生成随机字符串的最佳方法是什么 例如 原始字符串 9 个字符 string abcdefghi 限制为 6 个字符的随机字符串示例 string ibfeca 更新 我发现了大量这些类型
  • 使用 documentFragment 的 IE 性能不佳

    为了测试 DOM 操作与innerHTML 我使用了这个小测试方法documentFragment web page 追加 10000href元素到一个div元素 对于 Chrome 或 Firefox 性能还可以 但在 IE 10 9 8
  • PhpStorm 和 XAMPP - 调试未启动

    我在使用 PhpStorm 调试器时遇到了困难 我阅读了他们所有的文档 并且我已经正确设置了调试 根据phpinfo 调试定制安装报告和 PhpStorm 分析 但是 无论我尝试什么 调试器都不会触发 我的设置如下 我将 XAMPP 文档根
  • 如何传递定义为常量的数组的引用?

    我定义了哈希和数组常量 当将它们传递给函数时 我必须将它们作为引用传递 不过我想知道正确的语法是什么 考虑这个例子 usr bin perl use strict use warnings use constant AC gt qw a b
  • 使用 sqlalchemy 查询特定 JSON 列 (postgres)

    我有一个带有 JSON 字段的模型 class Item db Model data db Column JSON nullable False 数据包含一些 JSON 例如 cost 10 00 passengers 2 surcharg
  • 后台代理静态变量值不同

    我有一个应用程序 可以显示一些数据并启动后台代理来动态更新动态图块 由于动态图块内容是在后台代理中使用从主线程填充的一些变量创建的 因此我决定 也许这是一个错误的决定 但这是我认为唯一合理的决定 编写一个具有静态变量和属性的类以在主线程之间
  • Laravel 5.3 使用自定义验证

    我使用 Laravel 5 3 我想使用表单验证来测试用户密码的哈希值 这是我的代码 validator Validator make request gt all old password gt required max 20 min 6
  • jpa返回哪些集合?

    JPA 在本例中为 Eclipselink 是否总是返回 IndirectList 其中实体有一个列表 该列表可以吗 或者应该将其转换为另一个列表 可能是链接列表 Analysis 如果我们看一下 EclipseLink 的间接列表的 AP
  • 即使在呈现模式视图控制器时如何保持键盘存在?

    我已经显示了一个模态视图控制器 并且 UITextView 成为第一响应者并显示键盘 加载此屏幕后 用户可以在提交之前对其输入进行分类 这是通过顶部呈现的另一个模态视图控制器来实现的 当第二个出现时 键盘将消失 用户进行选择 然后当初始 U
  • std::remove() 按预期使用文字,但不适用于取消引用的迭代器

    在学习删除 擦除惯用语的同时 以及了解 std min element 的工作原理如何在 C 17 中使用 std min element 我想尝试从以下代码中删除最小元素 include
  • 从 S3 通配符加载文件时发生 Spark 错误

    我正在使用 pyspark shell 并尝试使用 Spark 的文件通配符功能从 S3 读取数据 但出现以下错误 Welcome to version 1 2 0 Using Python version 2 7 6 default Ju
  • 为什么此代码会抛出 Facebook API 错误 191?

    我有以下 config php 文件位于 www sitename com facebook
  • 地理围栏:如何使用 Oracle Spatial 查找点或形状是否在多边形内

    如何使用 Oracle 空间 SQL 查询查找点或多边形是否在另一个多边形内 这是场景 我有一个表 STATE TABLE 其中包含一个空间类型 sdo geometry 它是一个多边形 比如说一个州 我有另一个表 UNIVERSITY T
  • 使用从多个表中选择的内容创建烧瓶表单

    我看过大量的教程 这些教程显示了使用 Flask 和 flash wtf 的登录表单 但没有一个教程是从数据库表值填充多个选择框的 这就是我正在尝试做的 一个简单的注册表 名 姓 地址第一行 地址行 2 City 状态 Id 从 Id 状态