一种快速简单的小型web应用微框架

py4js的Python项目详细描述


PY4JS

py4js是一个快速简单的小型web应用程序微框架。它的目标是让你 以简单易懂的方式使用web应用程序。

使用它,您不需要知道http协议,也不需要知道python如何与javascript通信。可以在javascript中使用python函数,就像使用本地javascript函数一样。

使用步骤

步骤1

安装py4js包:pip install py4jspip3 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,您将看到警报消息: image

很简单,是吗?

服务器

服务器参数

服务器有几个可指定的启动参数,例如:

NameDescription
hostServer address to bind to(default: ^{}). Pass ^{} to listens on all services including the external one.
portServer port to bind to(default: 5000). Values below 1024 require root privileges. if port is None, server will use a random port.
serverSpecify the server adapter to use. For more details: Server adapter. (default: ^{}, others: ^{}/^{}/^{}/^{}/^{}.etc).
service_packageA 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 ^{}, also you can change it to another name if you like.
js_routethe path of JavaScript for browser to load.
access_control_allow_origindefault: ^{} , all cross domain requests are allowed.

服务器适配器

由于py4js服务器基于bottle,因此内置的默认服务器基于wsgiref wsgiserver。当服务器负载增加时,此非线程http服务器可能会成为性能瓶颈。 所以最好使用不同的服务器,要么是多线程的,要么支持异步IO。

Bottle为最常见的wsgi服务器提供了许多现成的适配器,例如: cherrypypastewaitressgeventeventlettornadotwisted等。 用法:

  1. 服务员

    frompy4jsimportServerServer(server='waitress').run()

    如果尚未安装waitress包,请首先通过pip install waitresspip3 install waitress安装它。

  2. gevent

    fromgeventimportmonkeyfrompy4jsimportServermonkey.patch_all()Server(server='gevent').run()

    如果尚未安装gevent软件包,请首先通过pip install geventpip3 install gevent安装它。
    由于gevent是异步的,服务器可以非常快,可以处理几乎无限数量的并发连接,并且易于管理。

欢迎加入QQ群-->: 979659372 Python中文网_新手群

推荐PyPI第三方库


热门话题
java需要设置框架。可设置大小(false)以重新绘制()   java我对PDF文件感到困惑   为什么是太阳。jvm。热点。调试器。DebuggerException:无法打开二进制文件`?   设置结果为textview时出现java空指针异常   我应该使用什么同步原语在Java中实现事件驱动程序框架?   java为什么WindowClosing处理程序在退出程序之前不执行后台任务?   如何将“20170712T18:43:04.000Z”转换为安卓或java中的相对时间?   Java,获取按键的时间长度,currentTimeMillies()始终为24   maven构建的java可执行Jar找不到logback。xml   java在其外部的函数中使用for循环中的值   java如何以表格格式将不同长度的数据对齐   java Play 2.5 WebSocket连接构建   maven而非eclipse的java强制转换问题   java如何在JFreeChart中使X轴上的值水平?   构建Java Windows应用程序以访问在线MySQL数据库需要什么   java添加构造函数会出错吗?这没有道理,请帮忙,编程问题   java在一个jframe中的两个JPanel中使用两个绘制方法   java数学或逻辑问题   java如何复制Androids库存摄像头方向更改