📜  在Python使用 PyWebIO 模块创建注册表

📅  最后修改于: 2022-05-13 01:55:24.445000             🧑  作者: Mango

在Python使用 PyWebIO 模块创建注册表

在本文中,我们将使用 PyWebIO 模块创建一个注册表单。这是一个Python模块,主要用于使用Python编程在本地 Web 上创建简单的交互式界面。

此表单将输入用户名、姓名、密码、电子邮件、网站链接。谈到密码,它还会再次检查您的密码,以确认您的密码是否正确。它还将验证您的电话号码、网站链接、电子邮件地址。之后,您将获得由性别组成的单选按钮,您还将获得评论部分,以便您可以写下您的反馈。

表单元素

为了创建带有验证的正确表单,我们将通过示例一一学习不同的表单元素。

1. input_group:该元素用于获取组中的输入。当我们使用input_group 时,我们需要为每个输入函数提供name参数来标识结果中的输入项。

Python3
info = input_group("Group inputs", [
     input('Username', name='username'),
     input('Password', name='pass')])


Python3
input("Your name")


Python3
input('Name', type=TEXT)
input('PIN', type=NUMBER)
input('Password', type=PASSWORD)


Python3
input('Name', required=True)


Python3
def is_valid(data):
    if data <= 0:
        return 'Age cannot be negative!'
  
input('Age', type=NUMBER, validate=is_valid)


Python3
input_group("Info", [input('Name', name='name'),input('PIN ', name='pin')], cancelable=True)


Python3
input('Name', placeholder="Please Enter your name")


Python3
radio("Gender", options=['Male', 'Female'])


Python3
select("Tech Stack", options=[
  'C Programming', 'Python', 'Web Development', 'Android Development'])


Python3
textarea("Comments/Questions", rows=3)


Python3
checkbox("Languages", options=['Hindi', 'English', 'French'])


Python3
popup("Who are you?", "Geeks for Geeks")


Python3
# Import following modules
from pywebio.input import *
from pywebio.output import *
from pywebio.session import *
import re
  
# For checking Email, whether Valid or not.
regex = '^(\w|\.|\_|\-)+[@](\w|\_|\-|\.)+[.]\w{2,3}$'
  
# For checking Phone Number, whether Valid or 
# not.
Pattern = re.compile("(0/91)?[6-9][0-9]{9}")
  
# For Checking URL, whether valid or not
regex_1 = ("((http|https)://)(www.)?" + 
           "[a-zA-Z0-9@:%._\\+~#?&//=]" +
           "{2,256}\\.[a-z]" +
           "{2,6}\\b([-a-zA-Z0-9@:%" +
           "._\\+~#?&//=]*)")
Pattern_1 = re.compile(regex_1)
  
  
def check_form(data):
    
    # for checking Name
    if data['name'].isdigit():
        return ('name', 'Invalid name!')
        
    # for checking UserName
    if data['username'].isdigit():
        return ('username', 'Invalid username!')
        
    # for checking Age
    if data['age'] <= 0:
        return ('age', 'Invalid age!')
        
    # for checking Email
    if not (re.search(regex, data['email'])):
        return ('email', 'Invalid email!')
      
    # for checking Phone Number
    if not (Pattern.match(str(data['phone']))) 
    or len(str(data['phone'])) != 10:
        return ('phone', 'Invalid phone!')
      
    # for checking Website URL
    if not re.search(Pattern_1, data['website']):
        return ('website', 'Invalid URL!')
        
    # for matching Passwords
    if data['pass'] != data['passes']:
        return ('passes', "Please make sure your passwords match")
  
  
# Taking input from the user
data = input_group("Fill out the form:", [
    input('Username', name='username', type=TEXT,
          required=True, PlaceHolder="@username"),
    
    input('Password', name='pass', type=PASSWORD,
          required=True, PlaceHolder="Password"),
    
    input('Confirm Password', name='passes', type=PASSWORD,
          required=True, PlaceHolder="Confirm Password"),
    
    input('Name', name='name', type=TEXT, required=True, 
          PlaceHolder="name"),
    
    input('Phone', name='phone', type=NUMBER,
          required=True, PlaceHolder="12345"),
    
    input('Email', name='email', type=TEXT,
          required=True, PlaceHolder="user@gmail.com"),
    
    input('Age', name='age', type=NUMBER, required=True,
          PlaceHolder="age"),
    
    input('Portfolio website', name='website', type=TEXT,
          required=True, PlaceHolder="www.XYZ.com")
    
], validate=check_form, cancelable=True)
  
# Create a radio button
gender = radio("Gender", options=['Male', 'Female'], required=True)
  
# Create a skills markdown
skills = select("Tech Stack", options=[
  'C Programming', 'Python', 'Web Development', 'Android Development'],
                required=True)
  
# Create a textarea
text = textarea("Comments/Questions", rows=3,
                placeholder="Write something...", required=True)
  
# Create a checkbox
agree = checkbox("Agreement", options=[
    'I agree to terms and conditions'], required=True)
  
# Display output using popup
popup("Your Details",
      f"Username: @{data['username']}\nName: {data['name']}\
      \nPhone: {str(data['phone'])}\nEmail: {data['email']}\
      \nAge: {str(data['age'])}\nWebsite: {data['website']}\
      \nGender: {gender}\nSkill: {skills}\nComments: {text}",
      closable=True)


输出:

2. input:该元素用于从浏览器中获取用户的各种输入。

蟒蛇3

input("Your name")

输出:



3. type:这是在input函数input_group函数的。这取决于用户选择是用户想要输入中的数字还是输入中的文本。如果类型等于数字,它将只接受数字和文本的类似大小写。

蟒蛇3

input('Name', type=TEXT)
input('PIN', type=NUMBER)
input('Password', type=PASSWORD)

输出:

4. required:如果required为true,则表示您必须输入一些内容,我们不能留空,否则会出现“请填写此字段”的错误。默认情况下,它是假的。

蟒蛇3

input('Name', required=True)

输出:

5.validate:该元素接收输入作为参数,当输入值有效时返回True,当用户输入无效时返回错误信息。

蟒蛇3

def is_valid(data):
    if data <= 0:
        return 'Age cannot be negative!'
  
input('Age', type=NUMBER, validate=is_valid)

输出:

6.cancelable:表单是否可以取消。默认值为假。如果cancelable=True,则表单底部将显示“取消”按钮。

蟒蛇3

input_group("Info", [input('Name', name='name'),input('PIN ', name='pin')], cancelable=True)

输出:

7. PlaceHolder:这个元素只在 input_group函数,用于显示非常轻的文本。

蟒蛇3

input('Name', placeholder="Please Enter your name")

输出:

8.单选:单选按钮用于在众多选项中我们只能选择一个选项,即只能选择一个。

蟒蛇3

radio("Gender", options=['Male', 'Female'])

输出:

9.选择:这也称为下拉选择。默认情况下,一次只能选择一个选项。您还可以通过将“multiple”参数设置为 True 来选择多个选项。

蟒蛇3

select("Tech Stack", options=[
  'C Programming', 'Python', 'Web Development', 'Android Development'])

输出:

10. textarea:该元素用于在文本输入区进行多行输入。是在textarea内定义的一个元素,用于许多可见的文本行。

蟒蛇3

textarea("Comments/Questions", rows=3)

输出:

11.复选框:复选框允许用户选择/取消选择多个值,我们必须提供选项以便用户可以选择任何值。

蟒蛇3

checkbox("Languages", options=['Hindi', 'English', 'French'])

输出:

12. popup: pop用于以弹出方式产生输出,不能同时显示多个弹出窗口。在显示新的弹出窗口之前,页面上现有的弹出窗口将自动关闭,或者您可以手动关闭。

蟒蛇3

popup("Who are you?", "Geeks for Geeks")

输出:

填写表格

蟒蛇3

# Import following modules
from pywebio.input import *
from pywebio.output import *
from pywebio.session import *
import re
  
# For checking Email, whether Valid or not.
regex = '^(\w|\.|\_|\-)+[@](\w|\_|\-|\.)+[.]\w{2,3}$'
  
# For checking Phone Number, whether Valid or 
# not.
Pattern = re.compile("(0/91)?[6-9][0-9]{9}")
  
# For Checking URL, whether valid or not
regex_1 = ("((http|https)://)(www.)?" + 
           "[a-zA-Z0-9@:%._\\+~#?&//=]" +
           "{2,256}\\.[a-z]" +
           "{2,6}\\b([-a-zA-Z0-9@:%" +
           "._\\+~#?&//=]*)")
Pattern_1 = re.compile(regex_1)
  
  
def check_form(data):
    
    # for checking Name
    if data['name'].isdigit():
        return ('name', 'Invalid name!')
        
    # for checking UserName
    if data['username'].isdigit():
        return ('username', 'Invalid username!')
        
    # for checking Age
    if data['age'] <= 0:
        return ('age', 'Invalid age!')
        
    # for checking Email
    if not (re.search(regex, data['email'])):
        return ('email', 'Invalid email!')
      
    # for checking Phone Number
    if not (Pattern.match(str(data['phone']))) 
    or len(str(data['phone'])) != 10:
        return ('phone', 'Invalid phone!')
      
    # for checking Website URL
    if not re.search(Pattern_1, data['website']):
        return ('website', 'Invalid URL!')
        
    # for matching Passwords
    if data['pass'] != data['passes']:
        return ('passes', "Please make sure your passwords match")
  
  
# Taking input from the user
data = input_group("Fill out the form:", [
    input('Username', name='username', type=TEXT,
          required=True, PlaceHolder="@username"),
    
    input('Password', name='pass', type=PASSWORD,
          required=True, PlaceHolder="Password"),
    
    input('Confirm Password', name='passes', type=PASSWORD,
          required=True, PlaceHolder="Confirm Password"),
    
    input('Name', name='name', type=TEXT, required=True, 
          PlaceHolder="name"),
    
    input('Phone', name='phone', type=NUMBER,
          required=True, PlaceHolder="12345"),
    
    input('Email', name='email', type=TEXT,
          required=True, PlaceHolder="user@gmail.com"),
    
    input('Age', name='age', type=NUMBER, required=True,
          PlaceHolder="age"),
    
    input('Portfolio website', name='website', type=TEXT,
          required=True, PlaceHolder="www.XYZ.com")
    
], validate=check_form, cancelable=True)
  
# Create a radio button
gender = radio("Gender", options=['Male', 'Female'], required=True)
  
# Create a skills markdown
skills = select("Tech Stack", options=[
  'C Programming', 'Python', 'Web Development', 'Android Development'],
                required=True)
  
# Create a textarea
text = textarea("Comments/Questions", rows=3,
                placeholder="Write something...", required=True)
  
# Create a checkbox
agree = checkbox("Agreement", options=[
    'I agree to terms and conditions'], required=True)
  
# Display output using popup
popup("Your Details",
      f"Username: @{data['username']}\nName: {data['name']}\
      \nPhone: {str(data['phone'])}\nEmail: {data['email']}\
      \nAge: {str(data['age'])}\nWebsite: {data['website']}\
      \nGender: {gender}\nSkill: {skills}\nComments: {text}",
      closable=True)

输出: