Python 웹 프로젝트 Cherry py 사용법 미 러

1.소개
자바 웹 프로젝트 를 구축 하려 면 Tomcat 서버 가 있어 야 진행 할 수 있 습 니 다.파 이 썬 웹 프로젝트 를 구축 하 는 것 은 cherry py 자체 서버 이기 때문에 이 모듈 만 다운로드 하면 웹 프로젝트 개발 이 가능 하 다.
2.가장 기본 적 인 용법
구현 기능:html 페이지 에 접근 하고 단 추 를 누 르 면 배경 py 가 되 돌아 오 는 값 을 받 습 니 다.
html 페이지(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>
  <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 입 니 다.
애플 리 케 이 션 mounted at'에는 빈 config 가 있 습 니 다.설정 이 없 음 을 표시 하고 기본 설정 을 사용 합 니 다.필요 하 다 면 설정 할 수 있 습 니 다.
py 스 크 립 트 실행 후 브 라 우 저 입력 열기http://127.0.0.1:8080/혹은http://127.0.0.1:8080/indextest 를 볼 수 있 습 니 다.cheery.html

클릭 helloWorld 버튼 을 누 르 면 py 의 hello 에 접근 합 니 다.World 함수

해석:testcherry.html 중
function callHelloWorld() {
$.get('/hello_world', function (data, status) {
alert('data:' + data)
alert('status:' + status)
})}
1)요청/helloWorld 는 py 의 함수 이름과 일치 해 야 합 니 다.
2)기본 포트 는 8080 입 니 다.8080 이 점용 되면 다시 설정 할 수 있 습 니 다.
cherrypy.quickstart(TestCherry(),'/')설정 파 라미 터 를 수신 할 수 있 습 니 다
여러 번 디 버 깅 을 하면 portend.Timeout:Port 8080 not free on 127.0.0.1.오류
8080 포트 가 점용 되 었 기 때 문 입 니 다.첫 번 째 디 버 깅 에 성공 하면 작업 관리 자 를 열 어 python 프로 세 스 를 멈 출 수 있 습 니 다.8080 이 풀 려 납 니 다.
3.웹 브 라 우 저 를 가 져 와 디 버 깅 개발(브 라 우 저 를 자동 으로 열 고 웹 주 소 를 입력 할 수 있 음)
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 에 함수 추가(getparameters)

# -*- 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>
실행 결과
클릭 getparameters 단추 후
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"
들 어 오 는 인자 가 인쇄 되 어 있 음 을 알 수 있 습 니 다.

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()
프로젝트 폴 더

이상 이 바로 본 고의 모든 내용 입 니 다.여러분 의 학습 에 도움 이 되 고 저 희 를 많이 응원 해 주 셨 으 면 좋 겠 습 니 다.

좋은 웹페이지 즐겨찾기