亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

Python Web項(xiàng)目Cherrypy使用方法鏡像

 更新時(shí)間:2020年11月05日 15:10:41   作者:南風(fēng)丶輕語(yǔ)  
這篇文章主要介紹了Python Web項(xiàng)目Cherrypy使用方法鏡像,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下

1、介紹

搭建Java Web項(xiàng)目,需要Tomcat服務(wù)器才能進(jìn)行。而搭建Python Web項(xiàng)目,因?yàn)閏herrypy自帶服務(wù)器,所以只需要下載該模塊就能進(jìn)行Web項(xiàng)目開(kāi)發(fā)。

2、最基本用法

實(shí)現(xiàn)功能:訪問(wèn)html頁(yè)面,點(diǎn)擊按鈕后接收后臺(tái)py返回的值

html頁(yè)面(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能請(qǐng)求到該函數(shù)
  def hello_world(self):
    print('Hello')
    return 'Hello World'

  @cherrypy.expose() # 保證html能請(qǐng)求到該函數(shù)http://127.0.0.1:8080/index
  def index(self): # 默認(rèn)頁(yè)為test_cherry.html
    return open(u'test_cherry.html')


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

運(yùn)行結(jié)果

[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

能看到啟動(dòng)的路徑為127.0.0.1::8080端口號(hào)是8080

The Application mounted at '' has an empty config.表示沒(méi)有自己配置,使用默認(rèn)配置,如果需要可自己配置

運(yùn)行py腳本后,打開(kāi)瀏覽器輸入http://127.0.0.1:8080/或者h(yuǎn)ttp://127.0.0.1:8080/index就可以看到test_cheery.html

點(diǎn)擊hello_world按鈕,就會(huì)訪問(wèn)py中的hello_world函數(shù)

解釋:test_cherry.html中

function callHelloWorld() {

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

alert('data:' + data)

alert('status:' + status)

})}

1)請(qǐng)求/hello_world需要與py中的函數(shù)名一致

2)默認(rèn)端口是8080,如果8080被占用,可以重新配置

cherrypy.quickstart(TestCherry(), '/')可以接收配置參數(shù)

若多次調(diào)試出現(xiàn)portend.Timeout: Port 8080 not free on 127.0.0.1.錯(cuò)誤

是因?yàn)?080端口被占用了,如果你第一次調(diào)試時(shí)成功了,則你可以打開(kāi)任務(wù)管理器把python進(jìn)程停掉,8080就被釋放了

3、導(dǎo)入webbrowser進(jìn)行調(diào)試開(kāi)發(fā)(可以自動(dòng)打開(kāi)瀏覽器,輸入網(wǎng)址)

py代碼

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

import cherrypy
import webbrowser


class TestCherry():
  @cherrypy.expose() # 保證html能請(qǐng)求到該函數(shù)
  def hello_world(self):
    print('Hello')
    return 'Hello World'

  @cherrypy.expose() # 保證html能請(qǐng)求到該函數(shù)http://127.0.0.1:8080/index
  def index(self): # 默認(rèn)頁(yè)為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) #啟動(dòng)前每次都調(diào)用auto_open函數(shù)
cherrypy.quickstart(TestCherry(), '/')

這樣運(yùn)行py就能自動(dòng)打開(kāi)網(wǎng)頁(yè)了,每次改變html代碼如果沒(méi)達(dá)到預(yù)期效果,可以試一試清理瀏覽器緩存?。?!

4、帶參數(shù)的請(qǐng)求

實(shí)現(xiàn)傳入?yún)?shù)并接收返回顯示在html上

py中添加一個(gè)函數(shù)(get_parameters)

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

import cherrypy
import webbrowser


class TestCherry():
  @cherrypy.expose() # 保證html能請(qǐng)求到該函數(shù)
  def hello_world(self):
    print('Hello')
    return 'Hello World'

  @cherrypy.expose() # 保證html能請(qǐng)求到該函數(shù)http://127.0.0.1:8080/index
  def index(self): # 默認(rèn)頁(yè)為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) # 啟動(dòng)前每次都調(diào)用auto_open函數(shù)
cherrypy.quickstart(TestCherry(), '/')

html中添加一個(gè)新按鈕和對(duì)應(yīng)按鈕事件

<!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>

運(yùn)行結(jié)果

點(diǎn)擊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"

能看出傳入的參數(shù)已經(jīng)打印出來(lái)了

5、config配置以及對(duì)應(yīng)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': {
      # 主機(jī)0.0.0.0表示可以使用本機(jī)IP訪問(wèn),如http://10.190.20.72:8090,可部署給別人訪問(wèn)
      # 否則只可以用http://127.0.0.1:8090
      'server.socket_host': service.host,
      # 端口號(hào)
      'server.socket_port': service.port,
      # 當(dāng)代碼變動(dòng)時(shí),是否自動(dòng)重啟服務(wù),True==是,F(xiàn)alse==否
      # 設(shè)為True時(shí),當(dāng)該P(yáng)Y代碼改變,服務(wù)會(huì)重啟
      'engine.autoreload.on': False
    },
    # 根目錄設(shè)置
    '/': {
      'tools.staticdir.on': True,
      'tools.staticdir.dir': service.media_folder
    },
    '/static': {
      'tools.staticdir.on': True,
      # 可以這么訪問(wèn)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)})
  # 當(dāng)代碼變動(dòng)時(shí),是否重啟服務(wù),True==是,F(xiàn)alse==否
  # cherrypy.config.update({'engine.autoreload.on': False})
  # 支持http://10.190.20.72:8080/形式
  # cherrypy.server.socket_host = '0.0.0.0'
  # 啟動(dòng)時(shí)調(diào)用函數(shù)
  cherrypy.engine.subscribe('start', service.auto_open)
  cherrypy.quickstart(service, '/', conf)


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

工程文件夾

以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

  • 利用Python實(shí)現(xiàn)去重聚合Excel數(shù)據(jù)并對(duì)比兩份數(shù)據(jù)的差異

    利用Python實(shí)現(xiàn)去重聚合Excel數(shù)據(jù)并對(duì)比兩份數(shù)據(jù)的差異

    在數(shù)據(jù)處理過(guò)程中,常常需要將多個(gè)數(shù)據(jù)表進(jìn)行合并,并進(jìn)行比對(duì),以便找出數(shù)據(jù)的差異和共同之處,本文將介紹如何使用 Pandas 庫(kù)對(duì)兩個(gè) Excel 數(shù)據(jù)表進(jìn)行合并與比對(duì),需要的可以參考下
    2023-11-11
  • Django實(shí)現(xiàn)聊天機(jī)器人

    Django實(shí)現(xiàn)聊天機(jī)器人

    本文基于channels + websocket結(jié)合Celery和Python爬蟲技術(shù)打造了一個(gè)會(huì)算術(shù)懂詩(shī)文的聊天機(jī)器人,是非常難得的一個(gè)Django綜合應(yīng)用項(xiàng)目哦,感興趣的朋友可以參考下
    2021-05-05
  • Python 之pandas庫(kù)的安裝及庫(kù)安裝方法小結(jié)

    Python 之pandas庫(kù)的安裝及庫(kù)安裝方法小結(jié)

    Pandas 是一種開(kāi)源的、易于使用的數(shù)據(jù)結(jié)構(gòu)和Python編程語(yǔ)言的數(shù)據(jù)分析工具,它與 Scikit-learn 兩個(gè)模塊幾乎提供了數(shù)據(jù)科學(xué)家所需的全部工具,今天通過(guò)本文給大家介紹Python 之pandas庫(kù)的安裝及庫(kù)安裝方法小結(jié),感興趣的朋友跟隨小編一起看看吧
    2022-11-11
  • pytorch 求網(wǎng)絡(luò)模型參數(shù)實(shí)例

    pytorch 求網(wǎng)絡(luò)模型參數(shù)實(shí)例

    今天小編就為大家分享一篇pytorch 求網(wǎng)絡(luò)模型參數(shù)實(shí)例,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧
    2019-12-12
  • Python制作數(shù)據(jù)分析透視表的方法詳解

    Python制作數(shù)據(jù)分析透視表的方法詳解

    透視表是一種可以對(duì)數(shù)據(jù)動(dòng)態(tài)排布并且分類匯總的表格格式,在常用的python的數(shù)據(jù)分析非標(biāo)準(zhǔn)庫(kù)pandas中體現(xiàn)為pivot_table模塊。本文主要介紹了如何實(shí)現(xiàn)制作數(shù)據(jù)分析透視表,需要的可以參考一下
    2022-09-09
  • 全面介紹python中很常用的單元測(cè)試框架unitest

    全面介紹python中很常用的單元測(cè)試框架unitest

    這篇文章主要介紹了python中很常用的單元測(cè)試框架unitest的相關(guān)資料,幫助大家更好的利用python進(jìn)行單元測(cè)試,感興趣的朋友可以了解下
    2020-12-12
  • 一文教會(huì)你調(diào)整Matplotlib子圖的大小

    一文教會(huì)你調(diào)整Matplotlib子圖的大小

    Matplotlib的可以把很多張圖畫到一個(gè)顯示界面,這就設(shè)計(jì)到面板切分成一個(gè)一個(gè)子圖,下面這篇文章主要給大家介紹了關(guān)于調(diào)整Matplotlib子圖大小的相關(guān)資料,文中通過(guò)實(shí)例代碼介紹的非常詳細(xì),需要的朋友可以參考下
    2022-06-06
  • Python中的Descriptor描述符學(xué)習(xí)教程

    Python中的Descriptor描述符學(xué)習(xí)教程

    簡(jiǎn)單來(lái)說(shuō),數(shù)據(jù)描述符是指實(shí)現(xiàn)了__get__、__set__、__del__方法的類屬性,等效于定義了三個(gè)方法的接口,下面就來(lái)詳細(xì)看一下Python中的Descriptor修飾符學(xué)習(xí)教程
    2016-06-06
  • Python3.遍歷某文件夾提取特定文件名的實(shí)例

    Python3.遍歷某文件夾提取特定文件名的實(shí)例

    下面小編就為大家分享一篇Python3.遍歷某文件夾提取特定文件名的實(shí)例,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧
    2018-04-04
  • Python的代理類實(shí)現(xiàn),控制訪問(wèn)和修改屬性的權(quán)限你都了解嗎

    Python的代理類實(shí)現(xiàn),控制訪問(wèn)和修改屬性的權(quán)限你都了解嗎

    這篇文章主要為大家詳細(xì)介紹了Python的代理類實(shí)現(xiàn),控制訪問(wèn)和修改屬性的權(quán)限,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下,希望能夠給你帶來(lái)幫助
    2022-03-03

最新評(píng)論