最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Python Web項目Cherrypy使用方法鏡像

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

1、介紹

搭建Java Web項目,需要Tomcat服務(wù)器才能進(jìn)行。而搭建Python Web項目,因為cherrypy自帶服務(wù)器,所以只需要下載該模塊就能進(jìn)行Web項目開發(fā)。

2、最基本用法

實現(xiàn)功能:訪問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能請求到該函數(shù)
  def hello_world(self):
    print('Hello')
    return 'Hello World'

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


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

運行結(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

能看到啟動的路徑為127.0.0.1::8080端口號是8080

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

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

點擊hello_world按鈕,就會訪問py中的hello_world函數(shù)

解釋:test_cherry.html中

function callHelloWorld() {

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

alert('data:' + data)

alert('status:' + status)

})}

1)請求/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.錯誤

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

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

py代碼

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

import cherrypy
import webbrowser


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

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

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

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

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

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

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

import cherrypy
import webbrowser


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

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

html中添加一個新按鈕和對應(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>

運行結(jié)果

點擊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)打印出來了

5、config配置以及對應(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': {
      # 主機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,
      # 當(dāng)代碼變動時,是否自動重啟服務(wù),True==是,F(xiàn)alse==否
      # 設(shè)為True時,當(dāng)該PY代碼改變,服務(wù)會重啟
      'engine.autoreload.on': False
    },
    # 根目錄設(shè)置
    '/': {
      '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)})
  # 當(dāng)代碼變動時,是否重啟服務(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'
  # 啟動時調(diào)用函數(shù)
  cherrypy.engine.subscribe('start', service.auto_open)
  cherrypy.quickstart(service, '/', conf)


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

工程文件夾

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

相關(guān)文章

  • 詳解使用scrapy進(jìn)行模擬登陸三種方式

    詳解使用scrapy進(jìn)行模擬登陸三種方式

    這篇文章主要介紹了使用scrapy進(jìn)行模擬登陸三種方式,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2021-02-02
  • 基于Python的人臉檢測與分類過程詳解

    基于Python的人臉檢測與分類過程詳解

    這篇文章主要介紹了基于Python的人臉檢測與分類,算法分為兩個部分識別人臉位置和確定人臉分類,由于這兩項工作截然相反,所以我們使用了兩個網(wǎng)絡(luò)分別完成,詳細(xì)過程跟隨小編一起看看吧
    2022-05-05
  • pandas使用函數(shù)批量處理數(shù)據(jù)(map、apply、applymap)

    pandas使用函數(shù)批量處理數(shù)據(jù)(map、apply、applymap)

    這篇文章主要介紹了pandas使用函數(shù)批量處理數(shù)據(jù)(map、apply、applymap),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2020-11-11
  • 使用python判斷jpeg圖片的完整性實例

    使用python判斷jpeg圖片的完整性實例

    今天小編就為大家分享一篇使用python判斷jpeg圖片的完整性實例,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2019-06-06
  • PyQt5結(jié)合QtDesigner實現(xiàn)文本框讀寫操作

    PyQt5結(jié)合QtDesigner實現(xiàn)文本框讀寫操作

    本文將結(jié)合實例代碼,介紹PyQt5結(jié)合QtDesigner實現(xiàn)文本框讀寫操作,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2021-06-06
  • Python?讀取?.gz?文件全過程

    Python?讀取?.gz?文件全過程

    這篇文章主要介紹了Python?讀取?.gz?文件全過程,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2022-09-09
  • Python中Array特性與應(yīng)用實例深入探究

    Python中Array特性與應(yīng)用實例深入探究

    這篇文章主要為大家介紹了Python中Array特性與應(yīng)用實例深入探究,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪
    2024-01-01
  • Python結(jié)巴中文分詞工具使用過程中遇到的問題及解決方法

    Python結(jié)巴中文分詞工具使用過程中遇到的問題及解決方法

    這篇文章主要介紹了Python結(jié)巴中文分詞工具使用過程中遇到的問題及解決方法,較為詳細(xì)的講述了Python結(jié)巴中文分詞工具的下載、安裝、使用方法及容易出現(xiàn)的問題與相應(yīng)解決方法,需要的朋友可以參考下
    2017-04-04
  • 解決Django中checkbox復(fù)選框的傳值問題

    解決Django中checkbox復(fù)選框的傳值問題

    這篇文章主要介紹了解決Django中checkbox復(fù)選框的傳值問題,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2020-03-03
  • 深入淺析NumPy庫中的numpy.diag()函數(shù)

    深入淺析NumPy庫中的numpy.diag()函數(shù)

    通過本文的介紹,我們深入了解了NumPy庫中numpy.diag()函數(shù)的用法和應(yīng)用,從基本用法到高級特性,再到在線性代數(shù)中的應(yīng)用,我們逐步展示了numpy.diag()在處理對角矩陣和相關(guān)問題時的強大功能,需要的朋友可以參考下
    2024-05-05

最新評論

长治市| 曲松县| 黑河市| 思茅市| 上栗县| 错那县| 岚皋县| 洛阳市| 富阳市| 施甸县| 新民市| 勃利县| 景洪市| 凌海市| 南平市| 麻栗坡县| 青浦区| 津市市| 杭州市| 栖霞市| 开阳县| 陇南市| 隆林| 安塞县| 定西市| 定边县| 招远市| 两当县| 双鸭山市| 营口市| 阳春市| 西峡县| 闸北区| 惠来县| 濉溪县| 襄汾县| 垦利县| 武邑县| 陇川县| 靖远县| 唐河县|