Python教程

only using python to make web app

本文主要是介绍only using python to make web app,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

引子

对于python开发者不用学习前端的知识,也希望能够做前后端一体的web应用。

优点:

提高开发效率;

减少用人成本。

 

发展道路, 从简到繁。

 

dominate -- 后端静态HTML

https://github.com/Knio/dominate

纯粹产生前端HTML CSS代码.

 

Dominate is a Python library for creating and manipulating HTML documents using an elegant DOM API. It allows you to write HTML pages in pure Python very concisely, which eliminates the need to learn another template language, and lets you take advantage of the more powerful features of Python.

 

import dominate
from dominate.tags import *

doc = dominate.document(title='Dominate your HTML')

with doc.head:
    link(rel='stylesheet', href='style.css')
    script(type='text/javascript', src='script.js')

with doc:
    with div(id='header').add(ol()):
        for i in ['home', 'about', 'contact']:
            li(a(i.title(), href='/%s.html' % i))

    with div():
        attr(cls='body')
        p('Lorem ipsum..')

print(doc)

 

Eel -- 前端JS <-->后端Python

https://github.com/ChrisKnott/Eel#eello-world

进一步,可以实现前端互相通信,RPC级别的通信。

Eel is a little Python library for making simple Electron-like offline HTML/JS GUI apps, with full access to Python capabilities and libraries.

Eel hosts a local webserver, then lets you annotate functions in Python so that they can be called from Javascript, and vice versa.

Eel is designed to take the hassle out of writing short and simple GUI applications. If you are familiar with Python and web development, probably just jump to this example which picks random file names out of the given folder (something that is impossible from a browser).

 

<!DOCTYPE html>
<html>
  <head>
    <title>Hello, World!</title>

    <!-- Include eel.js - note this file doesn't exist in the 'web' directory -->
    <script type="text/javascript" src="/eel.js"></script>
    <script type="text/javascript">
      eel.expose(say_hello_js); // Expose this function to Python
      function say_hello_js(x) {
        console.log("Hello from " + x);
      }

      say_hello_js("Javascript World!");
      eel.say_hello_py("Javascript World!"); // Call a Python function
    </script>
  </head>

  <body>
    Hello, World!
  </body>
</html>

 

import eel

# Set web files folder and optionally specify which file types to check for eel.expose()
#   *Default allowed_extensions are: ['.js', '.html', '.txt', '.htm', '.xhtml']
eel.init('web', allowed_extensions=['.js', '.html'])

@eel.expose                         # Expose this function to Javascript
def say_hello_py(x):
    print('Hello from %s' % x)

say_hello_py('Python World!')
eel.say_hello_js('Python World!')   # Call a Javascript function

eel.start('hello.html')             # Start (this blocks and enters loop)

 

Dash -- 后端生成HTML, 并绑定数据

https://github.com/plotly/dash

Dash is the most downloaded, trusted Python framework for building ML & data science web apps.

Built on top of Plotly.js, React and Flask, Dash ties modern UI elements like dropdowns, sliders, and graphs directly to your analytical Python code. Read our tutorial (proudly crafted ❤️ with Dash itself).

  • Docs: Create your first Dash app in under 5 minutes

  • dash.gallery: Dash app gallery with Python & R code

 

https://dash.plotly.com/layout

# Run this app with `python app.py` and
# visit http://127.0.0.1:8050/ in your web browser.

from dash import Dash, html, dcc
import plotly.express as px
import pandas as pd

app = Dash(__name__)

# assume you have a "long-form" data frame
# see https://plotly.com/python/px-arguments/ for more options
df = pd.DataFrame({
    "Fruit": ["Apples", "Oranges", "Bananas", "Apples", "Oranges", "Bananas"],
    "Amount": [4, 1, 2, 2, 4, 5],
    "City": ["SF", "SF", "SF", "Montreal", "Montreal", "Montreal"]
})

fig = px.bar(df, x="Fruit", y="Amount", color="City", barmode="group")

app.layout = html.Div(children=[
    html.H1(children='Hello Dash'),

    html.Div(children='''
        Dash: A web application framework for your data.
    '''),

    dcc.Graph(
        id='example-graph',
        figure=fig
    )
])

if __name__ == '__main__':
    app.run_server(debug=True)

 

PyWebIO -- 后端不用关心HTML

https://github.com/pywebio/PyWebIO

以python开发者熟悉的方式,写web应用。

 

PyWebIO provides a series of imperative functions to obtain user input and output on the browser, turning the browser into a "rich text terminal", and can be used to build simple web applications or browser-based GUI applications without the need to have knowledge of HTML and JS. PyWebIO can also be easily integrated into existing Web services. PyWebIO is very suitable for quickly building applications that do not require complex UI.

 

 

Features:

  • Use synchronization instead of a callback-based method to get input
  • Non-declarative layout, simple and efficient
  • Less intrusive: old script code can be transformed into a Web application only by modifying the input and output operation
  • Support integration into existing web services, currently supports Flask, Django, Tornado, aiohttp, FastAPI framework
  • Support for asyncio and coroutine
  • Support data visualization with third-party libraries, e.g., plotly, bokeh, pyecharts.

 

from pywebio.input import input, FLOAT
from pywebio.output import put_text

def bmi():
    height = input("Your Height(cm):", type=FLOAT)
    weight = input("Your Weight(kg):", type=FLOAT)

    BMI = weight / (height / 100) ** 2

    top_status = [(14.9, 'Severely underweight'), (18.4, 'Underweight'),
                  (22.9, 'Normal'), (27.5, 'Overweight'),
                  (40.0, 'Moderately obese'), (float('inf'), 'Severely obese')]

    for top, status in top_status:
        if BMI <= top:
            put_text('Your BMI: %.1f, category: %s' % (BMI, status))
            break

if __name__ == '__main__':
    bmi()

 

https://www.pyweb.io/index.html

PyWebIO is made for:

Engineers and scientists to share domain knowledge and best practices through web apps.
Web developers to quickly prototype a demo or MVP.
Software teams to build internal tools.
Beginner programmers to learn Python through web development.

 

streamlit -- The fastest way to build data apps in Python

https://github.com/streamlit/streamlit

https://streamlit.io/

 

与pywebio不同,使用范围更加通用,这个框架是专门面向数据科学家。

The fastest way to build and share data apps.

Streamlit lets you turn data scripts into sharable web apps in minutes, not weeks. It’s all Python, open-source, and free! And once you’ve created an app you can use our cloud platform to deploy, manage, and share your app!

 

展示厅

https://streamlit.io/gallery

多种ML应用场景类型的例子。

 

表单提交页面:

https://streamlit-example-app-bug-report-streamlit-app-lrm3fx.streamlitapp.com/

 

丰富的控件API

https://docs.streamlit.io/library/api-reference

 

数据自动更新 -- 后台定时实现

https://blog.streamlit.io/how-to-build-a-real-time-live-dashboard-with-streamlit/

 

与dash对比

https://analyticsindiamag.com/streamlit-vs-plotlydash-comparison-with-python-examples/

 

与fastapi配合实现ML展示

https://github.com/davidefiocco/streamlit-fastapi-model-serving

https://davidefiocco.github.io/streamlit-fastapi-ml-serving/

 

这篇关于only using python to make web app的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!