一种快速简单的小型web应用微框架
py4js的Python项目详细描述
PY4JS
py4js是一个快速简单的小型web应用程序微框架。它的目标是让你 以简单易懂的方式使用web应用程序。
使用它,您不需要知道http协议,也不需要知道python如何与javascript通信。可以在javascript中使用python函数,就像使用本地javascript函数一样。
使用步骤
步骤1
安装py4js包:pip install py4js
或pip3 install py4js
步骤2
首先,创建一个名为service的包,然后在包中创建一个python文件,例如hello.py
:
defsay_hello(name):""" say hello test :param name: :return: """return'Hello %s!'%name
步骤3
创建与服务包处于同一级别的python文件,例如main.py
:
frompy4jsimportServerServer().run()
然后运行它(默认情况下,服务器将在端口5000
启动wsgiref服务器。您还可以使用其他端口和wsgi服务器)。
步骤4
在任何地方创建一个html文件,例如index.html
:
<!DOCTYPE html><htmllang="en"><head><metacharset="UTF-8"><title>hello</title><scriptsrc="http://localhost:5000/service.js"></script></head><body><script>service.hello.say_hello('World',function(data){alert(data);});</script></body></html>
在浏览器中打开index.html
,您将看到警报消息:
很简单,是吗?
服务器
服务器参数
服务器有几个可指定的启动参数,例如:
Name | Description |
---|---|
host | Server address to bind to(default: ^{ |
port | Server port to bind to(default: 5000). Values below 1024 require root privileges. if port is None, server will use a random port. |
server | Specify the server adapter to use. For more details: Server adapter. (default: ^{ |
service_package | A package that will be scanned by the server. All modules and public functions in the package will be loaded as service for JavaScript. Default package name is ^{ |
js_route | the path of JavaScript for browser to load. |
access_control_allow_origin | default: ^{ |
服务器适配器
由于py4js服务器基于bottle,因此内置的默认服务器基于wsgiref wsgiserver。当服务器负载增加时,此非线程http服务器可能会成为性能瓶颈。 所以最好使用不同的服务器,要么是多线程的,要么支持异步IO。
Bottle为最常见的wsgi服务器提供了许多现成的适配器,例如:
cherrypy
、paste
、waitress
、gevent
、eventlet
、tornado
、twisted
等。
用法:
服务员
frompy4jsimportServerServer(server='waitress').run()
如果尚未安装
waitress
包,请首先通过pip install waitress
或pip3 install waitress
安装它。gevent
fromgeventimportmonkeyfrompy4jsimportServermonkey.patch_all()Server(server='gevent').run()
如果尚未安装
gevent
软件包,请首先通过pip install gevent
或pip3 install gevent
安装它。
由于gevent
是异步的,服务器可以非常快,可以处理几乎无限数量的并发连接,并且易于管理。