Python3 如何開啟自帶http服務

開啟Web服務

1.基本方式

Python中自帶瞭簡單的服務器程序,能較容易地打開服務。

在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/) …”,表示在本機8000端口開啟瞭服務。

如果需要後臺運行,可在命令後加”&”符號,Ctrl+C不會關閉服務,如下:

python -m http.server &

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

nohup python -m http.server 8001

2.指定端口

如果不使用默認端口,可在開啟時附帶端口參數,如:

python -m http.server 8001

則會在8001端口打開http服務。

使用Web服務

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

也可以使用ifconfig命令查看本機IP並使用。

補充:python創建http服務

背景

用java調用dll的時候經常出現 invalid memory access,改用java-Python-dll,

Python通過http服務給java提供功能。

環境

Python3.7

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

打印日志

filename為輸入日志名稱,默認是同目錄下,沒有該文件會新創建

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")

調用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

拼接應答報文後,才能給瀏覽器正確返回

# coding:utf-8
import socket
from multiprocessing import Process
def handle_client(client_socket):
    # 獲取客戶端請求數據
    request_data = client_socket.recv(1024)
    print("request:", request_data)
    # 構造響應數據
    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)
    # 向客戶端返回響應數據
    client_socket.send(bytes(response, "utf-8"))
    # 關閉客戶端連接
    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 你的具體業務操作
               
            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 即可,當前目錄下生成

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

當時自己建瞭一個py叫http,刪掉後正常

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

另存為utf-8即可

以上為個人經驗,希望能給大傢一個參考,也希望大傢多多支持WalkonNet。

推薦閱讀: