Skip to content

Latest commit

 

History

History
575 lines (417 loc) · 18.9 KB

工具.gui.web.md

File metadata and controls

575 lines (417 loc) · 18.9 KB

gui web 工具快速开发

一、库文件

pip install pywebio

二、input

from pywebio.input import *

inp = input("请填写一下信息")
sle = select("选择按钮", ['Option1', 'Option2'])
ckb = checkbox("Multiple Choices!", options=["a",'b','c','d'])
radio = radio("Select any one", options=['1', '2', '3'])
tar = textarea('Text Area', rows=3, placeholder='Multiple line text input')

# 输入框
input_res = input("please input your name:")
print('browser input is:', input_res)

# 密码框
pwd_res = input("please input your password:", type=PASSWORD)
print('password:', pwd_res)

# 下拉框
select_res = select("please select your city:", ['北京', '西安', '成都'])
print('your city is:', select_res)

# checkbox
checkbox_res = checkbox("please confirm the checkbox:",
                        options=['agree', 'disagree'])
print('checkbox:', checkbox_res)

# 文本框
text_res = textarea("please input what you want to say:",
                    rows=3, placeholder='...')
print('what you said is:', text_res)

# 文件上传
upload_res = file_upload(
    "please upload what you want to upload:", accept="image/*")

with open(upload_res.get('filename'), mode='wb') as f:  # 因为读取的图片内容是二进制,所以要以wb模式打开
    f.write(upload_res.get('content'))
print('what you uploaded is:', upload_res.get('filename'))

# 滑动条

sld = slider('这是滑动条', help_text='请滑动选择')  # 缺点是不能显示当前滑动的值
toast('提交成功')
print(sld)

# 单选选项

radio_res = radio(
    '这是单选',
    options=['西安', '北京', '成都']
)
print(radio_res)

# 更新输入项

Country2City = {
    'China': ['西安', '北京', '成都'],
    'USA': ['纽约', '芝加哥', '佛罗里达'],
}

countries = list(Country2City.keys())

update_res = input_group(
    "国家和城市联动",
    [
        # 当国家发生变化的时候,onchange触发input_update方法去更新name=city的选项,更新内容为Country2City[c],c代表国家的选项值
        select('国家', options=countries, name='country',
               onchange=lambda c: input_update('city', options=Country2City[c])),
        select('城市', options=Country2City[countries[0]], name='city')
    ]
)

print(update_res)
print(inp)
print(sle)
print(ckb)
print(radio)
print(tar)
---------------------------------------------------------------------------

SessionClosedException                    Traceback (most recent call last)

/var/folders/w6/9k4dzqlj617f06dfby_vk1pr0000gn/T/ipykernel_4568/3387241143.py in <module>
      1 from pywebio.input import *
      2 
----> 3 inp = input("请填写一下信息")
      4 sle = select("选择按钮", ['Option1', 'Option2'])
      5 ckb = checkbox("Multiple Choices!", options=["a",'b','c','d'])


/usr/local/anaconda3/envs/py39/lib/python3.9/site-packages/pywebio/input.py in input(label, type, validate, name, value, action, onchange, placeholder, required, readonly, datalist, help_text, **other_html_attrs)
    254         return d
    255 
--> 256     return single_input(item_spec, valid_func, preprocess_func, onchange_func)
    257 
    258 


/usr/local/anaconda3/envs/py39/lib/python3.9/site-packages/pywebio/session/__init__.py in inner(*args, **kwargs)
    281             return to_coroutine(gen)
    282         else:
--> 283             return run_as_function(gen)
    284 
    285     return inner


/usr/local/anaconda3/envs/py39/lib/python3.9/site-packages/pywebio/utils.py in run_as_function(gen)
    294     while 1:
    295         try:
--> 296             res = gen.send(res)
    297         except StopIteration as e:
    298             if len(e.args) == 1:


/usr/local/anaconda3/envs/py39/lib/python3.9/site-packages/pywebio/io_ctrl.py in single_input(item_spec, valid_func, preprocess_func, onchange_func)
    247 
    248     spec = dict(label=label, inputs=[item_spec])
--> 249     data = yield input_control(spec=spec,
    250                                preprocess_funcs={name: preprocess_func},
    251                                item_valid_funcs={name: valid_func},


/usr/local/anaconda3/envs/py39/lib/python3.9/site-packages/pywebio/session/__init__.py in inner(*args, **kwargs)
    281             return to_coroutine(gen)
    282         else:
--> 283             return run_as_function(gen)
    284 
    285     return inner


/usr/local/anaconda3/envs/py39/lib/python3.9/site-packages/pywebio/utils.py in run_as_function(gen)
    294     while 1:
    295         try:
--> 296             res = gen.send(res)
    297         except StopIteration as e:
    298             if len(e.args) == 1:


/usr/local/anaconda3/envs/py39/lib/python3.9/site-packages/pywebio/io_ctrl.py in input_control(spec, preprocess_funcs, item_valid_funcs, onchange_funcs, form_valid_funcs)
    265     :return:
    266     """
--> 267     send_msg('input_group', spec)
    268 
    269     data = yield input_event_handle(item_valid_funcs, form_valid_funcs, preprocess_funcs, onchange_funcs)


/usr/local/anaconda3/envs/py39/lib/python3.9/site-packages/pywebio/io_ctrl.py in send_msg(cmd, spec, task_id)
    203 
    204 def send_msg(cmd, spec=None, task_id=None):
--> 205     msg = dict(command=cmd, spec=spec, task_id=task_id or get_current_task_id())
    206     get_current_session().send_task_command(msg)
    207 


/usr/local/anaconda3/envs/py39/lib/python3.9/site-packages/pywebio/session/__init__.py in get_current_task_id()
    239 
    240 def get_current_task_id():
--> 241     return get_session_implement().get_current_task_id()
    242 
    243 


/usr/local/anaconda3/envs/py39/lib/python3.9/site-packages/pywebio/session/threadbased.py in get_current_task_id(cls)
    306     def get_current_task_id(cls):
    307         task_id = super().get_current_task_id()
--> 308         session = cls.get_current_session()
    309         if task_id not in session.task_mqs:
    310             session.register_thread(threading.current_thread())


/usr/local/anaconda3/envs/py39/lib/python3.9/site-packages/pywebio/session/threadbased.py in get_current_session(cls)
    300             raise SessionNotFoundException("Can't find current session. It might be a bug.")
    301         if cls.instance.closed():
--> 302             raise SessionClosedException()
    303         return cls.instance
    304 


SessionClosedException: 

三、 output

from pywebio.output import *
from pywebio import session

# 网页上显示纯文本
put_text("Hello friend!")

# 网页上显示表格
put_table([
    ['Object', 'Unit'],
    ['A', '55'],
    ['B', '73'],
])

# 网页上显示 MarkDown
put_markdown('~~PyWebIO~~')

# 网页上显示下载文件的链接
put_file('text.txt', b'You can put anything here')

# 网页上显示图片
put_image(open('test.png', 'rb').read())

# 下载内容
put_button('Click to download', lambda: session.download(
    './text.txt', b'hello world!'))

# 按钮输出
put_buttons(
    buttons=['A', 'B'],
    onclick=toast
)

# 网页上显示弹窗
# popup('popup title', 'popup text content')
---------------------------------------------------------------------------

SessionClosedException                    Traceback (most recent call last)

/var/folders/w6/9k4dzqlj617f06dfby_vk1pr0000gn/T/ipykernel_4568/3179816299.py in <module>
      3 
      4 # 网页上显示纯文本
----> 5 put_text("Hello friend!")
      6 
      7 # 网页上显示表格


/usr/local/anaconda3/envs/py39/lib/python3.9/site-packages/pywebio/output.py in put_text(sep, inline, scope, position, *texts)
    383     """
    384     content = sep.join(str(i) for i in texts)
--> 385     spec = _get_output_spec('text', content=content, inline=inline, scope=scope, position=position)
    386     return Output(spec)
    387 


/usr/local/anaconda3/envs/py39/lib/python3.9/site-packages/pywebio/output.py in _get_output_spec(type, scope, position, **other_spec)
    358 
    359     if not scope:
--> 360         scope_name = get_scope()
    361     else:
    362         scope_name = scope


/usr/local/anaconda3/envs/py39/lib/python3.9/site-packages/pywebio/output.py in get_scope(stack_idx)
    298     """
    299     try:
--> 300         return get_current_session().get_scope_name(stack_idx)
    301     except IndexError:
    302         logger.exception("Scope stack index error")


/usr/local/anaconda3/envs/py39/lib/python3.9/site-packages/pywebio/session/__init__.py in get_current_session()
    235 
    236 def get_current_session() -> "Session":
--> 237     return get_session_implement().get_current_session()
    238 
    239 


/usr/local/anaconda3/envs/py39/lib/python3.9/site-packages/pywebio/session/threadbased.py in get_current_session(cls)
    300             raise SessionNotFoundException("Can't find current session. It might be a bug.")
    301         if cls.instance.closed():
--> 302             raise SessionClosedException()
    303         return cls.instance
    304 


SessionClosedException: 

四、高级用法

import time

# ========================== 1-输入框的参数 ==============================

# input的更多参数
ipt = input(
    'This is label',
    type=TEXT,
    placeholder='This is placeholder',  # 占位
    help_text='This is help text',  # 提示
    required=True,                  # 必填
    datalist=['a1', 'b2', 'c3'])    # 常驻输入联想
print('what you input is:',ipt)

# =========================== 2-输入框自定义校验 =============================

# input的合法性校验
# 自定义校验函数

def check_age(n):
    if n<1:
        return "Too Small!@"
    if n>100:
        return "Too Big!@"
    else:
        pass

myAge = input('please input your age:',type=NUMBER,validate=check_age,help_text='must in 1,100')
print('myAge is:',myAge)

# ============================ 3-代码编辑 ============================

# textare的代码模式

code = textarea(
    label='这是代码模式',
    code={
        'mode':'python',
        'theme':'darcula',
    },
    value='import time\n\ntime.sleep(2)'
    )
print('code is:',code)

# ============================== 4-输入组 ==========================

def check_age(n):
    if n<1:
        return "Too Small!@"
    if n>100:
        return "Too Big!@"
    else:
        pass

def check_form(datas):
    print(datas)
    if datas.get("age")==1:
        #return 'you are only one years old!'
        return ('age','you are only one years old!')
    if len(datas.get("name"))<=3:
        return ('name','Name Too short!!!')

# 输入组
datas = input_group(
    "It's input groups...",
    inputs=[
        input('please input name',name='name'),
        input('please input age',name='age',type=NUMBER,validate=check_age)
    ],
    validate=check_form
    )

# ====================================== 5-输入框的action =========================================


def set_today(set_value):
    set_value(time.time())
    print(time.time())

tt = input('选择时间',action=('Today',set_today),readonly=True)
print(tt)

# ====================================== 5-输入框的弹窗 =========================================

def set_some(set_value):  # 此方法可以将选择的英文转换为中文
    with popup('It is popup'):    # popup 是 output 模块中的方法
        put_buttons(['Today','Tomorrow'],onclick=[lambda: set_value('今天','Today1'),lambda:set_value('明天','Tomorrow2')])   # set_value('今天','Today') 按Today的按钮输入Today1,实际对应:今天
        put_buttons(['Exit'],onclick=lambda _: close_popup())

pp = input('go popup',type=TEXT,action=('按钮弹窗',set_some))
print(pp)
---------------------------------------------------------------------------

SessionClosedException                    Traceback (most recent call last)

/var/folders/w6/9k4dzqlj617f06dfby_vk1pr0000gn/T/ipykernel_4568/1531760145.py in <module>
      4 
      5 # input的更多参数
----> 6 ipt = input(
      7     'This is label',
      8     type=TEXT,


/usr/local/anaconda3/envs/py39/lib/python3.9/site-packages/pywebio/input.py in input(label, type, validate, name, value, action, onchange, placeholder, required, readonly, datalist, help_text, **other_html_attrs)
    254         return d
    255 
--> 256     return single_input(item_spec, valid_func, preprocess_func, onchange_func)
    257 
    258 


/usr/local/anaconda3/envs/py39/lib/python3.9/site-packages/pywebio/session/__init__.py in inner(*args, **kwargs)
    281             return to_coroutine(gen)
    282         else:
--> 283             return run_as_function(gen)
    284 
    285     return inner


/usr/local/anaconda3/envs/py39/lib/python3.9/site-packages/pywebio/utils.py in run_as_function(gen)
    294     while 1:
    295         try:
--> 296             res = gen.send(res)
    297         except StopIteration as e:
    298             if len(e.args) == 1:


/usr/local/anaconda3/envs/py39/lib/python3.9/site-packages/pywebio/io_ctrl.py in single_input(item_spec, valid_func, preprocess_func, onchange_func)
    247 
    248     spec = dict(label=label, inputs=[item_spec])
--> 249     data = yield input_control(spec=spec,
    250                                preprocess_funcs={name: preprocess_func},
    251                                item_valid_funcs={name: valid_func},


/usr/local/anaconda3/envs/py39/lib/python3.9/site-packages/pywebio/session/__init__.py in inner(*args, **kwargs)
    281             return to_coroutine(gen)
    282         else:
--> 283             return run_as_function(gen)
    284 
    285     return inner


/usr/local/anaconda3/envs/py39/lib/python3.9/site-packages/pywebio/utils.py in run_as_function(gen)
    294     while 1:
    295         try:
--> 296             res = gen.send(res)
    297         except StopIteration as e:
    298             if len(e.args) == 1:


/usr/local/anaconda3/envs/py39/lib/python3.9/site-packages/pywebio/io_ctrl.py in input_control(spec, preprocess_funcs, item_valid_funcs, onchange_funcs, form_valid_funcs)
    265     :return:
    266     """
--> 267     send_msg('input_group', spec)
    268 
    269     data = yield input_event_handle(item_valid_funcs, form_valid_funcs, preprocess_funcs, onchange_funcs)


/usr/local/anaconda3/envs/py39/lib/python3.9/site-packages/pywebio/io_ctrl.py in send_msg(cmd, spec, task_id)
    203 
    204 def send_msg(cmd, spec=None, task_id=None):
--> 205     msg = dict(command=cmd, spec=spec, task_id=task_id or get_current_task_id())
    206     get_current_session().send_task_command(msg)
    207 


/usr/local/anaconda3/envs/py39/lib/python3.9/site-packages/pywebio/session/__init__.py in get_current_task_id()
    239 
    240 def get_current_task_id():
--> 241     return get_session_implement().get_current_task_id()
    242 
    243 


/usr/local/anaconda3/envs/py39/lib/python3.9/site-packages/pywebio/session/threadbased.py in get_current_task_id(cls)
    306     def get_current_task_id(cls):
    307         task_id = super().get_current_task_id()
--> 308         session = cls.get_current_session()
    309         if task_id not in session.task_mqs:
    310             session.register_thread(threading.current_thread())


/usr/local/anaconda3/envs/py39/lib/python3.9/site-packages/pywebio/session/threadbased.py in get_current_session(cls)
    300             raise SessionNotFoundException("Can't find current session. It might be a bug.")
    301         if cls.instance.closed():
--> 302             raise SessionClosedException()
    303         return cls.instance
    304 


SessionClosedException: 

五、校验

from pywebio.input import *
from pywebio.output import *
from pywebio.pin import *
from pywebio import start_server

def input_input():
    # input的合法性校验
    # 自定义校验函数

    def check_age(n):
        if n<1:
            return "Too Small!@"
        if n>100:
            return "Too Big!@"
        else:
            pass

    myAge = input('please input your age:',type=NUMBER,validate=check_age,help_text='must in 1,100')
    print('myAge is:',myAge)

if __name__ == '__main__':
    start_server(
        applications=[input_input,],
        debug=True,
        auto_open_webbrowser=True,
        remote_access=True,
        )
---------------------------------------------------------------------------

RuntimeError                              Traceback (most recent call last)

/var/folders/w6/9k4dzqlj617f06dfby_vk1pr0000gn/T/ipykernel_4568/1331053308.py in <module>
     20 
     21 if __name__ == '__main__':
---> 22     start_server(
     23         applications=[input_input,],
     24         debug=True,


/usr/local/anaconda3/envs/py39/lib/python3.9/site-packages/pywebio/platform/tornado.py in start_server(applications, port, host, debug, cdn, static_dir, remote_access, reconnect_timeout, allowed_origins, check_origin, auto_open_webbrowser, max_payload_size, **tornado_app_settings)
    352         tornado_app_settings['websocket_max_message_size'])
    353     tornado_app_settings['debug'] = debug
--> 354     handler = webio_handler(applications, cdn, allowed_origins=allowed_origins, check_origin=check_origin,
    355                             reconnect_timeout=reconnect_timeout)
    356     _, port = _setup_server(webio_handler=handler, port=port, host=host, static_dir=static_dir,


/usr/local/anaconda3/envs/py39/lib/python3.9/site-packages/pywebio/platform/tornado.py in webio_handler(applications, cdn, reconnect_timeout, allowed_origins, check_origin)
    235     applications = make_applications(applications)
    236     for target in applications.values():
--> 237         register_session_implement_for_target(target)
    238 
    239     cdn = cdn_validation(cdn, 'error')  # if CDN is not available, raise error


/usr/local/anaconda3/envs/py39/lib/python3.9/site-packages/pywebio/session/__init__.py in register_session_implement_for_target(target_func)
    197 
    198     if ScriptModeSession in _active_session_cls:
--> 199         raise RuntimeError("Already in script mode, can't start server")
    200 
    201     if cls not in _active_session_cls:


RuntimeError: Already in script mode, can't start server

参考文档