diff --git a/.gitignore b/.gitignore index 9be43b8..ab59a67 100644 --- a/.gitignore +++ b/.gitignore @@ -13,6 +13,7 @@ *.csv .* +venv/ test/ data/ build/ diff --git a/Dash/components.py b/Dash/components.py deleted file mode 100644 index 844a2fc..0000000 --- a/Dash/components.py +++ /dev/null @@ -1,118 +0,0 @@ -# _*_ coding: utf-8 _*_ - -""" -定义通用组件 -""" - -import dash_core_components as dcc -import dash_html_components as html -import dash_bootstrap_components as dbc -from Dash.config import * - -# --------------------------------------------------------------------------------------- -drop_down_list = [ - dbc.DropdownMenuItem("First"), - dbc.DropdownMenuItem(divider=True), - dbc.DropdownMenuItem("Links", header=True), - dbc.DropdownMenuItem("Internal link", href="/l/components/alerts"), - dbc.DropdownMenuItem("External link", href="https://baidu.com"), - dbc.DropdownMenuItem(divider=True), - dbc.DropdownMenuItem("Disabled", disabled=True), - dbc.DropdownMenuItem("Active", active=True) -] - - -# --------------------------------------------------------------------------------------- -email_input = dbc.FormGroup(children=[ - dbc.Label("Email", html_for="example-email"), - dbc.Input(type="email", id="example-email", placeholder="Enter email"), - dbc.FormText("Are you on email? You simply have to be these days", color="secondary"), -]) - -password_input = dbc.FormGroup(children=[ - dbc.Label("Password", html_for="example-password"), - dbc.Input(type="password", id="example-password", placeholder="Enter password"), - dbc.FormText("A password stops mean people taking your stuff", color="secondary"), -]) - - -# --------------------------------------------------------------------------------------- -email_input_row = dbc.FormGroup(children=[ - dbc.Label("Email", html_for="example-email-row", width=2), - dbc.Col(dbc.Input(type="email", id="example-email-row", placeholder="Enter email"), width=10) -], row=True) - -password_input_row = dbc.FormGroup(children=[ - dbc.Label("Password", html_for="example-password-row", width=2), - dbc.Col(dbc.Input(type="password", id="example-password-row", placeholder="Enter password"), width=10) -], row=True) - - -# --------------------------------------------------------------------------------------- -radioitems = dbc.FormGroup(children=[ - dbc.Label("Choose one"), - dbc.RadioItems(options=[ - {"label": "Option 1", "value": 1}, - {"label": "Option 2", "value": 2}, - ], value=1) -], style={"backgroundColor": color_success_light}) - -checklist = dbc.FormGroup(children=[ - dbc.Label("Choose a bunch"), - dbc.Checklist(options=[ - {"label": "Option 1", "value": 1}, - {"label": "Option 2", "value": 2}, - ], values=[1, 2]), -], style={"backgroundColor": color_info_light}) - - -# --------------------------------------------------------------------------------------- -radioitems_inline = dbc.FormGroup(children=[ - dbc.Label("Choose one"), - dbc.RadioItems(options=[ - {"label": "Option 1", "value": 1}, - {"label": "Option 2", "value": 2}, - ], value=1, inline=True), -], style={"backgroundColor": color_success_light}) - -checklist_inline = dbc.FormGroup(children=[ - dbc.Label("Choose a bunch"), - dbc.Checklist(options=[ - {"label": "Option 1", "value": 1}, - {"label": "Option 2", "value": 2}, - ], values=[1, 2], inline=True), -], style={"backgroundColor": color_info_light}) - - -# --------------------------------------------------------------------------------------- -tab1_content = dbc.Card(children=dbc.CardBody([ - dbc.CardText("This is tab 1!"), - dbc.Button("Click here", color="success"), - ]) -) - -tab2_content = dbc.Card(children=dbc.CardBody([ - dbc.CardText("This is tab 2!"), - dbc.Button("Don't click here", color="danger"), - ]) -) - - -def generate_table(dataframe, max_rows=10): - """ - 创建表 - """ - # Header - header = html.Thead(children=html.Tr([html.Th(col) for col in dataframe.columns[:10]])) - - # Row - rows = [] - for i in range(max_rows): - td_list = [] - for index, col in enumerate(dataframe.columns[:10]): - if index == 1: - td_list.append(html.Td(dcc.Link(dataframe.iloc[i][col], href=dataframe.iloc[i][col]))) - else: - td_list.append(html.Td(dataframe.iloc[i][col])) - rows.append(html.Tr(td_list)) - return dbc.Table([header, html.Tbody(rows)], striped=True, bordered=True, hover=True) diff --git a/Dash/config.py b/Dash/config.py deleted file mode 100644 index 2192fb2..0000000 --- a/Dash/config.py +++ /dev/null @@ -1,27 +0,0 @@ -# _*_ coding: utf-8 _*_ - -""" -配置文件 -""" - -import pandas as pd - -# 定义颜色值 -color_primary, color_primary_light = "#2d7df6", "#d0e4fc" -color_secondary, color_secondary_light = "#6e757c", "#e2e3e5" -color_success, color_success_light = "#53a451", "#d9ecdb" -color_info, color_info_light = "#49a0b5", "#d6ebf0" -color_warning, color_warning_light = "#f6c244", "#fdf3d1" -color_danger, color_danger_light = "#cb444a", "#f3d8da" - -# 有用的数据 -df = pd.read_csv("Dash/data.csv") -markdown_text = """ -### Dash and Markdown - -Dash apps can be written in Markdown. -Dash uses the [CommonMark](http://commonmark.org/) -specification of Markdown. -Check out their [60 Second Markdown Tutorial](http://commonmark.org/help/) -if this is your first introduction to Markdown! -""" diff --git a/Dash/data.csv b/Dash/data.csv deleted file mode 100644 index cbbf300..0000000 --- a/Dash/data.csv +++ /dev/null @@ -1,51 +0,0 @@ -id,state,total exports,beef,pork,poultry,dairy,fruits fresh,fruits proc,total fruits,veggies fresh,veggies proc,total veggies,corn,wheat,cotton -0,Alabama,1390.63,34.4,10.6,481.0,4.06,8.0,17.1,25.11,5.5,8.9,14.33,34.9,70.0,317.61 -1,Alaska,13.31,0.2,0.1,0.0,0.19,0.0,0.0,0.0,0.6,1.0,1.56,0.0,0.0,0.0 -2,Arizona,1463.17,71.3,17.9,0.0,105.48,19.3,41.0,60.27,147.5,239.4,386.91,7.3,48.7,423.95 -3,Arkansas,3586.02,53.2,29.4,562.9,3.53,2.2,4.7,6.88,4.4,7.1,11.45,69.5,114.5,665.44 -4, California,16472.88,228.7,11.1,225.4,929.95,2791.8,5944.6,8736.4,803.2,1303.5,2106.79,34.6,249.3,1064.95 -5,Colorado,1851.33,261.4,66.0,14.0,71.94,5.7,12.2,17.99,45.1,73.2,118.27,183.2,400.5,0.0 -6,Connecticut,259.62,1.1,0.1,6.9,9.49,4.2,8.9,13.1,4.3,6.9,11.16,0.0,0.0,0.0 -7,Delaware,282.19,0.4,0.6,114.7,2.3,0.5,1.0,1.53,7.6,12.4,20.03,26.9,22.9,0.0 -8,Florida,3764.09,42.6,0.9,56.9,66.31,438.2,933.1,1371.36,171.9,279.0,450.86,3.5,1.8,78.24 -9,Georgia,2860.84,31.0,18.9,630.4,38.38,74.6,158.9,233.51,59.0,95.8,154.77,57.8,65.4,1154.07 -10,Hawaii,401.84,4.0,0.7,1.3,1.16,17.7,37.8,55.51,9.5,15.4,24.83,0.0,0.0,0.0 -11,Idaho,2078.89,119.8,0.0,2.4,294.6,6.9,14.7,21.64,121.7,197.5,319.19,24.0,568.2,0.0 -12,Illinois,8709.48,53.7,394.0,14.0,45.82,4.0,8.5,12.53,15.2,24.7,39.95,2228.5,223.8,0.0 -13,Indiana,5050.23,21.9,341.9,165.6,89.7,4.1,8.8,12.98,14.4,23.4,37.89,1123.2,114.0,0.0 -14,Iowa,11273.76,289.8,1895.6,155.6,107.0,1.0,2.2,3.24,2.7,4.4,7.1,2529.8,3.1,0.0 -15,Kansas,4589.01,659.3,179.4,6.4,65.45,1.0,2.1,3.11,3.6,5.8,9.32,457.3,1426.5,43.98 -16,Kentucky,1889.15,54.8,34.2,151.3,28.27,2.1,4.5,6.6,0.0,0.0,0.0,179.1,149.3,0.0 -17,Louisiana,1914.23,19.8,0.8,77.2,6.02,5.7,12.1,17.83,6.6,10.7,17.25,91.4,78.7,280.42 -18,Maine,278.37,1.4,0.5,10.4,16.18,16.6,35.4,52.01,24.0,38.9,62.9,0.0,0.0,0.0 -19,Maryland,692.75,5.6,3.1,127.0,24.81,4.1,8.8,12.9,7.8,12.6,20.43,54.1,55.8,0.0 -20,Massachusetts,248.65,0.6,0.5,0.6,5.81,25.8,55.0,80.83,8.1,13.1,21.13,0.0,0.0,0.0 -21,Michigan,3164.16,37.7,118.1,32.6,214.82,82.3,175.3,257.69,72.4,117.5,189.96,381.5,247.0,0.0 -22,Minnesota,7192.33,112.3,740.4,189.2,218.05,2.5,5.4,7.91,45.9,74.5,120.37,1264.3,538.1,0.0 -23,Mississippi,2170.8,12.8,30.4,370.8,5.45,5.4,11.6,17.04,10.6,17.2,27.87,110.0,102.2,494.75 -24,Missouri,3933.42,137.2,277.3,196.1,34.26,4.2,9.0,13.18,6.8,11.1,17.9,428.8,161.7,345.29 -25,Montana,1718.0,105.0,16.7,1.7,6.82,1.1,2.2,3.3,17.3,28.0,45.27,5.4,1198.1,0.0 -26,Nebraska,7114.13,762.2,262.5,31.4,30.07,0.7,1.5,2.16,20.4,33.1,53.5,1735.9,292.3,0.0 -27,Nevada,139.89,21.8,0.2,0.0,16.57,0.4,0.8,1.19,10.6,17.3,27.93,0.0,5.4,0.0 -28,New Hampshire,73.06,0.6,0.2,0.8,7.46,2.6,5.4,7.98,1.7,2.8,4.5,0.0,0.0,0.0 -29,New Jersey,500.4,0.8,0.4,4.6,3.37,35.0,74.5,109.45,21.6,35.0,56.54,10.1,6.7,0.0 -30,New Mexico,751.58,117.2,0.1,0.3,191.01,32.6,69.3,101.9,16.7,27.1,43.88,11.2,13.9,72.62 -31,New York,1488.9,22.2,5.8,17.7,331.8,64.7,137.8,202.56,54.7,88.7,143.37,106.1,29.9,0.0 -32,North Carolina,3806.05,24.8,702.8,598.4,24.9,23.8,50.7,74.47,57.4,93.1,150.45,92.2,200.3,470.86 -33,North Dakota,3761.96,78.5,16.1,0.5,8.14,0.1,0.2,0.25,49.9,80.9,130.79,236.1,1664.5,0.0 -34,Ohio,3979.79,36.2,199.1,129.9,134.57,8.7,18.5,27.21,20.4,33.1,53.53,535.1,207.4,0.0 -35,Oklahoma,1646.41,337.6,265.3,131.1,24.35,3.0,6.3,9.24,3.4,5.5,8.9,27.5,324.8,110.54 -36,Oregon,1794.57,58.8,1.4,14.2,63.66,100.7,214.4,315.04,48.2,78.3,126.5,11.7,320.3,0.0 -37,Pennsylvania,1969.87,50.9,91.3,169.8,280.87,28.6,60.9,89.48,14.6,23.7,38.26,112.1,41.0,0.0 -38,Rhode Island,31.59,0.1,0.1,0.2,0.52,0.9,1.9,2.83,1.2,1.9,3.02,0.0,0.0,0.0 -39,South Carolina,929.93,15.2,10.9,186.5,7.62,17.1,36.4,53.45,16.3,26.4,42.66,32.1,55.3,206.1 -40,South Dakota,3770.19,193.5,160.2,29.3,46.77,0.3,0.5,0.8,1.5,2.5,4.06,643.6,704.5,0.0 -41,Tennessee,1535.13,51.1,17.6,82.4,21.18,2.0,4.2,6.23,9.4,15.3,24.67,88.8,100.0,363.83 -42,Texas,6648.22,961.0,42.7,339.2,240.55,31.9,68.0,99.9,43.9,71.3,115.23,167.2,309.7,2308.76 -43,Utah,453.39,27.9,59.0,23.1,48.6,3.9,8.4,12.34,2.5,4.1,6.6,5.3,42.8,0.0 -44,Vermont,180.14,6.2,0.2,0.9,65.98,2.6,5.4,8.01,1.5,2.5,4.05,0.0,0.0,0.0 -45,Virginia,1146.48,39.5,16.9,164.7,47.85,11.7,24.8,36.48,10.4,16.9,27.25,39.5,77.5,64.84 -46,Washington,3894.81,59.2,0.0,35.6,154.18,555.6,1183.0,1738.57,138.7,225.1,363.79,29.5,786.3,0.0 -47,West Virginia,138.89,12.0,0.3,45.4,3.9,3.7,7.9,11.54,0.0,0.0,0.0,3.5,1.6,0.0 -48,Wisconsin,3090.23,107.3,38.6,34.5,633.6,42.8,91.0,133.8,56.8,92.2,148.99,460.5,96.7,0.0 -49,Wyoming,349.69,75.1,33.2,0.1,2.89,0.1,0.1,0.17,3.9,6.3,10.23,9.0,20.7,0.0 \ No newline at end of file diff --git a/Dash/demo.py b/Dash/demo.py deleted file mode 100644 index f211147..0000000 --- a/Dash/demo.py +++ /dev/null @@ -1,338 +0,0 @@ -# _*_ coding: utf-8 _*_ - -""" -Dash实例 -""" - -import dash -import datetime -from dash.dependencies import Output, Input, State -from Dash.components import * - - -# 创建应用 -app = dash.Dash(__name__, external_stylesheets=[dbc.themes.BOOTSTRAP]) -app.scripts.config.serve_locally = True - -# 创建布局 -app.layout = html.Div(children=[ - # DIV布局 ======================================================================================== - dbc.Row(children=dbc.Col(html.Div("单独的DIV", style={"backgroundColor": color_primary_light, "height": 100, "padding": 10, "margin": 5}))), - dbc.Row(children=[ - dbc.Col(html.Div("One of three columns", style={"backgroundColor": color_info_light, "padding": 10, "margin": 5})), - dbc.Col(html.Div("One of three columns", style={"backgroundColor": color_info_light, "padding": 10, "margin": 5})), - dbc.Col(html.Div("One of three columns", style={"backgroundColor": color_info_light, "padding": 10, "margin": 5})), - ], no_gutters=True), - - dbc.Row(children=dbc.Col(html.Div("A single, half-width column, width=6", style={"backgroundColor": color_primary_light, "margin": 5}), width=6)), - dbc.Row(children=dbc.Col(html.Div("An automatically sized column", style={"backgroundColor": color_secondary_light, "margin": 5}), width="auto")), - dbc.Row(children=[ - dbc.Col(html.Div("One of 4 columns", style={"backgroundColor": color_info_light, "padding": 10, "margin": 5}), width=3), - dbc.Col(html.Div("Two of 4 columns", style={"backgroundColor": color_info_light, "padding": 10, "margin": 5})), - dbc.Col(html.Div("One of 4 columns", style={"backgroundColor": color_info_light, "padding": 10, "margin": 5}), width=3), - ], no_gutters=True), - - html.Br(), html.Br(), - # 显示文字 ======================================================================================== - html.Div(children=[ - html.H1(children="Hello Dash H1"), - html.H2(children="Hello Dash H2"), - html.H3(children="Hello Dash H3"), - html.H4(children=["This is a heading with a badge! ", dbc.Badge("New!", color="success")]), - html.P(children=html.A(children="这是一个百度链接", href="http://baidu.com")), - html.Label(children="这是一个Lable"), - dcc.Markdown(children=markdown_text), - ], style={"margin": 5}), - - html.Div(children=[ - dbc.Alert("primary!", color="primary"), - dbc.Alert("secondary!", color="secondary"), - dbc.Alert("success!", color="success"), - dbc.Alert("info!", color="info"), - dbc.Alert("warning!", color="warning"), - dbc.Alert("danger!", color="danger"), - # dbc.Alert("link!", color="link"), - ], style={"margin": 5}), - - html.Br(), html.Br(), - # 卡片类 ======================================================================================== - html.Div(children=dbc.Row(children=[ - dbc.Col(children=dbc.Card([ - dbc.CardHeader("Header"), - dbc.CardBody([ - dbc.CardTitle("This card has a title"), - dbc.CardText("And some text"), - ]), - ])), - dbc.Col(children=dbc.Card([ - dbc.CardBody([ - dbc.CardTitle("This card has a title"), - dbc.CardText("and some text, but no header"), - ]), - ], outline=True, color="primary")), - dbc.Col(children=dbc.Card([ - dbc.CardBody([ - dbc.CardTitle("This card has a title"), - dbc.CardText("and some text, and a footer!"), - ]), - dbc.CardFooter("Footer"), - ], outline=True, color="danger")), - ]), style={"margin": 5}), - - html.Br(), html.Br(), - # 按钮触发类 ======================================================================================== - # className: mr-1, m代表margin,r代表right,1代表距离,一般用于一行中元素的排列(mt, mb, ml, mr) - html.Div(children=[ - dbc.Button("Primary", color="primary", className="mr-1"), - dbc.Button("Secondary", color="secondary", className="mr-2"), - dbc.Button("Success", color="success", className="mr-3"), - dbc.Button("Info", color="info", className="mr-4"), - dbc.Button("Warning", color="warning", className="mr-3"), - dbc.Button("Danger", color="danger", className="mr-2"), - dbc.Button("outline", outline=True), - ], style={"margin": 5}), - - html.Div(children=[ - dbc.Button("Open collapse", id="collapse-button"), - dbc.Collapse( - dbc.Card(dbc.CardBody("This content is hidden in the collapse")), - id="collapse" - ) - ], style={"margin": 5, "marginTop": 20}), - - html.Div(children=[ - dbc.Button("Toggle fade", id="fade-button"), - dbc.Fade( - dbc.Card(dbc.CardBody(dbc.CardText("This content fades in and out"))), - id="fade", - is_in=True, - appear=False, - ), - ], style={"margin": 5, "marginTop": 20}), - - html.Div(children=[ - html.P(["Click on the word ", html.Span("popover", id="popover-target")]), - dbc.Popover([ - dbc.PopoverHeader("Popover header"), - dbc.PopoverBody("Popover body"), - ], id="popover", is_open=False, target="popover-target"), - ], style={"margin": 5, "backgroundColor": color_secondary_light}), - - html.Div(children=[ - html.P([ - "I wonder what ", - html.Span("floccinaucinihilipilification", id="tooltip-target", style={"color": color_info}), - " means?", - ]), - dbc.Tooltip( - "Noun: rare, the action or habit of estimating something as worthless.", - target="tooltip-target", - placement="auto", # top, left, bottom, right - ), - ], style={"margin": 5}), - - html.Div(children=dcc.ConfirmDialogProvider( - id="confirm", - children=dbc.Button("ConfirmDialogProvider", color="primary"), - message="Danger danger! Are you sure you want to continue?" - ), style={"margin": 5, "marginBottom": 20}), - - html.Div(children=dbc.Row(children=[ - dbc.Col(dbc.DropdownMenu(label="Menu-md", bs_size="md", children=drop_down_list)), - dbc.Col(dbc.DropdownMenu(label="Menu-lg", bs_size="lg", children=drop_down_list)), - dbc.Col(dbc.DropdownMenu(label="Menu-sm", bs_size="sm", children=drop_down_list)), - dbc.Col(dbc.DropdownMenu(label="Menu-down", bs_size="md", direction="down", children=drop_down_list)), - dbc.Col(dbc.DropdownMenu(label="Menu-left", bs_size="md", direction="left", children=drop_down_list)), - dbc.Col(dbc.DropdownMenu(label="Menu-right", bs_size="md", direction="right", children=drop_down_list)), - dbc.Col(dcc.Dropdown(options=[ - {"label": "New York City", "value": "NYC"}, - {"label": u"Montréal", "value": "MTL"}, - {"label": "San Francisco", "value": "SF"} - ], value="MTL")), - dbc.Col(dcc.Dropdown(options=[ - {"label": "New York City", "value": "NYC"}, - {"label": u"Montréal", "value": "MTL"}, - {"label": "San Francisco", "value": "SF"} - ], value="MTL", multi=True), width=3) - ], no_gutters=True), style={"margin": 5, "backgroundColor": color_secondary_light}), - - html.Br(), html.Br(), - # 输入类 ======================================================================================== - html.Div(children=[ - dbc.Input(placeholder="A large input...", bs_size="lg", className="mb-3"), - dbc.Input(placeholder="A medium input...", className="mb-3"), - dbc.Input(placeholder="A small input...", bs_size="sm", className="mb-3"), - dbc.Input(placeholder="Valid input...", valid=True, className="mb-3"), - dbc.Input(placeholder="Invalid input...", invalid=True, className="mb-3"), - dbc.Input(value=10, type="number", className="mb-3"), - dcc.Textarea(placeholder="Enter a value...", style={"width": "50%"}), - ], style={"margin": 5}), - - html.Div(children=[ - dbc.InputGroup([ - dbc.InputGroupAddon("@", addon_type="prepend"), - dbc.Input(placeholder="username, size=lg"), - ], size="lg", className="mb-3"), - dbc.InputGroup([ - dbc.Input(placeholder="username, size=md"), - dbc.InputGroupAddon("@example.com", addon_type="append"), - ], className="mb-3"), - dbc.InputGroup([ - dbc.InputGroupAddon("$", addon_type="prepend"), - dbc.Input(placeholder="Amount, size=sm", type="number"), - dbc.InputGroupAddon(".00", addon_type="append"), - ], size="sm", className="mb-3"), - dbc.InputGroup([ - dbc.InputGroupAddon(dbc.Button("Random name", id="input-group-button"), addon_type="prepend"), - dbc.Input(id="input-group-button-input", placeholder="name"), - ], className="mb-3"), - dbc.InputGroup([ - dbc.DropdownMenu(drop_down_list, label="Generate", addon_type="prepend"), - dbc.Input(id="input-group-dropdown-input", placeholder="name"), - ]), - ], style={"margin": 5}), - - html.Br(), html.Br(), - # 表单类 ======================================================================================== - dbc.Form(children=[email_input, password_input], style={"margin": 5, "backgroundColor": color_secondary_light}), - dbc.Form(children=[email_input_row, password_input_row], style={"margin": 5, "backgroundColor": color_secondary_light}), - dbc.Form(children=[ - dbc.FormGroup([ - dbc.Label("Email", className="mr-2"), - dbc.Input(type="email", placeholder="Enter email") - ], className="mr-3"), - dbc.FormGroup([ - dbc.Label("Password", className="mr-2"), - dbc.Input(type="password", placeholder="Enter password") - ], className="mr-3"), - dbc.FormGroup([ - dbc.Label("Date", className="mr-2"), - dbc.DatePickerSingle(id="date-picker-inline", date=datetime.date(2018, 10, 17)) - ], className="mr-3"), - dbc.FormGroup([ - dbc.Label("Date", className="mr-2"), - dcc.DatePickerRange(id="date-picker-range", start_date=datetime.datetime(1997, 5, 3), end_date_placeholder_text="Select!") - ], className="mr-3"), - ], inline=True, style={"margin": 5, "backgroundColor": color_secondary_light}), - - html.Br(), html.Br(), - # 表单类 ======================================================================================== - html.Div(children=[ - dbc.Label("Slider", html_for="slider"), - dcc.Slider(min=0, max=9, marks={i: "Label {}".format(i) if i == 1 else str(i) for i in range(1, 6)}, value=5), - html.Br(), - dbc.Label("RangeSlider", html_for="range-slider"), - dcc.RangeSlider(count=1, min=-5, max=10, step=0.5, value=[-3, 7]) - ], style={"margin": 5}), - - html.Div(children=[ - dbc.Label("Progress", html_for="progress"), - dbc.Progress(id="progress", value=0, striped=True, animated=True), - dcc.Interval(id="interval", interval=250, n_intervals=0), - ], style={"margin": 5}), - html.Div(children=[radioitems, checklist, radioitems_inline, checklist_inline], style={"margin": 5}), - - html.Br(), html.Br(), - # 展示类 ======================================================================================== - dbc.ListGroup(children=[ - dbc.ListGroupItem("ListGroupItem ListGroupItem"), - dbc.ListGroupItem("Internal link", href="/l/components/list_group"), - dbc.ListGroupItem("External link", href="https://google.com"), - dbc.ListGroupItem("Disabled link", href="https://google.com", disabled=True), - dbc.ListGroupItem("Button", id="button-item", n_clicks=0, action=True), - ], style={"margin": 5}), - - dbc.ListGroup(children=[ - dbc.ListGroupItem("The primary item", color="primary"), - dbc.ListGroupItem("A secondary item", color="secondary"), - dbc.ListGroupItem("A successful item", color="success"), - dbc.ListGroupItem("A warning item", color="warning"), - dbc.ListGroupItem("A dangerous item", color="danger"), - dbc.ListGroupItem("An informative item", color="info"), - ], style={"margin": 5}), - - dbc.ListGroup(children=[ - dbc.ListGroupItem([ - dbc.ListGroupItemHeading("This item has a heading"), - dbc.ListGroupItemText("And some text underneath"), - ]), - dbc.ListGroupItem([ - dbc.ListGroupItemHeading("This item also has a heading"), - dbc.ListGroupItemText("And some more text underneath too"), - ]), - ], style={"margin": 5}), - - html.Br(), html.Br(), - # Tab实例 ======================================================================================== - html.Div(children=dbc.Tabs([ - dbc.Tab(tab1_content, label="Tab 1"), - dbc.Tab(tab2_content, label="Tab 2"), - ]), style={"margin": 5, "backgroundColor": color_secondary_light}), - - html.Div(children=[ - dbc.Tabs([ - dbc.Tab(label="Tab 1", tab_id="tab-1"), - dbc.Tab(label="Tab 2", tab_id="tab-2"), - ], id="tabs", active_tab="tab-1"), - html.Div(id="content") - ], style={"margin": 5, "backgroundColor": color_secondary_light}), - - html.Br(), html.Br(), - # 表格Table ======================================================================================== - html.Div(children=generate_table(df), style={"margin": 5}), -]) - - -@app.callback(Output("collapse", "is_open"), [ - Input("collapse-button", "n_clicks") -], [ - State("collapse", "is_open") -]) -def toggle_collapse(n, is_open): - if n: - return not is_open - return is_open - - -@app.callback(Output("fade", "is_in"), [ - Input("fade-button", "n_clicks") -], [ - State("fade", "is_in") -]) -def toggle_fade(n, is_in): - if not n: - return True - return not is_in - - -@app.callback(Output("popover", "is_open"), [ - Input("popover-target", "n_clicks") -], [ - State("popover", "is_open") -]) -def toggle_popover(n, is_open): - if n: - return not is_open - return is_open - - -@app.callback(Output("progress", "value"), [ - Input("interval", "n_intervals") -]) -def advance_progress(n): - return min(n % 110, 100) - - -@app.callback(Output("content", "children"), [ - Input("tabs", "active_tab") -]) -def switch_tab(at): - if at == "tab-1": - return tab1_content - elif at == "tab-2": - return tab2_content - return html.P("This shouldn't ever be displayed...") - - -if __name__ == "__main__": - app.run_server(host="0.0.0.0", debug=True) diff --git a/Docker/Dockerfile b/Docker/Dockerfile deleted file mode 100644 index eefdf54..0000000 --- a/Docker/Dockerfile +++ /dev/null @@ -1,66 +0,0 @@ -# Dockerfile by xianhu: build a docker image -# centos6: -# docker build -t user/centos6 . -# docker run -it --name test [-p -v] user/centos6 -# docker attach test -# centos7: -# docker build -t user/centos7 . -# docker run -dt --privileged --name test [-p -v] user/centos7 -# docker exec -it test /bin/bash - -FROM centos:6.9 -MAINTAINER xianhu - -# change system environments -ENV LANG en_US.UTF-8 -ENV LC_ALL en_US.UTF-8 - -# change system local time -RUN ln -sf /usr/share/zoneinfo/Asia/Shanghai /etc/localtime - -# fix: warning: rpmts_HdrFromFdno -RUN rpm --import /etc/pki/rpm-gpg/RPM* - -# update yum and install something -RUN yum update -y -RUN yum install -y xz -RUN yum install -y vim -RUN yum install -y git -RUN yum install -y gcc -RUN yum install -y make -RUN yum install -y wget -RUN yum install -y screen -RUN yum install -y gcc-c++ -RUN yum install -y crontabs -RUN yum install -y zlib-devel -RUN yum install -y sqlite-devel -RUN yum install -y openssl-devel - -# install python -RUN yum install -y https://centos6.iuscommunity.org/ius-release.rpm -# RUN yum install -y https://centos7.iuscommunity.org/ius-release.rpm -RUN yum install -y python36u -RUN yum install -y python36u-pip -RUN yum install -y python36u-devel - -# install nginx -RUN yum install -y epel-release -RUN yum install -y nginx - -# clean yum cache -RUN yum clean all - -# install libs of python3 -ADD ./requirements.txt /root/ -WORKDIR /root/ -RUN pip3.6 install --upgrade pip -RUN pip3.6 install -r requirements.txt - -# clean everything -RUN rm -rf /root/* - -# centos6 -CMD /bin/bash - -# centos7 -# ENTRYPOINT /usr/sbin/init diff --git a/Docker/requirements.txt b/Docker/requirements.txt deleted file mode 100644 index 91a545e..0000000 --- a/Docker/requirements.txt +++ /dev/null @@ -1,34 +0,0 @@ -virtualenv -pylint -lxml -html5lib -xmltodict -pybloom_live -fake-useragent -beautifulsoup4 -aiohttp -requests -websocket-client -redis -PyMySQL -elasticsearch -Flask -Flask-WTF -Flask-Mail -Flask-Login -Flask-Moment -Flask-Script -Flask-RESTful -Flask-Migrate -Flask-HTTPAuth -Flask-Bootstrap -Flask-SQLAlchemy -gunicorn -uWSGI -numpy -scipy -pandas -scikit-learn -matplotlib -plotly -jupyter diff --git a/README.md b/README.md index ce18449..812e234 100644 --- a/README.md +++ b/README.md @@ -56,7 +56,18 @@ ### python_numpy.py: 使用numpy进行矩阵操作 +### python_mail.py: 使用Python自动发送邮件,包括发送HTML以及图片、附件等 + +### python_redis.py: Python操作Redis实现消息的发布与订阅 + +### python_schedule.py: Python进行调度开发 + +### python_socket.py: Python的socket开发实例 + +### python_re.py:Python的re模块的主要功能以及如何使用它们进行字符串匹配和替换 + ### Plotly目录: 一些plotly画图的实例,使用jupyter notebook编写 + =================================================================================================== ### 您可以fork该项目, 并在修改后提交Pull request, 看到后会尽量进行代码合并 diff --git a/python_base.py b/python_base.py index 45def87..9b5e605 100644 --- a/python_base.py +++ b/python_base.py @@ -292,7 +292,7 @@ def __missing__(self, key): #-- 元组和列表的唯一区别在于元组是不可变对象,列表是可变对象 a = [1, 2, 3] # a[1] = 0, OK a = (1, 2, 3) # a[1] = 0, Error - a = ([1, 2]) # a[0][1] = 0, OK + a = ([1, 2],) # a[0][1] = 0, OK a = [(1, 2)] # a[0][1] = 0, Error #-- 元组的特殊语法: 逗号和圆括号 diff --git a/python_celery.py b/python_celery.py new file mode 100644 index 0000000..f7c8f9a --- /dev/null +++ b/python_celery.py @@ -0,0 +1,23 @@ +# _*_ coding: utf-8 _*_ + +""" +测试celery +终端运行:celery -A python_celery:app worker -l INFO +""" + +import time + +from celery import Celery + +broker = "redis://localhost:6379/10" # 用redis做broker,中间件 +backend = "redis://localhost:6379/11" # 用redis做broken,用来保存结果 + +app = Celery("tasks", broker=broker, backend=backend) + + +@app.task +def add(x, y): + print(time.time(), x, y) + time.sleep(3) + print(time.time(), x, y, "--") + return x + y diff --git a/python_celery_test.py b/python_celery_test.py new file mode 100644 index 0000000..f3d1dbc --- /dev/null +++ b/python_celery_test.py @@ -0,0 +1,18 @@ +# _*_ coding: utf-8 _*_ + +""" +测试 +""" + +import time + +from python_celery import add + +if __name__ == "__main__": + result = [] + for i in range(10): + result.append(add.delay(i, i)) + print("----", time.time()) + for index, item in enumerate(result): + print(index, item.get()) + print("----", time.time()) diff --git a/python_mail.py b/python_mail.py new file mode 100644 index 0000000..a57049a --- /dev/null +++ b/python_mail.py @@ -0,0 +1,71 @@ +# _*_ coding: utf-8 _*_ + +""" +python发送邮件 +""" + +import smtplib +from email.header import Header +from email.mime.text import MIMEText +from email.mime.image import MIMEImage +from email.mime.multipart import MIMEMultipart + +# 第三方 SMTP 服务(以腾讯企业邮件和QQ邮箱为例) +mail_host = "smtp.exmail.qq.com" +# mail_host = "smtp.qq.com" +mail_user = "from@from.com.cn" +# mail_user = "from@qq.com" +mail_pass = "授权码" +mail_sender = mail_user +mail_port = 465 +mail_receivers = ["to@to.com", "to@qq.com"] + +# 设置邮件格式、内容等 -- 普通格式 ================================================ +message = MIMEText("邮件内容", "plain", "utf-8") + +# 设置邮件格式、内容等 -- HTML格式 =============================================== +msg_html = """ +

Python 邮件发送测试...

+

这是一个链接

+ + + + +
MonthSavings
January$100
February$80
+""" +message = MIMEText(msg_html, "html", "utf-8") + +# 设置邮件格式、内容等 -- HTML格式(带有图片和附件)================================== +msg_html = """ +

Python 邮件发送测试...

+

这是一个链接

+

图片演示:

+

+""" +msg_content = MIMEText(msg_html, "html", "utf-8") +msg_image = MIMEImage(open("test.png", "rb").read()) +msg_image.add_header("Content-ID", "") + +msg_file = MIMEText(open("test.csv", "rb").read(), "base64", "utf-8") +msg_file["Content-Type"] = "application/octet-stream" +msg_file["Content-Disposition"] = "attachment; filename=\"test.csv\"" + +message = MIMEMultipart("related") +message.attach(msg_content) +message.attach(msg_image) +message.attach(msg_file) +# ============================================================================== + +# 设置邮件的收发件、标题等 +message["From"] = mail_sender +message["To"] = ";".join(mail_receivers) +message["Subject"] = Header("邮件标题", "utf-8") + +try: + # 登录,并发送邮件 + smtpObj = smtplib.SMTP_SSL(mail_host, mail_port) + smtpObj.login(mail_user, mail_pass) + smtpObj.sendmail(mail_sender, mail_receivers, message.as_string()) + print("success") +except smtplib.SMTPException as excep: + print("error", excep) diff --git a/python_re.py b/python_re.py new file mode 100644 index 0000000..4e548f6 --- /dev/null +++ b/python_re.py @@ -0,0 +1,83 @@ +import re + +#-- 基本正则表达式语法 +''' +.:匹配除换行符以外的任意字符。 +^:匹配字符串的开始。 +$:匹配字符串的结束。 +*:匹配前一个字符0次或多次。 ++:匹配前一个字符1次或多次。 +?:匹配前一个字符0次或1次。 +{m}:匹配前一个字符m次。 +{m,n}:匹配前一个字符至少m次,至多n次。 +[abc]:匹配字符集合中的任意一个字符(例如a、b或c)。 +[^abc]:匹配不在字符集合中的任意字符。 +|:表示“或”关系,匹配符号前后的任意一个表达式。 +():用于分组,可以提取匹配的部分。 +\d:匹配任意数字,等价于[0-9]。 +\D:匹配任意非数字字符,等价于[^0-9]。 +\w:匹配任意字母数字字符,包括下划线,等价于[a-zA-Z0-9_]。 +\W:匹配任意非字母数字字符,等价于[^a-zA-Z0-9_]。 +\s:匹配任意空白字符,包括空格、制表符、换行符等。 +\S:匹配任意非空白字符。 +''' + +#-- re 模块的主要函数 +re.match(pattern, string, flags=0) # 尝试从字符串的起始位置匹配正则表达式,如果匹配成功,返回一个匹配对象;否则返回None。 +re.search(pattern, string, flags=0) # 扫描整个字符串,返回第一个成功匹配的对象;否则返回None。 +re.findall(pattern, string, flags=0) # 在字符串中找到所有与正则表达式匹配的非重叠匹配项,并返回一个列表。 +re.finditer(pattern, string, flags=0) # 与findall类似,但返回的是一个迭代器,每个迭代元素都是一个匹配对象。 +re.sub(pattern, repl, string, count=0, flags=0) # 使用repl替换string中所有与pattern匹配的子串,count表示替换的最大次数。 +re.subn(pattern, repl, string, count=0, flags=0) # 功能与sub相同,但返回一个元组,包含替换后的字符串和替换的总次数。 +re.split(pattern, string, maxsplit=0, flags=0) # 根据正则表达式的模式分割字符串,maxsplit表示分割的最大次数。 +re.escape(string) # 对字符串中的非字母数字字符进行转义,使其可以安全地用于正则表达式中。 + +#-- 示例代码1 +# 匹配字符串的开始 +match_obj = re.match(r'^Hello', 'Hello World') +if match_obj: + print("Match found:", match_obj.group()) +else: + print("No match") + +# 搜索字符串 +search_obj = re.search(r'World', 'Hello World') +if search_obj: + print("Search found:", search_obj.group()) +else: + print("No search match") + +# 查找所有匹配项 +findall_result = re.findall(r'\d+', 'There are 42 apples and 33 oranges') +print("Findall result:", findall_result) + +# 替换匹配项 +sub_result = re.sub(r'\d+', 'many', 'There are 42 apples and 33 oranges') +print("Sub result:", sub_result) + +# 分割字符串 +split_result = re.split(r'\s+', 'Hello World this is Python') +print("Split result:", split_result) + +# 转义字符串 +escaped_string = re.escape('Hello? World!') +print("Escaped string:", escaped_string) + +#-- 标志位(flags) +re.IGNORECASE # 忽略大小写。 +re.MULTILINE # 多行模式,改变^和$的行为。 +re.DOTALL # 让.匹配包括换行符在内的所有字符。 +re.VERBOSE # 允许正则表达式包含空白和注释,使其更易于阅读。 + +#-- 示例代码2 +pattern = re.compile(r''' + \d+ # 匹配一个或多个数字 + \. # 匹配小数点 + \d+ # 匹配一个或多个数字 +''', re.VERBOSE) + +match_obj = pattern.match('123.456') +if match_obj: + print("Match found:", match_obj.group()) +else: + print("No match") \ No newline at end of file diff --git a/python_redis.py b/python_redis.py new file mode 100644 index 0000000..a853875 --- /dev/null +++ b/python_redis.py @@ -0,0 +1,55 @@ +# _*_ coding: utf-8 _*_ + +""" +Python操作Redis实现消息的发布与订阅 +""" + +import sys +import time +import redis + +# 全局变量 +conn_pool = redis.ConnectionPool(host="localhost", port=6379, db=1) +conn_inst = redis.Redis(connection_pool=conn_pool) +channel_name = "fm-101.1" + + +def public_test(): + while True: + # 发布消息 + conn_inst.publish(channel_name, "hello " + str(time.time())) + if int(time.time()) % 10 == 1: + conn_inst.publish(channel_name, "over") + time.sleep(1) + + +def subscribe_test(_type=0): + pub = conn_inst.pubsub() + pub.subscribe(channel_name) + + if _type == 0: + # 订阅消息 + for item in pub.listen(): + print("Listen on channel: %s" % item) + if item["type"] == "message" and item["data"].decode() == "over": + print(item["channel"].decode(), "已停止发布") + break + else: + # 另一种订阅模式 + while True: + item = pub.parse_response() + print("Listen on channel: %s" % item) + if item[0].decode() == "message" and item[2].decode() == "over": + print(item[1].decode(), "已停止发布") + break + + # 取消订阅 + pub.unsubscribe() + return + + +if __name__ == '__main__': + if sys.argv[1] == "public": + public_test() + else: + subscribe_test(int(sys.argv[2])) diff --git a/python_schedule.py b/python_schedule.py new file mode 100644 index 0000000..0366a17 --- /dev/null +++ b/python_schedule.py @@ -0,0 +1,53 @@ +# _*_ coding: utf-8 _*_ + +""" +调度的使用 +""" + +import time +import datetime +from threading import Timer +from apscheduler.schedulers.blocking import BlockingScheduler +from apscheduler.schedulers.background import BackgroundScheduler + + +def print_hello(): + print("TimeNow in func: %s" % (datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"))) + return + + +if __name__ == "__main__": + # 1. 使用Threading模块中的Timer + # t = Timer(2, print_hello) + # + # print("TimeNow start: %s" % (datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"))) + # t.start() + # print("TimeNow end: %s" % (datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"))) + # exit() + + # 2. BlockingScheduler:在进程中运行单个任务,调度器是唯一运行的东西, 采用阻塞的方式 + scheduler = BlockingScheduler() + + # 采用固定时间间隔(interval)的方式,每隔5秒钟执行一次 + scheduler.add_job(print_hello, "interval", seconds=5) + + # 采用date的方式,在特定时间只执行一次 + # scheduler.add_job(print_hello, "date", run_date=datetime.datetime.now() + datetime.timedelta(seconds=5)) + + # print("TimeNow start: %s" % (datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"))) + # scheduler.start() + # print("TimeNow end: %s" % (datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"))) + # exit() + + # 3. BackgroundScheduler: 适合于要求任何在程序后台运行的情况,当希望调度器在应用后台执行时使用。采用非阻塞的方式 + scheduler = BackgroundScheduler() + + # 采用固定时间间隔(interval)的方式,每隔3秒钟执行一次 + scheduler.add_job(print_hello, "interval", seconds=5) + + # 这是一个独立的线程 + # print("TimeNow start: %s" % (datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"))) + # scheduler.start() + # print("TimeNow end: %s" % (datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"))) + # while True: + # time.sleep(2) diff --git a/python_socket.py b/python_socket.py new file mode 100644 index 0000000..549a5f8 --- /dev/null +++ b/python_socket.py @@ -0,0 +1,80 @@ +# _*_ coding: utf-8 _*_ + +""" +Socket编程 +""" + +import sys +import socket + + +def server_func(port): + """ + 服务端 + """ + # 1. 创建socket对象 + server = socket.socket() + + # 2. 绑定ip和端口 + server.bind(("127.0.0.1", port)) + + # 3. 监听是否有客户端连接 + server.listen(10) + print("服务端已经启动%s端口......" % port) + + # 4. 接收客户端连接 + sock_obj, address = server.accept() + sock_obj.settimeout(3) + print("客户端:%s,超时时间:%s" % (address, sock_obj.gettimeout())) + + while True: + try: + # 5. 接收客户端发送的消息 + recv_data = sock_obj.recv(1024).decode("utf-8") + print("客户端端 -> 服务端: %s" % recv_data) + if recv_data == "quit": + break + + # 6. 给客户端回复消息 + send_data = "received[%s]" % recv_data + sock_obj.send(send_data.encode("utf-8")) + print("服务端 -> 客户端: %s" % send_data) + except Exception as excep: + print("error: ", excep) + + # 7. 关闭socket对象 + sock_obj.close() + server.close() + + +def client_func(port): + """ + 客户端 + """ + # 1. 创建客户端的socket对象 + client = socket.socket() + + # 2. 连接服务端, 需要指定端口和IP + client.connect(("127.0.0.1", port)) + + while True: + # 3. 给服务端发送数据 + send_data = input("客户端>").strip() + client.send(send_data.encode("utf-8")) + if send_data == "quit": + break + + # 4. 获取服务端返回的消息 + recv_data = client.recv(1024).decode("utf-8") + print("服务端 -> 客户端: %s" % recv_data) + + # 5. 关闭socket连接 + client.close() + + +if __name__ == '__main__': + flag = sys.argv[1] + if flag == "server": + server_func(9901) + else: + client_func(9901) diff --git a/test.png b/test.png new file mode 100644 index 0000000..77b79e9 Binary files /dev/null and b/test.png differ diff --git a/wxPython/hello_world.py b/wxPython/hello_world.py new file mode 100644 index 0000000..3a79415 --- /dev/null +++ b/wxPython/hello_world.py @@ -0,0 +1,93 @@ +# _*_ coding: utf-8 _*_ + +""" +Hello World +""" + +import wx + + +class HelloFrame(wx.Frame): + """ + A Frame that says Hello World + """ + + def __init__(self, *args, **kw): + # ensure the parent's __init__ is called + super(HelloFrame, self).__init__(*args, **kw) + + # create a panel in the frame + pnl = wx.Panel(self) + + # and put some text with a larger bold font on it + st = wx.StaticText(parent=pnl, label="Hello World!", pos=(25, 25)) + font = st.GetFont() + font.PointSize += 10 + font = font.Bold() + st.SetFont(font) + + # create a menu bar + self.make_menubar() + + # and a status bar + self.CreateStatusBar() + self.SetStatusText("Welcome to wxPython!") + + def make_menubar(self): + """ + A menu bar is composed of menus, which are composed of menu items. + This method builds a set of menus and binds handlers to be called + when the menu item is selected. + """ + # Make a file menu with Hello and Exit items + menu_file = wx.Menu() + # The "\t..." syntax defines an accelerator key that also triggers the same event + + item_hello = menu_file.Append(-1, "&Hello...\tCtrl-H", "Help string shown in status bar for this menu item") + menu_file.AppendSeparator() + + # When using a stock ID we don't need to specify the menu item's label + item_exit = menu_file.Append(wx.ID_EXIT) + + # Now a help menu for the about item + menu_help = wx.Menu() + item_about = menu_help.Append(wx.ID_ABOUT) + + # Make the menu bar and add the two menus to it. The '&' defines + # that the next letter is the "mnemonic" for the menu item. On the + # platforms that support it those letters are underlined and can be + # triggered from the keyboard. + menu_bar = wx.MenuBar() + menu_bar.Append(menu_file, "&File") + menu_bar.Append(menu_help, "&Help") + + # Give the menu bar to the frame + self.SetMenuBar(menu_bar) + + # Finally, associate a handler function with the EVT_MENU event for + # each of the menu items. That means that when that menu item is + # activated then the associated handler function will be called. + self.Bind(wx.EVT_MENU, self.OnHello, item_hello) + self.Bind(wx.EVT_MENU, self.OnExit, item_exit) + self.Bind(wx.EVT_MENU, self.OnAbout, item_about) + + def OnExit(self, event): + """Close the frame, terminating the application.""" + self.Close(True) + + def OnHello(self, event): + """Say hello to the user.""" + wx.MessageBox("Hello again from wxPython") + + def OnAbout(self, event): + """Display an About Dialog""" + wx.MessageBox("This is a wxPython Hello World sample", "About Hello World 2", wx.OK | wx.ICON_INFORMATION) + + +if __name__ == '__main__': + # When this module is run (not imported) then create the app, the + # frame, show it, and start the event loop. + app = wx.App() + frm = HelloFrame(None, title='Hello World 2') + frm.Show() + app.MainLoop()