Python Web项目Cherrypy使用方法镜像


Posted in Python onNovember 05, 2020

1、介绍

搭建Java Web项目,需要Tomcat服务器才能进行。而搭建Python Web项目,因为cherrypy自带服务器,所以只需要下载该模块就能进行Web项目开发。

2、最基本用法

实现功能:访问html页面,点击按钮后接收后台py返回的值

html页面(test_cherry.html)

<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8">
  <title>Test Cherry</title>
  <script src="https://cdn.staticfile.org/jquery/1.10.2/jquery.min.js"></script>
</head>

<body>

  <h1>Test Cherry</h1>
  <p id="p1"></p>
  <button type="button" onclick="callHelloWorld()">hello_world</button>
  <script>


    function callHelloWorld() {
      $.get('/hello_world', function (data, status) {
        alert('data:' + data)
        alert('status:' + status)

      })
    }



  </script>
</body>

</html>

编写脚本py

# -*- encoding=utf-8 -*-

import cherrypy


class TestCherry():
  @cherrypy.expose() # 保证html能请求到该函数
  def hello_world(self):
    print('Hello')
    return 'Hello World'

  @cherrypy.expose() # 保证html能请求到该函数http://127.0.0.1:8080/index
  def index(self): # 默认页为test_cherry.html
    return open(u'test_cherry.html')


cherrypy.quickstart(TestCherry(), '/')

运行结果

[27/May/2020:09:04:42] ENGINE Listening for SIGTERM.
[27/May/2020:09:04:42] ENGINE Bus STARTING
CherryPy Checker:
The Application mounted at '' has an empty config.

[27/May/2020:09:04:42] ENGINE Set handler for console events.
[27/May/2020:09:04:42] ENGINE Started monitor thread 'Autoreloader'.
[27/May/2020:09:04:42] ENGINE Serving on http://127.0.0.1:8080
[27/May/2020:09:04:42] ENGINE Bus STARTED

能看到启动的路径为127.0.0.1::8080端口号是8080

The Application mounted at '' has an empty config.表示没有自己配置,使用默认配置,如果需要可自己配置

运行py脚本后,打开浏览器输入http://127.0.0.1:8080/或者http://127.0.0.1:8080/index就可以看到test_cheery.html

Python Web项目Cherrypy使用方法镜像

点击hello_world按钮,就会访问py中的hello_world函数

Python Web项目Cherrypy使用方法镜像

解释:test_cherry.html中

function callHelloWorld() {

$.get('/hello_world', function (data, status) {

alert('data:' + data)

alert('status:' + status)

})}

1)请求/hello_world需要与py中的函数名一致

2)默认端口是8080,如果8080被占用,可以重新配置

cherrypy.quickstart(TestCherry(), '/')可以接收配置参数

若多次调试出现portend.Timeout: Port 8080 not free on 127.0.0.1.错误

是因为8080端口被占用了,如果你第一次调试时成功了,则你可以打开任务管理器把python进程停掉,8080就被释放了

3、导入webbrowser进行调试开发(可以自动打开浏览器,输入网址)

py代码

# -*- encoding=utf-8 -*-

import cherrypy
import webbrowser


class TestCherry():
  @cherrypy.expose() # 保证html能请求到该函数
  def hello_world(self):
    print('Hello')
    return 'Hello World'

  @cherrypy.expose() # 保证html能请求到该函数http://127.0.0.1:8080/index
  def index(self): # 默认页为test_cherry.html
    return open(u'test_cherry.html')

def auto_open():
  webbrowser.open('http://127.0.0.1:8080/')

cherrypy.engine.subscribe('start', auto_open) #启动前每次都调用auto_open函数
cherrypy.quickstart(TestCherry(), '/')

这样运行py就能自动打开网页了,每次改变html代码如果没达到预期效果,可以试一试清理浏览器缓存!!!

4、带参数的请求

实现传入参数并接收返回显示在html上

py中添加一个函数(get_parameters)

# -*- encoding=utf-8 -*-

import cherrypy
import webbrowser


class TestCherry():
  @cherrypy.expose() # 保证html能请求到该函数
  def hello_world(self):
    print('Hello')
    return 'Hello World'

  @cherrypy.expose() # 保证html能请求到该函数http://127.0.0.1:8080/index
  def index(self): # 默认页为test_cherry.html
    return open(u'test_cherry.html')
  @cherrypy.expose()
  def get_parameters(self, name, age, **kwargs):
    print('name:{}'.format(name))
    print('age:{}'.format(age))
    print('kwargs:{}'.format(kwargs))
    return 'Get parameters success'
def auto_open():
  webbrowser.open('http://127.0.0.1:8080/')
cherrypy.engine.subscribe('start', auto_open) # 启动前每次都调用auto_open函数
cherrypy.quickstart(TestCherry(), '/')

html中添加一个新按钮和对应按钮事件

<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8">
  <title>Test Cherry</title>
  <script src="https://cdn.staticfile.org/jquery/1.10.2/jquery.min.js"></script>
</head>

<body>

  <h1>Test Cherry</h1>
  <p id="p1"></p>
  <button type="button" onclick="callHelloWorld()">hello_world</button>
  <button type="button" id="postForParameters">get_parameters</button>
  <p id="getReturn"></p>
  <script>


    function callHelloWorld() {
      $.get('/hello_world', function (data, status) {
        alert('data:' + data)
        alert('status:' + status)

      })
    }

    $(document).ready(function () {

      $('#postForParameters').click(function () {
        alert('pst')
        $.post('/get_parameters',
          {
            name: 'TXT',
            age: 99,
            other: '123456'
          },
          function (data, status) {
            if (status === 'success') {
              $('#getReturn').text(data)
            }
          })
      })
    })
  </script>
</body>

</html>

运行结果

点击get_parameters按钮后

D:\Python37_32\python.exe D:/B_CODE/Python/WebDemo/test_cherry.py
[27/May/2020:09:58:40] ENGINE Listening for SIGTERM.
[27/May/2020:09:58:40] ENGINE Bus STARTING
CherryPy Checker:
The Application mounted at '' has an empty config.

[27/May/2020:09:58:40] ENGINE Set handler for console events.
[27/May/2020:09:58:40] ENGINE Started monitor thread 'Autoreloader'.
[27/May/2020:09:58:41] ENGINE Serving on http://127.0.0.1:8080
[27/May/2020:09:58:41] ENGINE Bus STARTED
127.0.0.1 - - [27/May/2020:09:58:41] "GET / HTTP/1.1" 200 1107 "" "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.61 Safari/537.36"
127.0.0.1 - - [27/May/2020:09:59:37] "GET / HTTP/1.1" 200 1136 "" "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.61 Safari/537.36"
127.0.0.1 - - [27/May/2020:09:59:37] "GET /favicon.ico HTTP/1.1" 200 1406 "http://127.0.0.1:8080/" "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.61 Safari/537.36"
127.0.0.1 - - [27/May/2020:10:02:50] "GET / HTTP/1.1" 200 1208 "" "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.61 Safari/537.36"
127.0.0.1 - - [27/May/2020:10:02:50] "GET /favicon.ico HTTP/1.1" 200 1406 "http://127.0.0.1:8080/" "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.61 Safari/537.36"
name:TXT
age:99
kwargs:{'other': '123456'}
127.0.0.1 - - [27/May/2020:10:02:54] "POST /get_parameters HTTP/1.1" 200 22 "http://127.0.0.1:8080/" "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.61 Safari/537.36"

能看出传入的参数已经打印出来了

Python Web项目Cherrypy使用方法镜像

5、config配置以及对应url(追加,所以代码不同了)

# -*- encoding=utf-8 -*-
import json
import os
import webbrowser
import cherrypy


class Service(object):
  def __init__(self, port):
    self.media_folder = os.path.abspath(os.path.join(os.getcwd(), 'media'))
    self.host = '0.0.0.0'
    self.port = int(port)
    self.index_html = 'index.html'
    pass

  @cherrypy.expose()
  def index(self):
    return open(os.path.join(self.media_folder, self.index_html), 'rb')

  def auto_open(self):
    webbrowser.open('http://127.0.0.1:{}/'.format(self.port))

  @cherrypy.expose()
  def return_info(self, sn):
    cherrypy.response.headers['Content-Type'] = 'application/json'
    cherrypy.response.headers['Access-Control-Allow-Origin'] = '*'
    my_dict = {'aaa':'123'}# 或者用list[]可保证有序
    return json.dumps(my_dict).encode('utf-8')


def main():

  service = Service(8090)
  conf = {
    'global': {
      # 主机0.0.0.0表示可以使用本机IP访问,如http://10.190.20.72:8090,可部署给别人访问
      # 否则只可以用http://127.0.0.1:8090
      'server.socket_host': service.host,
      # 端口号
      'server.socket_port': service.port,
      # 当代码变动时,是否自动重启服务,True==是,False==否
      # 设为True时,当该PY代码改变,服务会重启
      'engine.autoreload.on': False
    },
    # 根目录设置
    '/': {
      'tools.staticdir.on': True,
      'tools.staticdir.dir': service.media_folder
    },
    '/static': {
      'tools.staticdir.on': True,
      # 可以这么访问http://127.0.0.1:8090/static加上你的资源,例如
      # http://127.0.0.1:8090/static/js/jquery-1.11.3.min.js
      'tools.staticdir.dir': service.media_folder
    },

  }

  # 可以使用该种写法代替config配置
  # cherrypy.config.update(
  #     {'server.socket_port': service.port})
  # cherrypy.config.update(
  #     {'server.thread_pool': int(service.thread_pool_count)})
  # 当代码变动时,是否重启服务,True==是,False==否
  # cherrypy.config.update({'engine.autoreload.on': False})
  # 支持http://10.190.20.72:8080/形式
  # cherrypy.server.socket_host = '0.0.0.0'
  # 启动时调用函数
  cherrypy.engine.subscribe('start', service.auto_open)
  cherrypy.quickstart(service, '/', conf)


if __name__ == '__main__':
  pass
  main()

工程文件夹

Python Web项目Cherrypy使用方法镜像

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持三水点靠木。

Python 相关文章推荐
Python实现的Kmeans++算法实例
Apr 26 Python
python字典排序实例详解
May 20 Python
Python tornado队列示例-一个并发web爬虫代码分享
Jan 09 Python
django的登录注册系统的示例代码
May 14 Python
78行Python代码实现现微信撤回消息功能
Jul 26 Python
Python多进程原理与用法分析
Aug 21 Python
python pickle存储、读取大数据量列表、字典数据的方法
Jul 07 Python
Django使用中间件解决前后端同源策略问题
Sep 02 Python
python 实现仿微信聊天时间格式化显示的代码
Apr 17 Python
Keras 利用sklearn的ROC-AUC建立评价函数详解
Jun 15 Python
Python利用Turtle绘制哆啦A梦和小猪佩奇
Apr 04 Python
如何利用python实现列表嵌套字典取值
Jun 10 Python
Python实现异步IO的示例
Nov 05 #Python
Python requests HTTP验证登录实现流程
Nov 05 #Python
Python包资源下载路径报404解决方案
Nov 05 #Python
如何一键升级Python所有包
Nov 05 #Python
python实现磁盘日志清理的示例
Nov 05 #Python
Python常用外部指令执行代码实例
Nov 05 #Python
Python Pandas数据分析工具用法实例
Nov 05 #Python
You might like
PHP chmod 函数与批量修改文件目录权限
2010/05/10 PHP
显示youtube视频缩略图和Vimeo视频缩略图代码分享
2014/02/13 PHP
php获取POST数据的三种方法实例详解
2016/12/20 PHP
PHP框架Laravel中实现supervisor执行异步进程的方法
2017/06/07 PHP
Laravel框架生命周期与原理分析
2018/06/12 PHP
使用jscript实现二进制读写脚本代码
2008/06/09 Javascript
JavaScript中使用正则匹配多条,且获取每条中的分组数据
2010/11/30 Javascript
javascript hashtable 修正版 下载
2010/12/30 Javascript
JS 两日期相减,获得天数的小例子(兼容IE,FF)
2013/07/01 Javascript
js里取容器大小、定位、距离等属性搜集整理
2013/08/19 Javascript
中文输入法不触发onkeyup事件的解决办法
2014/07/09 Javascript
AngularJS实现元素显示和隐藏的几个案例
2015/12/09 Javascript
jQuery实现伪分页的方法分享
2016/02/17 Javascript
谈一谈JS消息机制和事件机制的理解
2016/04/14 Javascript
jQuery插件实现图片轮播特效
2016/06/16 Javascript
jQuery实现查找链接文字替换属性的方法
2016/06/27 Javascript
JQuery对ASP.NET MVC数据进行更新删除
2016/07/13 Javascript
vue省市区三联动下拉选择组件的实现
2017/04/28 Javascript
[05:00]第二届DOTA2亚洲邀请赛主赛事第三天比赛集锦.mp4
2017/04/04 DOTA
python psutil库安装教程
2018/03/19 Python
python寻找list中最大值、最小值并返回其所在位置的方法
2018/06/27 Python
浅谈python 读excel数值为浮点型的问题
2018/12/25 Python
python获取全国城市pm2.5、臭氧等空气质量过程解析
2019/10/12 Python
使用wxpy实现自动发送微信消息功能
2020/02/28 Python
Pycharm pyuic5实现将ui文件转为py文件,让UI界面成功显示
2020/04/08 Python
python 基于UDP协议套接字通信的实现
2021/01/22 Python
毕业生自我鉴定实例
2014/01/21 职场文书
创建青年文明号材料
2014/05/09 职场文书
好人好事演讲稿
2014/09/01 职场文书
代领学位证书毕业证书委托书
2014/09/30 职场文书
党员干部廉洁自律承诺书
2015/04/28 职场文书
《天净沙·秋思》教学反思三篇
2019/11/02 职场文书
导游词之塘栖古镇
2019/12/04 职场文书
React配置子路由的实现
2021/06/03 Javascript
Python+tkinter实现高清图片保存
2022/03/13 Python
《游戏王:大师决斗》新活动上线 若无符合卡组可免费租用
2022/04/13 其他游戏