欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Python Web项目Cherrypy使用方法镜像

程序员文章站 2022-03-27 20:51:05
1、介绍搭建java web项目,需要tomcat服务器才能进行。而搭建python web项目,因为cherrypy自带服务器,所以只需要下载该模块就能进行web项目开发。2、最基本用法实现功能:访...

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使用方法镜像

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