濮阳杆衣贸易有限公司

主頁 > 知識庫 > Python3 如何開啟自帶http服務(wù)

Python3 如何開啟自帶http服務(wù)

熱門標(biāo)簽:沈陽人工外呼系統(tǒng)價格 武漢外呼系統(tǒng)平臺 沈陽外呼系統(tǒng)呼叫系統(tǒng) 沈陽防封電銷卡品牌 如何申請400電話費(fèi)用 江西省地圖標(biāo)注 富錦商家地圖標(biāo)注 池州外呼調(diào)研線路 外呼系統(tǒng)哪些好辦

開啟Web服務(wù)

1.基本方式

Python中自帶了簡單的服務(wù)器程序,能較容易地打開服務(wù)。

在python3中將原來的SimpleHTTPServer命令改為了http.server,使用方法如下:

1. cd www目錄

2. python -m http.server

開啟成功,則會輸出“Serving HTTP on 0.0.0.0 port 8000 (http://0.0.0.0:8000/) …”,表示在本機(jī)8000端口開啟了服務(wù)。

如果需要后臺運(yùn)行,可在命令后加""符號,Ctrl+C不會關(guān)閉服務(wù),如下:

python -m http.server 

如果要保持服務(wù),則在命令前加nohup以忽略所有掛斷信號,如下:

nohup python -m http.server 8001

2.指定端口

如果不使用默認(rèn)端口,可在開啟時附帶端口參數(shù),如:

python -m http.server 8001

則會在8001端口打開http服務(wù)。

使用Web服務(wù)

可以使用http://0.0.0.0:8000/查看www目錄下的網(wǎng)頁文件,若無index.html則會顯示目錄下的文件。

也可以使用ifconfig命令查看本機(jī)IP并使用。

補(bǔ)充:python創(chuàng)建http服務(wù)

背景

用java調(diào)用dll的時候經(jīng)常出現(xiàn) invalid memory access,改用java-Python-dll,

Python通過http服務(wù)給java提供功能。

環(huán)境

Python3.7

通過 http.server.BaseHTTPRequestHandler 來處理請求,并返回response

打印日志

filename為輸入日志名稱,默認(rèn)是同目錄下,沒有該文件會新創(chuàng)建

filemode a 是追加寫的模式,w是覆蓋寫

import logging
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s',
    filename="hhh.txt",
    filemode='a'
)
logging.info("xxxx")

調(diào)用dll

pchar - ctypes.c_char_p

integer 用了 bytes(0),byref(ctypes.c_void_p(0)) 都OK,沒有更深入去研究,如有錯誤請指正。

import ctypes
from ctypes import *
dll = ctypes.windll.LoadLibrary('C:\\xxx\\xxx.dll')
print("dll版本號為 : "+ str(dll.GetVersion()) )
 name = ctypes.c_char_p(b"gc")
            roomno = ctypes.c_char_p(bytes(room.encode("utf-8")))
            begintime = ctypes.c_char_p(bytes(begin.encode("utf-8")))
            endtime = ctypes.c_char_p(bytes(end.encode("utf-8")))
            cardno = ctypes.c_void_p(0)
            dll.invoke...

http方案一

要注意 必須有 response = response_start_line + response_headers + “\r\n” + response_body

拼接應(yīng)答報文后,才能給瀏覽器正確返回

# coding:utf-8
import socket
from multiprocessing import Process
def handle_client(client_socket):
    # 獲取客戶端請求數(shù)據(jù)
    request_data = client_socket.recv(1024)
    print("request:", request_data)
    # 構(gòu)造響應(yīng)數(shù)據(jù)
    response_start_line = "HTTP/1.1 200 OK\r\n"
    response_headers = "Server: My server\r\n"
    response_body = "helloWorld!"
    response = response_start_line + response_headers + "\r\n" + response_body
    print("response:", response)
    # 向客戶端返回響應(yīng)數(shù)據(jù)
    client_socket.send(bytes(response, "utf-8"))
    # 關(guān)閉客戶端連接
    client_socket.close()
if __name__ == "__main__":
    server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    server_socket.bind(("", 8888))
    server_socket.listen(120)
    print("success")
    while True:
        client_socket, client_address = server_socket.accept()
        print("[%s, %s]用戶連接上了" % client_address)
        handle_client_process = Process(target=handle_client, args=(client_socket,))
        handle_client_process.start()
        client_socket.close()

完整代碼

另外一種http方式

#-.- coding:utf-8 -.-
from http.server import  HTTPServer
import ctypes
from ctypes import *
# HTTPRequestHandler class
import http.server
import socketserver
import logging
# pyinstaller -F
class testHTTPServer_RequestHandler(http.server.BaseHTTPRequestHandler):
    # GET
  def do_GET(self):
        logging.error('start make ')
        str2 =  str(self.path)
        print("revice: " + str2)
        if "xxx" in str2:
            # todo 你的具體業(yè)務(wù)操作
               
            if "xxx" in str2:
                print("hahaha")
                logging.error('hahaha')
                # response_body = "0"
                self.send_response(200)
                # Send headers
                self.send_header('Content-type','text/html')
                self.end_headers()
                # Send message back to client
                message = "Hello world!"
                # Write content as utf-8 data
                self.wfile.write(bytes(message, "utf8"))
                return
        else:
            print("1else")
            self.send_response(200)
            # Send headers
            self.send_header('Content-type', 'text/html')
            self.end_headers()
            # Send message back to client
            message = "Hello world222333!"
            # Write content as utf-8 data
            self.wfile.write(bytes(message, "utf8"))
            return
            
def run():
  print('starting server...')
  logging.basicConfig(
      level=logging.INFO,
      format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s',
      filename="http_make_card.txt",
      filemode='a+'
  )
  # Server settings
  server_address = ('127.0.0.1', 8888)
  httpd = HTTPServer(server_address, testHTTPServer_RequestHandler)
  print('running server...')
  httpd.serve_forever()
run()

打包exe

pip install pyinstaller

pyinstaller -F xxx.py 即可,當(dāng)前目錄下生成

1、No module named ‘http.server'; ‘http' is not a package

當(dāng)時自己建了一個py叫http,刪掉后正常

2、UnicodeDecodeError: ‘utf-8' codec can't decode byte 0xce in position 130: invalid continuat

另存為utf-8即可

以上為個人經(jīng)驗(yàn),希望能給大家一個參考,也希望大家多多支持腳本之家。

您可能感興趣的文章:
  • Python中使用aiohttp模擬服務(wù)器出現(xiàn)錯誤問題及解決方法
  • Python如何實(shí)現(xiàn)自帶HTTP文件傳輸服務(wù)
  • Python3搭建http服務(wù)器的實(shí)現(xiàn)代碼
  • Python搭建HTTP服務(wù)過程圖解
  • 使用python快速在局域網(wǎng)內(nèi)搭建http傳輸文件服務(wù)的方法
  • 淺析使用Python搭建http服務(wù)器
  • Python代碼實(shí)現(xiàn)http/https代理服務(wù)器的腳本

標(biāo)簽:通遼 黑龍江 株洲 常德 呂梁 阿里 潛江 銅川

巨人網(wǎng)絡(luò)通訊聲明:本文標(biāo)題《Python3 如何開啟自帶http服務(wù)》,本文關(guān)鍵詞  Python3,如何,開啟,自帶,http,;如發(fā)現(xiàn)本文內(nèi)容存在版權(quán)問題,煩請?zhí)峁┫嚓P(guān)信息告之我們,我們將及時溝通與處理。本站內(nèi)容系統(tǒng)采集于網(wǎng)絡(luò),涉及言論、版權(quán)與本站無關(guān)。
  • 相關(guān)文章
  • 下面列出與本文章《Python3 如何開啟自帶http服務(wù)》相關(guān)的同類信息!
  • 本頁收集關(guān)于Python3 如何開啟自帶http服務(wù)的相關(guān)信息資訊供網(wǎng)民參考!
  • 推薦文章
    长岛县| 临汾市| 邳州市| 天镇县| 阜平县| 清苑县| 汽车| 公安县| 常宁市| 潮安县| 石渠县| 贞丰县| 汉川市| 类乌齐县| 桐柏县| 晋城| 登封市| 冷水江市| 醴陵市| 防城港市| 东阿县| 荣昌县| 宁晋县| 德安县| 玛多县| 西盟| 卢氏县| 湖南省| 钦州市| 象州县| 阆中市| 富平县| 慈利县| 平谷区| 郑州市| 太和县| 邯郸市| 尚义县| 平和县| 同德县| 新河县|