Python小型web服务 web.py 简单教程

最近有个项目需要通过Java调用Python的服务,有考虑过gRPC,那是一个很好的框架,通信效率高。但是基于够用就好的原则,决定选择使用简单的HTTP通信方式,Python建立服务器,公开JSON API,Java通过API方式调用Python的服务,下面是web.py的简单使用教程。

web.py

web.py 是一个Python 的web 框架,它简单而且功能强大。

安装web.py

pip install web.py

Demo代码

下面的代码实现的功能是,调用http://localhost:8080/upper/TEXT,返回TEXT对应的大写。调用http://localhost:8080/lower/TEXT,返回TEXT对应的小写。

import web
urls = (
    '/upper/(.*)', 'upper',
    '/lower/(.*)', 'lower'
)
app = web.application(urls, globals())
class upper:
    def GET(self, text):
        print('input:' + text)
        return text.upper()

class lower:
    def GET(self, text):
        print('input:' + text)
        return text.lower()

if __name__ == "__main__":
    app.run()
测试

http://localhost:8080/upper/Wiki
http://localhost:8080/lower/Wiki

HTML模板

我们开发除了API外,HTML也是常用,在templates文件夹下创建一个名称叫做hello.html的文件。

$def with (content)
<html>
<body>
<p>识别结果:$content</p>
</body>
</html>

hello.html的名称很重要,和下面的render.hello是对应的,$content是传入的参数名称。

import web
urls = (
    '/upper_html/(.*)', 'upper_html'
)
app = web.application(urls, globals())
render = web.template.render('templates/')
class upper_html:
    def GET(self, text):
        print('input:' + text)
        return render.hello(content=text.upper())
if __name__ == "__main__":
    app.run()
测试

http://localhost/upper_html/Wiki

图片、js、css等静态资源的引用

images目录下放一张image.jpg的图片
修改HTML

$def with (content)
<html>

<body>
<p>识别结果:$content</p>
<img src="/images/image.jpg" width="400">
</body>
</html>

修改python代码,下面增加的代码的意思是,把包含jscssimages路径的请求,返回静态资源,但是通常建议使用nginx来实现静态资源。

import web
urls = (
    '/upper_html/(.*)', 'upper_html',
    '/(js|css|images)/(.*)', 'static'
)
app = web.application(urls, globals())
render = web.template.render('templates/')
class upper_html:
    def GET(self, text):
        print('input:' + text)
        return render.hello(content=text.upper())

class static:
    def GET(self, media, file):
        try:
            f = open(media+'/'+file, 'r')
            return f.read()
        except:
            return ''

if __name__ == "__main__":
    app.run()
测试

http://localhost/upper_html/Wiki

项目结构

├── images
│   └── image.jpg
├── templates
│   └── hello.html
├── web_demo.py

猜你喜欢

转载自blog.csdn.net/weixin_33845477/article/details/87069383
今日推荐